Elasticsearch多category_type_id匹配查询返回全部分类问题求助
Elasticsearch 查询返回所有分类类型的问题修复
原查询的问题出在should子句的结构上:
- 你把包含
should的子bool查询嵌套在多层must里,且这个子bool没有设置minimum_should_match参数。在Elasticsearch的bool查询规则中,当一个bool里只有should子句、没有指定minimum_should_match时,默认只需要满足0个should条件就会匹配,这就导致category_type_id的过滤完全不起作用,最终返回所有符合organization_id和object_type的文档。
修正方案一:给包含should的bool添加minimum_should_match: 1
调整后的查询会强制要求至少满足一个should里的category_type_id匹配:
{ "size": 25, "query": { "bool": { "must": [ {"match": {"organization_id": "dummy_organization"}}, {"match": {"object_type": "category"}}, { "bool": { "must": [ { "bool": { "should": [ {"match": {"category_type_id": "94f7dc26b611a5c2"}}, {"match": {"category_type_id": "b630613358520d51"}} ], "minimum_should_match": 1 } }, {"bool": {"must_not": []}} ] } } ] } }, "sort": [{"category_name": {"order": "asc"}}] }
修正方案二:简化查询结构(更推荐)
直接把分类ID的过滤逻辑移到外层bool的filter中,同时用terms查询替代多个match,让查询更简洁高效:
{ "size": 25, "query": { "bool": { "must": [ {"match": {"organization_id": "dummy_organization"}}, {"match": {"object_type": "category"}} ], "filter": [ { "terms": { "category_type_id": ["94f7dc26b611a5c2", "b630613358520d51"] } } ] } }, "sort": [{"category_name": {"order": "asc"}}] }
terms是精确匹配查询(如果category_type_id是keyword类型,效果和match一致但性能更优),且filter子句不会影响文档评分,整体查询效率更高。
内容的提问来源于stack exchange,提问作者Muhammad Umar
相关产品推荐
相关产品推荐

