ElasticSearch:多级嵌套查询"AND"语法



我有一个类似于elasticsearch-doc多级嵌套查询示例中显示的示例索引的索引:https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-nested-query.html#multi-分层嵌套查询(不包括(

给定以下示例文档:

{
"driver" : {
"last_name" : "McQueen",
"vehicle" : [
{
"make" : "Powell Motors",
"model" : "Canyonero"
},
{
"make" : "Miller-Meteor",
"model" : "Ecto-1"
}
]
}
}
{
"driver" : {
"last_name" : "Hudson",
"vehicle" : [
{
"make" : "Mifune",
"model" : "Mach Five"
},
{
"make" : "Miller-Meteor",
"model" : "Ecto-1"
}
]
}
}

我需要能够找到driver.vehicle.make匹配两个值的文档,即同时拥有两个车辆的驾驶员";Powell Motors";以及";Miller流星";应该匹配麦昆,但不能匹配哈德逊。我尝试了一个类似于文档示例的make和model查询的查询,但它返回0个文档:

{
"query": {
"nested": {
"path": "driver",
"query": {
"nested": {
"path": "driver.vehicle",
"query": {
"bool": {
"must": [
{ "match": { "driver.vehicle.make": "Powell Motors" } },
{ "match": { "driver.vehicle.make": "Miller-Meteor" } }
]
}
}
}
}
}
}
}

改变";必须";至";应该";返回两个文档。我似乎找不到一个查询可以在同一个文档中查询车辆阵列中的多个值匹配。

上面的查询返回0个文档,因为在您的示例中没有一个文档(在driver.vehicle内部(的driver.vehicle.make值为"Powell Motors";以及";米勒流星";。

注意:此处单个文档指driver.vehicle中的每个单独文档(或对象(。

因此,当您将must子句更改为should子句时,它会返回那些driver.vehicle.make值为"Powell Motors" OR "Miller-meteor"的文档(在本例中为两个文档(。must充当逻辑AND运算符,should充当逻辑OR运算符。

根据您的要求,我相信您想要那些拥有车辆的驾驶员";Powell Motors";OR";Miller流星";应该匹配麦昆,但不匹配哈德逊

在这种情况下,您需要将嵌套查询与普通查询相结合,这可以使用bool查询来完成。

您修改后的查询将是

{
"query": {
"nested": {
"path": "driver",
"query": {
"bool": {
"must": [
{
"match": {
"driver.last_name": "McQueen"
}
},
{
"nested": {
"path": "driver.vehicle",
"query": {
"bool": {
"should": [
{
"match": {
"driver.vehicle.make": "Powell Motors"
}
},
{
"match": {
"driver.vehicle.make": "Miller-Meteor"
}
}
]
}
}
}
}
]
}
}
}
}
}

搜索结果将是

"hits" : [
{
"_index" : "soidx1",
"_type" : "_doc",
"_id" : "1",
"_score" : 3.105637,
"_source" : {
"driver" : {
"last_name" : "McQueen",
"vehicle" : [
{
"make" : "Powell Motors",
"model" : "Canyonero"
},
{
"make" : "Miller-Meteor",
"model" : "Ecto-1"
}
]
}
}
}
]

最新更新