简体   繁体   中英

Elastic Search: Query on multiple fields

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": []
    }
  }
}'

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"
              }
            }
          }
        }
      ]
    }
  }
}'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM