0
我試圖獲取嵌套文檔中有兩個名稱的文檔,但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
爲每個名稱添加一個嵌套塊非常詳細,但解決了問題,謝謝。 –
可能是冗長的,但這是做到這一點的方法。 –