解决too_many_clauses: maxClauseCount is set to 1024 报错问题
问题场景
查询语句:查询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
的数量,以减少子句数量。