ElasticSearch bool查询SHOULD子句OR逻辑未达预期问题求助
问题排查
你出现查询无结果的问题,核心有4个疏漏:
- 存储结构不符合查询要求:你的
products字段存储的是JSON序列化字符串,而非ES支持的nested嵌套对象类型,无法直接检索数组内的对象字段值。需要先调整索引映射,将products设置为nested类型,且写入数据时直接传入对象数组,不要做JSON序列化。 - 查询字段路径错误:嵌套对象的字段检索需要写完整路径,比如
products.productType、products.productId,你直接查询products根字段无法匹配到内部属性。 - 拼写错误:你filter条件中写的
fakeProductTYpe存在拼写错误(T后为大写Y),和实际存储的fakeProductType(T后为小写y)不一致,term是精确匹配查询,拼写错误会直接导致无结果。 - 查询逻辑层级错误:你需要匹配同一个product对象同时满足type条件和id条件,不能把两个条件拆到外层bool的filter和should中,否则会匹配到「存在一个product符合type要求、另一个product符合id要求」的文档,和你的预期逻辑不符。
备注:如果暂时无法调整存储结构,只能通过正则匹配
products字符串的方式检索,性能很差,不推荐生产使用。
正确示例
1. 索引映射设置示例
PUT /your_index { "mappings": { "properties": { "userId": { "type": "keyword" }, "products": { "type": "nested", "properties": { "productType": { "type": "keyword" }, "productId": { "type": "keyword" } } }, "transactionType": { "type": "keyword" } } } }
2. 正确的查询语句
POST /your_index/_search { "query": { "nested": { "path": "products", "query": { "bool": { "filter": [ { "term": { "products.productType": "fakeProductType" } } ], "should": [ { "term": { "products.productId": "fakeProductId_1" } }, { "term": { "products.productId": "fakeProductId_2" } } ], "minimum_should_match": 1 } } } } }
内容的提问来源于stack exchange,提问作者wentao Qi
相关产品推荐
相关产品推荐

