我正在尝试查询具有多个值的嵌套属性。
这里有一个例子会更清楚。
使用嵌套字段创建索引
curl -X DELETE "http://localhost:9200/testing_nested_query/"
curl -X POST "http://localhost:9200/testing_nested_query/" -d '{
"mappings": {
"class": {
properties: {
title: {"type": "string"},
"students": {
"type": "nested",
"properties": {
"name": {"type": "string"}
}
}
}
}
}
}'
添加一些值
curl -XPUT 'http://localhost:9200/testing_nested_query/class/1' -d '{
"title": "class1",
"students": [{"name": "john"},{"name": "jack"},{"name": "jim"}]
}'
curl -XPUT 'http://localhost:9200/testing_nested_query/class/2' -d '{
"title": "class2",
"students": [{"name": "john"},{"name": "chris"},{"name": "alex"}]
}'
查询 john 所在的所有类(class)(按预期命中 2 次)
curl -XGET 'http://localhost:9200/testing_nested_query/class/_search' -d '{
"query": {
"nested": {
"path":"students",
"query": {
"bool": {
"must": [
{"match": {"students.name": "john"}}
]
}
}
}
}
}'
查询 john 和 jack 都参加的类(class)(结果为 0 而不是 1)
curl -XGET 'http://localhost:9200/testing_nested_query/class/_search' -d '{
"query": {
"nested": {
"path":"students",
"query": {
"bool": {
"must": [
{"match": {"students.name": "john"}},
{"match": {"students.name": "jack"}}
]
}
}
}
}
}'
我试过匹配和过滤,但我永远无法让查询返回预期值。
最佳答案
它只需要一点点改变:
{
"query": {
"bool": {
"must": [
{
"nested": {
"path":"students",
"query": {
"bool": {
"must": [
{"match": {"name": "john"}}
]
}
}
}
},
{
"nested": {
"path":"students",
"query": {
"bool": {
"must": [
{"match": {"name": "jack"}}
]
}
}
}
}
]
}
}
}
为什么?
基本上,在嵌套查询中,查询和过滤器在单个嵌套文档上共同执行 - 在您的例子中是一个名称。因此,您的查询将选取每个嵌套文档,并尝试同时查找 name
等于 john
和 jack
的每个文档 - 这是不可能的。
我的查询试图找到一个索引文档,该文档具有一个 name
等于 john
的嵌套文档和另一个 name
等于的嵌套文档 jack
。所以基本上一个嵌套查询会尝试完全匹配一个嵌套文档。
为了证明我的建议,试试这个:
使用与您相同的映射创建相同的索引
** 然后索引以下文档**
curl -XPUT 'http://localhost:9200/testing_nested_query/class/1' -d '{
"title": "class1",
"students": [{"name": "john", "age": 4},{"name": "jack", "age": 1},{"name": "jim", "age": 9}]
}'
curl -XPUT 'http://localhost:9200/testing_nested_query/class/2' -d '{
"title": "class1",
"students": [{"name": "john", "age": 5},{"name": "jack", "age": 4},{"name": "jim", "age": 9}]
}'
现在执行以下查询:
{
"query": {
"nested": {
"path":"students",
"query": {
"bool": {
"must": [
{"match": {"name": "john"}},
{"match": {"age": 4}}
]
}
}
}
}
}
根据您的预期,这应该匹配 2 个文档,但实际上只匹配一个。因为只有一个嵌套文档的 name
等于 john
和 age
等于 4
。
希望对您有所帮助。
关于elasticsearch - 使用 elasticsearch 在同一字段上搜索嵌套字段的多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24539551/