解決too_many_clauses: maxClauseCount is set to 1024 報錯問題
- 問題場景
- 報錯信息
- 問題分析解決
- 1. 優化查詢
- 2. 增加maxClauseCount
- 3. 改用其他查詢類型
- 修改后的查詢示例
問題場景
查詢語句:查詢clcNo分類號包含分類O
的所有文檔
{"match_phrase_prefix": {"clcNo": {"query": "O","analyzer": "standard","slop": 0,"max_expansions": 10000,"boost": 10.0}}
}
報錯信息
{"took": 12,"responses": [{"error": {"root_cause": [{"type": "exception","reason": "Elasticsearch exception [type=search_phase_execution_exception, reason=all shards failed]","phase": "query","suppressed": [{"type": "exception","reason": "Elasticsearch exception [type=too_many_clauses, reason=too_many_clauses: maxClauseCount is set to 1024]"}]}],"type": "exception","reason": "Elasticsearch exception [type=search_phase_execution_exception, reason=all shards failed]","phase": "query","suppressed": [{"type": "exception","reason": "Elasticsearch exception [type=too_many_clauses, reason=too_many_clauses: maxClauseCount is set to 1024]"}]},"status": 500}]
}
問題分析解決
從報錯信息來看,查詢出現了too_many_clauses
錯誤,這是因為使用的match_phrase_prefix
或者in
以及其他的查詢生成的子句數量超過了Elasticsearch的默認限制(1024
個子句)。我這里的錯誤是由于使用match_phrase_prefix
可能擴展為大量詞條的查詢中超過了限制
可以嘗試通過以下幾種方式來解決這個問題:
- 優化查詢:減少查詢中使用的子句數量
- 增加maxClauseCount:增加Elasticsearch中允許的最大子句數量
- 改用其他查詢類型:使用性能更好的查詢類型
1. 優化查詢
嘗試減少子句數量,優化子句的查詢數量,使得能減少到1024的個數限制
2. 增加maxClauseCount
如果確實需要大量的子句,可以增加Elasticsearch中的maxClauseCount
限制。可以通過以下步驟來增加:
-
修改Elasticsearch7.x配置文件 (
elasticsearch.yml
):indices.query.bool.max_clause_count: 2048
-
或者通過Elasticsearch的API動態更新設置(這個我沒嘗試,而且可能只是臨時的):
curl -X PUT "localhost:9200/_settings" -H 'Content-Type: application/json' -d '{"index" : {"query" : {"bool" : {"max_clause_count" : 2048}}} }'
3. 改用其他查詢類型
如果前兩種方法不可行,考慮使用性能更好的查詢類型,比如prefix
查詢。雖然prefix
查詢不如match_phrase_prefix
查詢精確,但它性能更好,并且不會產生過多的子句。
修改后的查詢示例
這里是一個優化后的查詢示例,將match_phrase_prefix
替換為prefix
查詢,并減少inner_hits
的數量:
{"prefix": {"clcNo": {"value": "O","boost": 10.0}}}
以上修改包括:
- 使用
prefix
查詢替代match_phrase_prefix
查詢。 - 降低
inner_hits
的數量,以減少子句數量。