preface

Recently in view of the Internet company interview asked knowledge points, summed up the Java programmer interview involves most of the interview questions and answers to share with you, I hope to help you review before the interview and find a good job, but also save you on the Internet to search for information time to learn.

Content covers: Java, MyBatis, ZooKeeper, Dubbo, Elasticsearch, Memcached, Redis, MySQL, Spring, SpringBoot, SpringCloud, RabbitMQ, Kafka, Linux and other technology stacks.

Full version Java interview questions address: Java backend questions integration

How many shards do you have in your es cluster? How many shards do you have in your es cluster?

Interviewer: I want to know the application scenario and scale of ES that the applicant contacted with before, and whether he has done large-scale index design, planning and tuning. Answer: truthfully combined with their own practice scenarios can be answered. For example, the ES cluster architecture has 13 nodes, and the index is 20+ index according to channel. The index is increased by 20+ index according to date, and the index is 10 fragments, and the index is increased by 100 million + data every day. The index size of each channel is controlled within 150GB. Indexing-only tuning means:

1.1. Optimization in the design stage

(1) Create indexes based on date templates and roll over API according to incremental service requirements;

(2) Use alias for index management;

(3) Perform force_merge operations on indexes at dawn every day to release space.

(4) Adopt cold and hot separation mechanism to store hot data on SSD to improve retrieval efficiency; Cold data is periodically shrink to reduce storage;

(5) life cycle management of index is adopted.

(5) Set the word segmentation reasonably only for the fields requiring word segmentation;

(6) In the Mapping stage, attributes of each field are fully combined to determine whether retrieval and storage are needed. … .

1.2. Write tuning

(1) The number of copies before writing is set to 0;

(2) Before writing, disable refresh_interval to -1 and refresh mechanism;

(3) In the writing process, bulk writing is adopted;

(4) Restore the number of copies and refresh interval after writing;

(5) Use automatically generated ids whenever possible.

1.3. Query tuning

(1) Disable wildcard.

(2) Disable batch terms (hundreds of scenarios);

(3) Make full use of the inverted index mechanism to keyword as much as possible;

(4) When the amount of data is large, the index can be determined based on time before retrieval;

(5) Set a reasonable routing mechanism.

1.4. Other tuning

(1) Deployment tuning, business tuning, etc.

As part of the above, the interviewer will have a general assessment of your previous practice or operations experience.

Interviewer: I want to know your understanding of basic concepts.

Answer: A simple explanation is ok. Traditionally, our retrieval is to find the position of corresponding keywords through the article one by one. The inverted index, through the word segmentation strategy, forms the mapping relation table between words and articles, and this dictionary + mapping table is the inverted index. With the inverted index, it can realize o (1) time complexity of the efficient retrieval of articles, greatly improving the retrieval efficiency.

The academic solution: an inverted index, as opposed to which words are included in an article, starts with a word and records which documents that word appears in. It consists of two parts — a dictionary and an inverted list. The underlying implementation of inversion indexes is based on: FST (Finite State) data structure. The data structure that Lucene has used extensively since version 4+ is FST.

FST has two advantages:

(1) Small space occupation. By reusing the prefixes and suffixes of words in the dictionary, the storage space is reduced.

(2) Fast query speed. O(len(STR)) query time complexity.

(3) How to adjust and deploy elasticSearch index data

Interviewer: I want to know the operation and maintenance ability of large data volume. Answer: Index data planning, should do a good job in the early planning, is the so-called “design first, coding after”, so as to effectively avoid the sudden data surge caused by the cluster processing capacity insufficient online customer search or other business affected. How to tune, as mentioned in Question 1, is detailed here:

3.1 Dynamic index Level

Create index based on template + time + Rollover API scrolling, for example: Design phase definition: blog index template format is: blog_index_ timestamp form, increasing data every day. The advantage of this is that the data volume does not surge so that the data volume of a single index is very large, close to the 32nd power -1 of upper limit 2, and the index storage reaches TB+ or even larger. Once a single index is large, storage and other risks come with it, so think ahead + avoid early.

3.2 Storage Layer

Hot data (for example, data generated in the latest three days or one week) is stored separately, and other data is stored separately. If cold data is not written to new data, you can periodically perform force_merge plus shrink compression to save storage space and search efficiency.

