如何用Elasticsearch的simple_query_string在指定嵌套分类中跨文档检索?
Elasticsearch跨指定分类嵌套文档的查询方案
Elasticsearch支持这类跨指定分类嵌套文档的检索需求,核心是结合嵌套类型(nested)和bool查询的should+minimum_should_match来实现,解决你之前遇到的扁平化数据无法过滤、单嵌套文档不能跨检索的问题。
步骤1:确保索引映射正确
首先必须把publications字段设置为nested类型,避免数据扁平化丢失关联关系,示例映射如下:
{ "mappings": { "properties": { "name": { "type": "text" }, "publications": { "type": "nested", "properties": { "category": { "type": "keyword" }, "text": { "type": "text" } } } } } }
步骤2:构造目标查询
以你需求中的场景为例:
- 要在
cat-aaa和cat-ccc中执行car AND mouse查询,需构造如下查询:
{ "query": { "bool": { "minimum_should_match": 2, "should": [ { "nested": { "path": "publications", "query": { "bool": { "must": [ { "term": { "publications.category": "cat-aaa" } }, { "simple_query_string": { "query": "car", "fields": ["publications.text"] } } ] } } } }, { "nested": { "path": "publications", "query": { "bool": { "must": [ { "term": { "publications.category": "cat-ccc" } }, { "simple_query_string": { "query": "mouse", "fields": ["publications.text"] } } ] } } } } ] } } }
这个查询的逻辑是:
每个
should子句对应一个嵌套文档的检索,分别验证cat-aaa下有car、cat-ccc下有mouseminimum_should_match: 2要求两个子句都满足,这样只有同时符合两个条件的文档才会被返回如果仅在
cat-aaa中执行car AND mouse查询,对应的查询会因单个嵌套文档里无法同时匹配car和mouse,所以不会返回目标文档,符合你的需求。
补充说明
如果需要更复杂的多分类多文本匹配,只需在should中添加对应数量的嵌套查询子句,并调整minimum_should_match的值即可,也可以结合must/filter先过滤出包含指定分类的文档,进一步缩小检索范围。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

