ElasticSearch: Find record with multiple conditions on a list of sub-elements

Viewed 26

I'm saving documents like this to ElasticSearch:

[
  {
    "text": "Sam works for Google.",
    "entities": [
      {
        "text": "Sam",
        "type": "PERSON"
      },
      {
        "text": "Google",
        "type": "ORGANIZATION"
      }
    ]
  }
]

It's essentially a sentence and entities that appear in that sentence. Now, I want to find any document that has entities of type "PERSON" AND "ORGANIZATION". I tried a boolean must query:

{
  "bool": {
    "must": [
      {
        "match": {
          "entities.type": "PERSON"
        }
      },
      {
        "match": {
          "entities.type": "ORGANIZATION"
        }
      }
    ]
  }
}

... but that seems to try to look for entities that that are of both types, which obviously returns nothing. How do I need to formulate my query?

Thanks!

1 Answers

You should use below query as your original query dont have correct field name.

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "entities.type": "PERSON"
          }
        },
        {
          "match": {
            "entities.type": "ORGANIZATION"
          }
        }
      ]
    }
  }
}
Related