3.3 Deployment Layer

Once there is no planning, this is a contingency strategy. Combined with the dynamic expansion feature of ES itself, dynamic new machines can relieve the cluster pressure. Note: if the master nodes are properly planned before, dynamic new machines can be completed without restarting the cluster.

How does ElasticSearch implement master voting

Interviewer: To understand the underlying principles of ES clustering, not just the business level.

Answer:

Prerequisites:

(1) Only the candidate primary node (master: true) can become the primary node.

(2) The minimum number of primary nodes (MIN_master_nodes) is designed to prevent brain splitting. This I looked at a variety of online analysis of the version and source code analysis of the books, clouds in the fog. Select the Master node and return the corresponding Master node successfully, otherwise return null. The election process is roughly described as follows:

Step 1: Ensure the number of candidate primary nodes is up to the specified value of elasticSearch. yml: discovery.zen.minimum_master_nodes; Comparison: determine whether master is qualified first, and those with candidate master node qualification will be returned first; If both nodes are candidate primary nodes, the value with a small ID is the primary node. Note that the id here is of type string. Off-topic: how to get the node ID. 1GET /_cat/nodes? v&h=ip,port,heapPercent,heapMax,id,name2ip port heapPercent heapMax id name

Select * from Elasticsearch; select * from Elasticsearch

Interviewer: To understand the underlying principle of ES, not just the business level.

Answer: The index document here should be understood as the document writing ES, the process of creating the index. Document writing includes single document writing and bulk writing. This section describes the process of single document writing. Remember this diagram from the official documentation.

Step 1: The customer writes data to a node in the cluster and sends a request. (If no routing/coordination node is specified, the requested node acts as the routing node.) Step 2: After node 1 receives the request, it uses the document id to determine that the document belongs to Shard 0. The request will be forwarded to another node, let’s say node 3. Therefore, the primary shard of shard 0 is allocated to node 3. Step 3: Node 3 performs a write operation on the master shard. If successful, the request is forwarded to the replica shards of node 1 and node 2 in parallel and waits for the result to return. All replica shards report success, node 3 reports success to the coordinator node (node 1), and node 1 reports success to the requesting client. If the interviewer asks again: How do you get sharded documents in step 2? A: Obtained by the routing algorithm. The routing algorithm is the process of calculating the target fragment ID based on the route and document ID. 1shard = hash(_routing) % (num_of_primary_shards)

Description of Elasticsearch search process in detail

Interviewer: You want to understand the underlying principles of ES search, not just the business level. Answer: The search is decomposed into two phases of “Query then fetch”. The purpose of the Query phase is to locate the position without fetching it.

The steps are as follows:

(1) Suppose an index data has 5 master +1 copies in total 10 shards, one of which will be hit in one request.

(2) Each fragment is queried locally, and the result is returned to the local ordered priority queue.

(3) The results of step 2 are sent to the coordination node, which produces a global sorted list. The purpose of the FETCH phase is to fetch data. The routing node retrieves all documents and returns them to the client.

7. How to optimize the Linux Settings for Elasticsearch deployment

Interviewer: I want to know the operation and maintenance capability of ES cluster.

Answer:

(1) Disable cache swap;

(2) The heap memory is set to Min (node memory /2, 32GB);

(3) Set the maximum number of file handles;

(4) Adjust thread pool + queue size according to business needs;

(5) Disk storage RAID mode – Raid 10 is used to improve the performance of a single node and avoid storage failures of a single node.

8. What is the internal structure of Lucence?

Interviewer: I want to know the breadth and depth of your knowledge.

Answer:

Lucene is an index and search process, including index creation, index, and search. You can build on that a little bit. Elasticsearch and search engine related questions, and my own answers.

How does Elasticsearch implement Master voting?

(1) Elasticsearch is selected by ZenDiscovery module, which consists of Ping (the RPC between nodes to find each other) and Unicast (the Unicast module contains a host list to control which nodes need to be pinged). (2) Sort all nodes that can become master (node.master: true) according to the nodeId dictionary, each election of each node in the order of known nodes, then select the first (0) node, for the moment it is considered as the master node. (3) If the number of votes for a node reaches a certain value (n/2+1) and the node elects itself, then the node is master. Otherwise, a new election will be held until the above conditions are met. (4) Supplement: The master node is responsible for cluster, node and index management, not document-level management; The data node can turn off HTTP functionality *.

