ElasticSearch 嵌套布尔查询
Posted
技术标签:
【中文标题】ElasticSearch 嵌套布尔查询【英文标题】:ElasticSearch nested bool queries 【发布时间】:2018-04-28 10:25:31 【问题描述】:我正在使用 ElasticSearch 5.6。我有以下 JSON 文档。
"cards": [
"tag_categories": [
"is_sensitive": true,
"category": "Users",
"tags": [
"is_selected": true,
"name": "user1"
,
"is_selected": true,
"name": "user2"
,
"is_selected": false,
"name": "user3"
]
],
"risk": "medium",
"position": 1,
"placement": 4,
"title": "test title",
, ...]
如果所有给定的用户名和相应的 is_selected 值为 true,我想返回此文档。
这是我的查询。
"_source":
"excludes": ["cards.pages"]
,
"query":
"bool":
"must": [
"match":
"_all": "hello world"
],
"filter": [
"nested":
"path": "cards.tag_categories.tags",
"query":
"bool":
"must": [
"bool":
"must": [
"match":
"cards.tag_categories.tags.name": "user2"
,
"match":
"cards.tag_categories.tags.is_selected": true
]
,
"bool":
"must": [
"match":
"cards.tag_categories.tags.name": "user1"
,
"match":
"cards.tag_categories.tags.is_selected": true
]
]
,
"term":
"name.keyword": "hello name"
,
"term":
"title.keyword": "hello title"
]
我添加了两个子布尔查询来匹配每组用户名和 is_selected 值。父布尔查询将获取AND
,如果为真则返回文档。
在上面的示例查询中,文档应返回为 user1 和 user2 匹配条件。但它不会发生。
如果我将单个用户与文档返回的 is_selected 值进行比较。例如:用户 1。
如果有人能告诉我我在哪里犯了错误,我将不胜感激。
【问题讨论】:
【参考方案1】:我添加了单独的嵌套块并且它起作用了!
"_source":
"excludes": ["cards.pages"]
,
"query":
"bool":
"must": [
"match":
"_all": "hello world"
],
"filter": [
"nested":
"path": "cards.tag_categories.tags",
"query":
"bool":
"must": [
"term":
"cards.tag_categories.tags.name.keyword": "user1"
,
"term":
"cards.tag_categories.tags.is_selected": true
]
,
"nested":
"path": "cards.tag_categories.tags",
"query":
"bool":
"must": [
"term":
"cards.tag_categories.tags.name.keyword": "user2"
,
"term":
"cards.tag_categories.tags.is_selected": true
]
,
"term":
"name.keyword": "hello name"
,
"term":
"title.keyword": "hello title"
]
【讨论】:
以上是关于ElasticSearch 嵌套布尔查询的主要内容,如果未能解决你的问题,请参考以下文章
ElasticSearch 将嵌套字段的 Rest 查询转换为客户端 Scala/Java 代码