preface
Elasticsearch has attracted more and more attention as enterprises demand near-real-time search. It is widely used by Internet companies such as Alibaba, Tencent and JD.com, as well as traditional enterprises such as Ping An and SF Express. Most Elasticsearch features were paid for before the release of Elasticsearch 6.8. The open source version of Elasticsearch has limited cluster management capabilities. A common implementation solution is to add a layer gateway to control Elasticsearch.
Java Oop, Java Collections containers, Java exceptions, concurrent programming, Java reflection, Java serialization, JVM, Redis, Spring MVC, MyBatis, MySQL database, messaging middleware MQ, Dubbo, Linux, ZooKeeper, distributed & data structure and algorithm, etc. 25 thematic technical points, are all small editor in each big factory summary of the interview real questions, there have been many fans with this PDF to win many big factory offer. Today, here is a summary to share to everyone! [Finished]
The full version of the Java interview questions address: 2021 latest interview questions collection collection.
The serial number | project | content | link |
---|---|---|---|
1 | The middleware | Java Middleware (2021) | Juejin. Cn/post / 694870… |
2 | Micro service | Java Microservices (2021) | Juejin. Cn/post / 694906… |
3 | Concurrent programming | Concurrent Programming in Java (2021 latest Edition) | Juejin. Cn/post / 695053… |
4 | Java based | Java Basics (2021) | Juejin. Cn/post / 695062… |
5 | Spring Boot | Spring Boot Interview Questions (2021 Latest edition) | Juejin. Cn/post / 695137… |
6 | Redis | Redis Interview Questions (2021 Latest edition) | Juejin. Cn/post / 695166… |
7 | Spring MVC | Spring MVC (2021) | Juejin. Cn/post / 695166… |
8 | Spring Cloud | Spring Cloud Interview Questions (2021) | Juejin. Cn/post / 695245… |
9 | MySQL optimization | MySQL optimize interview questions (2021 latest edition) | Juejin. Cn/post / 695246… |
10 | JVM | JVM Performance Tuning Interview questions (2021 Latest Edition) | Juejin. Cn/post / 695246… |
11 | Linux | Linux Interview Questions (2021 latest edition) | Juejin. Cn/post / 695287… |
12 | Mybatis | Mybatis (2021 latest Edition) | Juejin. Cn/post / 695287… |
13 | Network programming | TCP, UDP, Socket, Http Network programming interview (2021 latest edition) | Juejin. Cn/post / 695287… |
14 | Design patterns | Design Mode Interview Questions (2021 Latest edition) | Juejin. Cn/post / 695544… |
15 | Big data | 100 Big Data Interview Questions (2021 latest edition) | Juejin. Cn/post / 695544… |
16 | Tomcat | Tomcat Interview Questions (2021 Latest edition) | Juejin. Cn/post / 695570… |
17 | multithreading | Multithreaded Interview Questions (2021 Latest edition) | Juejin. Cn/editor/draf… |
18 | Nginx | Nginx_BIO_NIO_AIO interview Questions (2021 Latest edition) | Juejin. Cn/editor/draf… |
19 | memcache | Memcache Interview Questions (2021 latest edition) | Juejin. Cn/post / 695608… |
20 | Java exception | Java Exception Interview Questions (2021 Latest edition) | Juejin. Cn/post / 695644… |
21 | The Java virtual machine | Java Virtual Machine Interview (2021 latest edition) | Juejin. Cn/post / 695658… |
22 | Java collection | Java Set Interview Questions (2021 Latest edition) | Juejin. Cn/post / 695684… |
23 | Git Git | Git Command (2021) | Juejin. Cn/post / 695692… |
24 | Elasticsearch | Elasticsearch (2021 Latest Edition) | Juejin. Cn/post / 695840… |
25 | Dubbo | Dubbo Interview Questions (2021 Latest edition) | Juejin. Cn/post / 695842… |
Elasticsearch interview questions
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.
(6) Set the word segmentation reasonably only for the fields requiring word segmentation;
(7) 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
- Deployment tuning, business tuning, etc.
- As part of the above, the interviewer will have a general assessment of your previous practice or operations experience.
What is the inverted index of ElasticSearch
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.
Select * from elasticSearch; select * from elasticSearch
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 rolling, example: design phase definition: blog index template format: blog_index_ timestamp form, increasing data every day. The advantage of this method is that the data volume of a single index is not very large, which is close to the 32th 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.
How does ElasticSearch implement master voting
1GET /_cat/nodes? V&h = IP, port, heapPercent heapMax, id, name 2 IP port heapPercent heapMax id name copy codeCopy the code
5, Describe the process of Elasticsearch indexing documents in detail
How about Elasticsearch?
Interviewer: You want to understand the underlying principles of ES search, not just the business level.
Answer:
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 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.
How to optimize 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.
How does Elasticsearch implement Master voting?
(1) The main selection of Elasticsearch is performed by ZenDiscovery module, which consists of Ping (the RPC between nodes to discover each other) and Unicast (the Unicast module contains a host list to control which nodes need to Ping).
(2) Sort all nodes that can become master (node.master: true) according to nodeId dictionary, each election each node know the node order, then select the first (0) node, for the moment consider it is the master node.
(3) If the number of votes for a node reaches a certain value (n/2+1 can be the number of master nodes) and the node also chooses 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, 10 of the Elasticsearch nodes (say 20)
If I pick one master, and the other 10 pick another master, what do I do?
(1) When the number of master candidates in the cluster is not less than 3, the problem of split brain can be solved by setting the minimum number of votes (discovery.zen.minimum_master_nodes) to exceed half of all candidate nodes.
(3) 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?
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) Copy the codeCopy the code
(1) When the shard node receives a request from the coordination node, it writes the request to the MemoryBuffffer and then writes it to the Filesystem Cache periodically (default: every 1 second). This process from MomeryBuffffer to Filesystem Cache is called refresh;
(2) Of course, in some cases, Momery Buffffer and Filesystem Cache data may be lost. ES ensures data reliability through the translog mechanism. Data in Filesystem cache is flushed when the data in Filesystem cache is written to disk. This process is called flflush.
(3) During Flflush, 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) Flflush 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.
Elasticsearch is a distributed RESTful search and data analysis engine.
(1) Queries: Elasticsearch allows you to perform and merge multiple types of searches — structured, unstructured, geographic, metric — in any way you want.
(2) Analysis: It is one thing to find the ten documents that best match the query. But what if you’re dealing with a billion lines of logs? Elasticsearch aggregation allows you to think big and explore trends and patterns in your data.
(3) Speed: Elasticsearch is fast. Really, really fast.
(4) Scalability: it can run on laptop computers. It can also run on hundreds of servers that host petabytes of data.
(5) Elasticity: Elasticsearch runs in a distributed environment and has been designed with this in mind since the beginning.
(6) Flexibility: Multiple case scenarios. Number, text, location, structured, unstructured. All data types are welcome.
(7) HADOOP & SPARK: Elasticsearch + HADOOP
Elasticsearch is a highly scalable open source full text search and analysis engine. It allows you to store, search, and analyze large amounts of data quickly and in near real time.
Here are some use cases for Elasticsearch:
(1) You run an online store and you allow your customers to search for the products you sell. In this case, you can use Elasticsearch to store the entire product catalog and inventory and provide search and auto-complete suggestions for them.
(2) You want to collect log or transaction data, and you want to analyze and mine that data for trends, statistics, summaries, or anomalies. In this case, you can use Loghide (part of Elasticsearch/ Loghide /Kibana stack) to collect, aggregate, and parse data, and then have Loghide input this data into Elasticsearch. Once the data is in Elasticsearch, you can run searches and aggregations to mine any information you’re interested in.
(3) You run a price alert platform that allows price-savvy customers to specify the following rule: “I am interested in purchasing specific electronic devices and would like to be notified if any vendor’s product is priced below $X in the next month.” In this case, you can grab the vendor’s prices, push them into Elasticsearch, and use its reverse Percolator feature to match price movements with customer queries, eventually pushing an alert to the customer when a match is found.
(4) You have analytical/business intelligence needs and want to quickly investigate, analyze, visualize, and ask special questions about large amounts of data (think millions or billions of records). In this case, you can use Elasticsearch to store the data, and then use Kibana (part of Elasticsearch/ Loghide /Kibana stack) to build custom dashboards to visualize the various aspects of the data that are important to you. In addition, you can perform complex business intelligence queries on data using Elasticsearch aggregation capabilities.
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
16, Describe the process of Elasticsearch.
In Elasticsearch, how do I find an inverted index based on a word?
(1) Lucene’s indexing process is the process of writing inverted list in this file format according to the basic process of full-text retrieval.
(2) Lucene’s search process is to read out the information indexed in accordance with this file format, and then calculate the score of each document.
18, 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) By setting gateway.recover_after_nodes, gateway.expected_nodes, and gateway.recover_after_time, you can avoid excessive fragment exchanges during cluster restart, which may cause data recovery from several nodes
Hours were shortened 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.
19. 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, so the growth trend of Segmentmemory on data node needs to be monitored.
All caches, fifield cache, fifilter cache, indexing cache, bulk queue, etc., should be set to a reasonable size and the heap should be sufficient in the worst-case scenario, i.e., when all caches are full. Is there heap space available for other tasks? Avoid using clear Cache to free memory.
(3) 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.
(4) 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.
(5) To know whether the heap is sufficient, we must combine the actual application scenarios and continuously monitor the heap usage of the cluster.
(6) Understand the memory requirements according to the monitoring data, and reasonably configure all kinds of circuit breaker to minimize the risk of memory overflow
20, 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.
21, What does Elasticsearch do to ensure read-write consistency under concurrent conditions?
(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 set the search request parameter _preference to primary
Poll the master shard to make sure the document is the latest version.
22. 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.
Introduce the overall technical architecture of your e-commerce search.
24. Tell me about your personalized search solution.
Personalized search based on Word2vec and Elasticsearch
(1) Based on Word2vec, Elasticsearch and a custom script plugin, we have implemented a personalized search service, which has a much higher click through rate and conversion rate than the original implementation.
(2) The commodity vector based on Word2VEc has another advantage, that is, it can be used to recommend similar commodities;
(3) There are some limitations in using Word2vec to realize personalized search or personalized recommendation, because it can only process time series data such as user click history, but can not fully consider user preferences, which still has a lot of room for improvement and improvement;
25, 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. 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.
Or 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
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 search
The speed of the query can keep the complexity of the hash O(1)
26. 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, coffffee length is 6, add 2 for each), and then fill in the following positions with black numbers. The calculation process of other lattices is as follows
Minimum of three values:
If the uppermost character is equal to the leftmost character, the upperleft digit. Otherwise, the top left digit +1. (0 for 3,3)
Left digit +1 (2 for 3,3 cells)
Top number +1 (2 for 3,3 cells)
Finally, the value in the lower right corner is the value of editing distance 3.