10 select a master from Elasticsearch and 10 select another master from Elasticsearch

(1) When the number of master candidates in the cluster is not less than 3, the split brain problem can be solved by setting the minimum number of votes (discovery.zen.minimum_master_nodes) to exceed half of all candidate nodes.

(2) When the number of candidates is two, only one master candidate can be modified, and the other candidates can be used as data nodes to avoid the problem of brain splitting.

11. How do clients select specific nodes to execute requests when connecting to the cluster?

(1) TransportClient remotely connects to an ElasticSearch cluster using the Transport module. It does not join the cluster, but simply obtains one or more initialized transport addresses and communicates with them in a polling manner.

Describe the process of indexing documents for Elasticsearch.

By default, the coordination node participates in the calculation using the document ID (routing is also supported) to provide the appropriate shard for the route. shard = hash(document_id) % (num_of_primary_shards)

(1) When the node where the shard is located receives the request from the coordination node, it writes the request to the MemoryBuffer, and then writes the request to the Filesystem Cache periodically (every second by default). This process from MomeryBuffer to Filesystem Cache is called refresh;

(2) Of course, in some cases, Momery Buffer and Filesystem Cache data may be lost. ES ensures data reliability through the translog mechanism. The data in Filesystem cache is flushed when the data is written to disk.

(3) During Flush, the buffer in memory is cleared, the content is written to a new segment, the segment’s fsync creates a new commit point and flusher the content to disk, and the old translog is deleted and a new translog is started.

Flush is triggered when it is timed (default: 30 minutes) or when translog becomes too large (default: 512 MB).

Addendum: About Lucene seinterfaces:

(1) Lucene index is composed of multiple segments, and the segment itself is a fully functional inverted index.

The (2) segment is immutable, allowing Lucene to incrementally add new documents to the index without rebuilding the index from scratch.

(3) For each search request, all segments in the index are searched, and each segment consumes CPU clock cycles, file handles, and memory. This means that the higher the number of segments, the lower the search performance.

(4) To solve this problem, Elasticsearch merges segments into a larger segment, commits the new merged segments to disk, and removes those old segments.

Describe how Elasticsearch updates and deletes documents.

(1) Delete and update are write operations, but Elasticsearch documents are immutable and cannot be deleted or changed to show changes.

(2) Each segment on disk has a corresponding.del file. When the delete request is sent, the document is not actually deleted, but is marked as deleted in the.del file. The document will still match the query, but will be filtered out of the results. When segments are merged, documents marked as deleted in the. Del file will not be written to the new segment.

(3) When a new document is created, Elasticsearch assigns a version number to that document. When the update is performed, the old document is marked as deleted in the.del file and the new document is indexed to a new segment. Older versions of documents still match the query, but are filtered out of the results.

Describe the Elasticsearch process in detail.

(1) The search is executed in a two-stage process called Query Then Fetch;

(2) During the initial query phase, the query is broadcast to each shard copy (master shard or replica shard) in the index. Each shard performs a search locally and builds a priority queue matching documents of size from + size. PS: Filesystem Cache is queried during search, but some of the data is still in the MemoryBuffer, so the search is performed in near real time.

(3) Each shard returns the IDS and sorting values of all documents in its own priority queue to the coordination node, which merges these values into its own priority queue to generate a global sorted result list.

(4) Next comes the fetch phase, in which the coordination node identifies which documents need to be retrieved and submits multiple GET requests to the relevant shard. Each shard loads and enriches the document, then returns the document to the coordination node if necessary. Once all documents have been retrieved, the coordination node returns the result to the client.

(5) Supplementary: The search type of Query Then Fetch refers to the data of the fragment when scoring the document relevance, which may not be accurate when the number of documents is small. DFS Query Then Fetch adds a pre-query processing. Ask Term and Document Frequency, this score is more accurate, but performance deteriorates. *

In Elasticsearch, how do YOU find an inverted index based on a word?

SEE:

· Lucene index file format (1)

· Lucene index file format (2)

What are the optimizations for Linux Settings when Elasticsearch is deployed?

(1) MACHINES with 64 GB of ram are ideal, but 32 GB and 16 GB machines are also common. Less than 8 GB is counterproductive.

