Elasticsearch "search_phase_execution_exception" in CI
A search failed while executing across shards. The wrapper search_phase_execution_exception carries a more specific caused_by, most commonly that you sorted or aggregated on a text field with fielddata disabled, or sent a malformed query. Reading the nested reason is the whole fix.
What this error means
A search returns HTTP 400 with "search_phase_execution_exception" and a caused_by such as "Fielddata is disabled on [field] in [index]" or a query parsing error.
{"error":{"type":"search_phase_execution_exception","reason":"all shards failed",
"caused_by":{"type":"illegal_argument_exception","reason":"Fielddata is disabled on
[name] in [products]. Text fields are not optimised for operations that require per-document
field data like aggregations and sorting ..."}},"status":400}Common causes
Sorting or aggregating on a text field
Text fields have fielddata disabled by default; sorting or aggregating on one raises an error inside the search phase.
A malformed query body
A bad query clause or an unmapped field referenced in a sort or aggregation makes the shards fail during execution.
How to fix it
Aggregate on a keyword sub-field
- Read the nested
caused_byreason to see which field and operation failed. - Map a
keywordsub-field (or use one) for sorting and aggregation. - Point the sort or aggregation at
field.keywordinstead of the analyzed text field.
curl -X PUT "http://localhost:9200/products" -H 'Content-Type: application/json' -d '
{"mappings":{"properties":{"name":{"type":"text","fields":{"keyword":{"type":"keyword"}}}}}}'Fix the query body
If the cause is a parse error, correct the query clause or reference a field that exists in the mapping.
How to prevent it
- Always read the
caused_byreason, not just the wrapper exception. - Use
keywordfields for sorting and aggregations. - Validate queries and referenced fields against the mapping.