Elastic Search: Query on multiple fields

我们两清 提交于 2020-03-26 05:32:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!