问题
I have JSON document in elastic search as follows
{
"animals": [
{
"id": 1,
"name": "cat"
},
{
"id": 2,
"name": "dog"
},
{
"id": 3,
"name": "rabbit"
}
]
}
How to query return this document only when all the three animals are present?
This is not working.
curl -H 'Content-Type: application/json' -XPOST http://localhost:9200/*animals*/_search -d '{
"query": {
"bool": {
"must": [
{
"term": {
"animals.name.keyword": "dog"
}
},
{
"term": {
"animals.name.keyword": "cat"
}
},
{
"term": {
"animals.name.keyword": "rabbit"
}
}
],
"must_not": [],
"should": []
}
}
}'
回答1:
In order to achieve what you want to need to make sure that animals
is of nested type in your index mapping:
PUT animals
{
"mappings": {
"properties": {
"animals": {
"type": "nested"
}
}
}
}
Then your query needs to look like this:
curl -H 'Content-Type: application/json' -XPOST http://localhost:9200/*animals*/_search -d '{
"query": {
"bool": {
"must": [
{
"nested": {
"path": "animals",
"query": {
"term": {
"animals.name.keyword": "dog"
}
}
}
},
{
"nested": {
"path": "animals",
"query": {
"term": {
"animals.name.keyword": "cat"
}
}
}
},
{
"nested": {
"path": "animals",
"query": {
"term": {
"animals.name.keyword": "rabbit"
}
}
}
}
]
}
}
}'
来源:https://stackoverflow.com/questions/56727491/elastic-search-query-on-multiple-fields