Search code examples
elasticsearchelasticsearch-dsl

Elasticsearch Array Intersect Query


I'm trying to filter results based on whether an array field has at least one element from another set.

I have a field containing an array of strings eg:

_source: {
...
keywords: [
"Data Science",
"Chemistry",
"Biology",
"Computer Science",
"Economics"
]
}

I'd like to filter the results such that keywords contain at least one of a list of values, eg:

> ["History","Biology"] # would return the above document
> ["History","Geography"] # would not

It doesn't really matter how many it contains, just that it matches at least one of them.

I tried the terms query, but that does not give me any results


Solution

  • The terms query is an OR-query by default so the following will match

    {
      "query": {
        "terms": {
          "keywords": [
            "Chemistry",
            "Geography"
          ]
        }
      }
    }
    

    if your condition such that keywords contain at least one is to be satisfied.


    Now, if the requirement is to use an AND query (if one more more do not match, return null), you can use a bool-must query

    {
      "query": {
        "bool": {
          "must": [
            {
              "term": {
                "keywords": {
                  "value": "Chemistry"
                }
              }
            },
            {
              "term": {
                "keywords": {
                  "value": "Geography"
                }
              }
            }
          ]
        }
      }
    }
    

    Depending on the mapping you may need to append .keyword to the field in question.