Recently I came into contact with a lot of interview related content, so I specially organized the following, including: Java, MyBatis, ZooKeeper, Dubbo, Elasticsearch, Memcached, Redis, MySQL, Spring, Spring Boot, Spring Cloud, RabbitMQ, Kafka, Linux Technology stack. There will be a special interview video, welcome to pay attention to.

ElasticSearch

1. Actual production problems

How many shards are there, how many are there, and how many tuning methods are there? Truthfully combined with their own practice can be answered. For example, the ES cluster architecture has 13 nodes, the index is 20+ index according to channel, increasing by 20+ index per day according to date, index: 10 fragments, increasing by 100 million + data per day, index size control per channel per day: within 150GB index level 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 aliases 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. Adopt the life cycle management of index for curator; 6. Set the word segmentation reasonably only for the fields that need word segmentation; 7. In the Mapping stage, the attributes of each field are fully combined to determine whether it needs to be retrieved and stored. … … .

1.2. Write tuning

1. Set the number of copies before writing to 0. 2. Before writing, disable refresh_interval and set it to -1. 3. During 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. Disable batch terms (hundreds of scenarios); 3. Make full use of the inverted index mechanism and try to keyword type; 4, when the amount of data is large, you can first finalize the index based on time and then search; 5. Set a proper routing mechanism.

1.4. Other tuning

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

2. What is the inverted index

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 has appeared 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 footprint. 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 do if index data is too much, how to tune and deploy

The planning of index data should be well planned in the early stage, just as the so-called “design first, coding later”, so as to effectively avoid the impact of sudden data surge on online customer search or other businesses caused by insufficient cluster processing capacity. How to tune, as mentioned in Question 1, is detailed here:

3.1 Dynamic index Level

Create index based on template + time + Rollover API rolling, example: design phase definition: blog index template format: 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 node and other planning is reasonable, dynamic new machines can be completed without restarting the cluster.

4, How to implement Master election?

  1. For Elasticsearch, the ZenDiscovery module is responsible for Ping (the RPC used by 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) by the nodeId dictionary. Each election is based on the order of the nodes that it knows, and then select the first node (0th bit).
  3. If the number of votes for a node reaches a certain value (n/2+1) and the node elects itself, that node is master. Otherwise, a new election will be held until the above conditions are met.
  4. Note: The master node is responsible for cluster, node, and index management, not document level management. The data node can turn off HTTP functionality *.

5, Describe the process of Elasticsearch indexing documents in detail

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)
Copy the code

How about Elasticsearch?

The search is decomposed into two phases: “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 with 10 shards, one of which will be hit in one request.
  2. Each fragment is queried locally, and the results are 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 setup at deployment time

A machine with 64 GB of ram is ideal, but 32 GB and 16 GB machines are 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 an 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 in close proximity. Clustering across large geographical distances is definitely avoided.

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

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

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.

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 lot 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

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. And you can add more

Set index.translog.flush_threshold_size 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 don’t 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.

8. What is the internal structure of Lucence?

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.

9. Actual scene problems

What if 10 of the 20 Elasticsearch nodes select one master and the other 10 select another master?

1. When the number of master candidates in the cluster is not less than 3, you can solve the split brain problem 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 the master candidate can be changed, and the other candidates can be used as data nodes to avoid the brain-splitting problem.

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

The TransportClient uses the Transport module to remotely connect to an ElasticSearch cluster. 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 shard node receives a request from the coordinator node, it writes the request to the Memory Buffer and then to the Filesystem Cache periodically (every second by default). This process from Momery Buffer 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.

  4. 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 indexes are composed of multiple segments, which themselves are a fully functional inverted index.
  2. Segments are 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 small 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 also write operations, but documents in Elasticsearch are immutable and therefore cannot be deleted or changed to show their 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 the document, and when the update is performed, the old version of the document is marked as deleted in the.del file, and the new version of the 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 as a two-phase 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 data is still stored in Memory Buffer, 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, where the coordination node identifies which documents need to be fetched and submits multiple GET requests to the related 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. *

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

1. The index of inverted dictionary needs to be resident in memory and cannot be GC. It needs to monitor the growth trend of segment memory on data node.

Set the appropriate 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. Is there heap space available for other tasks? Avoid using clear Cache to free memory. Avoid searches and aggregations 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. 4. Cluster STATS resides in the memory and cannot be horizontally expanded. The super-large cluster can be divided into multiple clusters connected by the tribe Node. 5. To determine whether heap is sufficient, the heap usage of a cluster must be continuously monitored based on actual application scenarios.

15. How to realize the aggregation of large amount of data (hundreds 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.

16, How to ensure read/write consistency for Elasticsearch in concurrent mode?

Optimistic concurrency control can be used by version numbers to ensure that the new version is not overwritten by the old version, leaving the application layer to handle specific conflicts; In addition, for write operations, the consistency level supports quorum/ One /all, which defaults to quorum, that is, 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 the 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.

17. 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.

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

19. Do you know dictionary trees?

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. 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.

1. As you can see, 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. 2, implementation: for each node to open a letter set size array, each node to hang a linked list, using left son and right brother notation to record the tree; 3. 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).

20. 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(x,y) = d(y,x) — the distance from x to y is the same as the distance from y to x d(x,y) + d(y,z) >= d(x,z) — triangle inequality

1. According to the triangle inequality, if the distance between query and another character is within the range of N, the distance between B and 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

The parent node is “book” and the two children, “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 for edges labeled d-n to D + N (inclusive) 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. For example, if you enter cape and the maximum tolerance distance is 1, then you calculate d(” book “, “cape”)=4, and then you find cake, which is 3 to 5 away from the root. Calculate d(” cake “, “cape”)=1, so return cake, then find the cart node that is 0 to 2 away from cake, find cape and cart node respectively, and get cape.

~ Well, the length reason ES related interview questions we will introduce here oh! Welcome to focus on zan plus collection oh!