(2) If you have to choose between faster CPUs and more cores, more cores is better. The extra concurrency provided by multiple cores far outweighs a slightly faster clock rate.

(3) If you can afford SSD, it will go far beyond any rotating media. Ssd-based nodes have improved query and index performance. SSDS are a good choice if you can afford them.

(4) Avoid clustering across multiple data centers, even if they are close by. Clustering across large geographical distances is definitely avoided.

(5) Make sure that the JVM running your application is exactly the same as the server’s JVM. In several places in Elasticsearch, Java’s native serialization is used.

(6) Setting gateway.recover_after_nodes, gateway.expected_nodes, and gateway.recover_after_time can avoid excessive fragment exchanges when the cluster restarts. This could reduce data recovery from hours to seconds.

(7) Elasticsearch is configured to use unicast discovery by default to prevent nodes from unintentionally joining the cluster. Only nodes running on the same machine automatically form a cluster. It is best to use unicast instead of multicast.

(8) Do not arbitrarily change the size of the garbage collector (CMS) and individual thread pools.

(9) Give Lucene (less than) half of your memory (but no more than 32 GB!) , set by the ES_HEAP_SIZE environment variable.

(10) Swapping memory to disk is fatal to server performance. If memory is swapped to disk, a 100 microsecond operation can become 10 milliseconds. And think about all those 10 microseconds of operating delays that add up. It’s not hard to see how awful performance considerations are.

(11) Lucene uses a large number of files. Elasticsearch also uses a lot of sockets to communicate between nodes and HTTP clients. All of this requires sufficient file descriptors. You should increase your file descriptor and set it to a large value, such as 64,000. Added: Index phase performance enhancement method

(1) Use bulk requests and resize them: 5-15 MB per batch is a good starting point.

(2) Storage: USE SSD

(3) Segments and merge: The default value for Elasticsearch is 20 MB/s, which should be a good setting for mechanical disks. If you’re using SSD, consider going up to 100-200 MB/s. If you’re doing bulk imports and don’t care about search at all, you can turn merge limiting off completely. You can also increase the index.translog.flush_threshold_size setting from the default of 512 MB to a larger value, such as 1 GB, which accumulates larger segments in the transaction log during a flush trigger.

(4) If your search results do not require near-real-time accuracy, consider changing the index.refresh_interval for each index to 30s. (5) If you are doing bulk imports, consider turning off replicas by setting index.number_of_replicas: 0.

17. What do you need to know about using Elasticsearch for GC?

(1) SEE: elasticsearch. Cn/article / 32

(2) The index of inverted dictionary needs to be resident in memory and cannot be GC, so the growth trend of Segmentmemory on data node needs to be monitored.

(3) Set a reasonable size for all types of caches, such as field cache, filter cache, indexing cache, bulk queue, etc., and determine whether the heap is sufficient in the worst-case scenario, i.e., when all types of caches are full. Is there heap space available for other tasks? Avoid using clear Cache to free memory.

(4) Avoid search and aggregation that return a large number of result sets. The Scan & Scroll API can be used for scenarios that require a large amount of data pulling.

(5) Cluster STATS resides in memory and cannot be expanded horizontally. The super-large cluster can be divided into multiple clusters to be connected through the tribe Node.

(6) To know whether the heap is sufficient, we must combine the actual application scenarios and continuously monitor the heap usage of the cluster.

18, How to implement Elasticsearch aggregation for large data (tens of millions of magnitude)?

The first approximation aggregation provided by Elasticsearch is cardinality metrics. It provides the cardinality of a field, the number of distinct or unique values for that field. It is based on the HLL algorithm. HLL will first for our input hash algorithm, and then according to the result of the hash operation base of the bits do probability estimation is obtained. It features configurable precision to control memory usage (more precision = more memory); Small data sets are very accurate; We can configure parameters to set the fixed amount of memory required for deduplication. Whether unique values are in the thousands or billions, the amount of memory used depends only on the precision of your configuration.

19, What does Elasticsearch do to ensure read-write consistency in concurrent cases?

(1) Optimistic concurrency control can be used by version number to ensure that the new version will not be overwritten by the old version, and the application layer handles specific conflicts;

