如何编写Elasticsearch查询判断嵌套对象中expires字段存在情况
Elasticsearch 嵌套对象字段存在性查询
假设我们有存储冰箱信息的索引,示例文档结构如下:
{ "_id": "whatever", "location": "North Building 1", "floor": 2, "tag": "refrigerator-1", "contents": [ { "item": "milk-carton", "expires": "2023-01-01" }, { "item": "pyrex-container" } ] }
以下是对应需求的查询语句:
1. 查找至少有一件物品包含expires字段的冰箱
直接使用exists查询匹配存在目标字段的文档:
{ "query": { "exists": { "field": "contents.expires" } } }
2. 查找没有任何物品包含expires字段的冰箱
通过bool查询的must_not排除所有存在目标字段的文档:
{ "query": { "bool": { "must_not": [ { "exists": { "field": "contents.expires" } } ] } } }
3. 查找所有物品都包含expires字段的冰箱
注意:此查询要求contents字段必须是nested类型(若未设置需先修改索引映射)。通过组合nested查询和bool逻辑实现:
{ "query": { "bool": { "must": [ { "nested": { "path": "contents", "query": { "exists": { "field": "contents.expires" } } } } ], "must_not": [ { "nested": { "path": "contents", "query": { "bool": { "must_not": [ { "exists": { "field": "contents.expires" } } ] } } } } ] } } }
逻辑说明:
must部分确保文档至少有一个物品包含expires字段(过滤空数组或无符合条件的情况)must_not部分排除任何存在物品不包含expires字段的文档
两者结合即可得到所有物品都带有expires字段的冰箱文档。
内容的提问来源于stack exchange,提问作者Erik Philips
相关产品推荐
相关产品推荐

