Elasticsearch查询匹配相同嵌套字段的不同值
问题描述:
我试图获取嵌套文档中有两个名称的文档,但must
子句以“OR”而不是“AND”工作。 这里是例子:Elasticsearch查询匹配相同嵌套字段的不同值
映射:
curl -XPUT "http://localhost:9200/my_index" -d '
{
"mappings": {
"blogpost": {
"properties": {
"comments": {
"type": "nested",
"properties": {
"name": { "type": "keyword" },
"age": { "type": "short" }
}
}
}
}
}
}'
索引3个文件:
curl "http://localhost:9200/my_index/blogpost/1" -d '
{
"title": "doc1",
"comments": [
{
"name": "John Smith",
"age": 28
},
{
"name": "Alice White",
"age": 31
}
]
}
'
curl "http://localhost:9200/my_index/blogpost/2" -d '
{
"title": "doc2",
"comments": [
{
"name": "Luther Lawrence",
"age": 21
},
{
"name": "Alice White",
"age": 19
}
]
}
'
curl "http://localhost:9200/my_index/blogpost/3" -d '
{
"title": "doc3",
"comments": [
{
"name": "Tadhg Darragh",
"age": 22
},
{
"name": "Alice White",
"age": 31
},
{
"name": "Lorene Hicks",
"age": 44
}
]
}
'
我正在寻找具有comments.name
与"Alice White"
和"John Smith"
在同一文档中的文件,使用上面的数据只有文件id 1
会匹配。我试着用这个查询:
curl "http://localhost:9200/my_index/blogpost/_search" -d '
{
"_source": { "include": "title" },
"query": {
"nested": {
"path": "comments",
"query": {
"bool": {
"must": [
{ "terms": { "comments.name": ["John Smith", "Alice White"] } }
]
}
}
}
}
}
'
它匹配所有文件,因为所有文件都有“John Smith”或“Alice White”。 改善这个查询有两个分开的比赛query.nested.query.bool.must[].terms
,一个匹配每个值:
curl "http://localhost:9200/my_index/blogpost/_search" -d '
{
"_source": { "include": "title" },
"query": {
"nested": {
"path": "comments",
"query": {
"bool": {
"must": [
{ "term": { "comments.name": "John Smith" } },
{ "term": { "comments.name": "Alice White" } }
]
}
}
}
}
}
'
所以,我的问题是,如何建立一个查询仅匹配文档与"Alice White"
和"John Smith"
?
ps。删除脚本与example here
答
{
"_source": {
"include": "title"
},
"query": {
"bool": {
"must": [
{
"nested": {
"path": "comments",
"query": {
"bool": {
"must": [
{
"terms": {
"comments.name": [
"John Smith"
]
}
}
]
}
}
}
},
{
"nested": {
"path": "comments",
"query": {
"bool": {
"must": [
{
"terms": {
"comments.name": [
"Alice White"
]
}
}
]
}
}
}
}
]
}
}
}
为每个名称添加一个嵌套块非常详细,但解决了问题,谢谢。 –
可能是冗长的,但这是做到这一点的方法。 –