Briefly, this error occurs when Elasticsearch is unable to rewrite the main query due to syntax errors or incorrect query structure. To resolve this issue, you should first check the syntax of your query to ensure it’s correct. If the syntax is correct, then check the structure of your query. Make sure that the fields you’re querying exist in your index and that the query is structured correctly according to the Elasticsearch query DSL. If the error persists, consider simplifying your query or breaking it down into smaller parts to identify the problematic section.
This guide will help you check for common problems that cause the log ” Failed to rewrite main query ” to appear. To understand the issues related to this log, read the explanation below about the following Elasticsearch concepts: search, query.
Overview
Search refers to the searching of documents in an index or multiple indices. The simple search is just a GET API request to the _search endpoint. The search query can either be provided in query string or through a request body.
Examples
When looking for any documents in this index, if search parameters are not provided, every document is a hit and by default 10 hits will be returned.
GET my_documents/_search
A JSON object is returned in response to a search query. A 200 response code means the request was completed successfully.
{ "took" : 1, "timed_out" : false, "_shards" : { "total" : 2, "successful" : 2, "failed" : 0 }, "hits" : { "total" : 2, "max_score" : 1.0, "hits" : [ ... ] } }
Notes and good things to know
- Distributed search is challenging and every shard of the index needs to be searched for hits, and then those hits are combined into a single sorted list as a final result.
- There are two phases of search: the query phase and the fetch phase.
- In the query phase, the query is executed on each shard locally and top hits are returned to the coordinating node. The coordinating node merges the results and creates a global sorted list.
- In the fetch phase, the coordinating node brings the actual documents for those hit IDs and returns them to the requesting client.
- A coordinating node needs enough memory and CPU in order to handle the fetch phase.
Log Context
Log “Failed to rewrite main query” class name is DefaultSearchContext.java. We extracted the following from Elasticsearch source code for those seeking an in-depth context :
this.query = buildFilteredQuery(query); if (rewrite) { try { this.query = searcher.rewrite(query); } catch (IOException e) { throw new QueryPhaseExecutionException(shardTarget; "Failed to rewrite main query"; e); } } } @Override