(2) In addition, for write operations, the consistency level supports quorum/ One /all, which defaults to quorum, i.e. write operations are allowed only when most shards are available. But even if most are available, there may be a failure to write to the copy due to network reasons, so that the copy is considered faulty and the shard is rebuilt on a different node.

(3) For read operations, you can set Replication to sync(the default), so that the operation is returned only after both master and replica sharding is complete; If Replication is set to ASYNc, you can also query the master shard by setting the search request parameter _preference to primary to ensure that the document is the latest version.

20. How do I monitor the Elasticsearch cluster status?

Marvel makes it easy to monitor Elasticsearch via Kibana. You can view your cluster health and performance in real time, as well as analyze past cluster, index, and node metrics.

21. Introduce the overall technical architecture of your e-commerce search.

22. Tell me about your personalized search solution.

SEE implements personalized search based on Word2vec and Elasticsearch

23, Do you know dictionary tree?

The common dictionary data structure is as follows:The core idea of Trie is to use the common prefix of the string to reduce the cost of query time to improve efficiency. It has three basic properties:

(1) The root node contains no characters, and each node except the root node contains only one character.

(2) From the root node to a node, the characters on the path are connected to the string corresponding to the node.

(3) All children of each node contain different characters.(4) It can be seen that the number of nodes at each level of the trie tree is 26^ I. So to save space, we can also use dynamic linked lists, or we can use arrays to simulate dynamics. And space costs no more than the number of words times the length of words. (5) Implementation: for each node to open a letter set size array, each node to hang a linked list, using the left son and right brother notation to record the tree; (6) For The Chinese dictionary tree, the child nodes of each node are stored in a hash table, so as not to waste too much space, and the query speed can retain the complexity of the hash O(1).

24. How is spelling correction implemented?

(1) Spelling correction is based on editing distance; Edit distance is a standard method of representing the minimum number of operation steps required to convert from one string to another through insert, delete, and replace operations.

(2) Calculation process of edit distance: For example, to calculate the edit distance of Batyu and Beauty, first create a 7×8 table (batyu length is 5, coffee length is 6, add 2 for each), and then fill in the following positions with black numbers. The other cells are computed by taking the minimum of the following three values: the upper-left digit if the uppermost character is equal to the left-most character. Otherwise, the top left digit +1. (0 for 3,3) the left digit +1 (2 for 3,3 cells) the top digit +1 (2 for 3,3 cells) finally takes the lower right value which is the value of the edit distance 3.

For spelling correction, we consider constructing a Metric Space in which any relation satisfies three basic conditions:

D (x,y) = 0 — if the distance between x and y is 0, then x=y

D of x,y is equal to d of y,x — the distance from x to y is the same thing as the distance from y to x

D (x,y) + d(y,z) >= d(x,z) — Triangle inequality

(1) According to the triangle inequality, then another character whose distance from Query is within the range of N is transferred to B, and its distance from A is at most D + N and at least D-n.

(2) The construction process of BK tree is as follows: each node has any child nodes, and each edge has a value to represent the editing distance. The edge of all child nodes to the parent node is marked with n to indicate that the editing distance is exactly N. For example, we have a tree whose parent is “book” and two children are “cake” and “books”. The edge from “book” to “books” is numbered 1, and the edge from “book” to “cake” is numbered 4. After constructing the tree from the dictionary, whenever you want to insert a new word, calculate the edit distance of the word from the root node and look for edges with a value of D (neweord, root). The recursion is compared to each child node until there are no children, and you can create a new child node and store the new word there. For example, to insert “boo” into the tree in the example above, we first examine the root node, looking for the edge where D (” book “, “boo”) = 1, and then examine the children of the edge numbered 1 to get the word “books”. We calculate the distance D (” books “, “boo”)=2 and insert the new word after “books” with the edge number 2.

(3) Query similar words as follows: calculate the editing distance D between the word and the root node, and then recursively search the edges labeled d-n to D + N (including) of each child node. If the distance d between the checked node and the search word is less than n, the node is returned and the query continues. Cake (” cape “, “cape”)=1 if the maximum tolerance distance is 1, then d(” book “, “cape”)=4 and d(” book “, “cape”)= 5 and d(” cake “, “cape”)=1 So I’m going to return cake, and then I’m going to find the cape and cart nodes that are 0 to 2 away from cake, and I’m going to get cape.