Filter items which array contains any of given values

Olivier picture Olivier · Jan 17, 2015 · Viewed 124.8k times · Source

I have a set of documents like

{
    tags:['a','b','c']
    // ... a bunch properties
}

As stated in the title: Is there a way to filter all documents containing any of given tags using Nest ?

For instance, the record above would match ['c','d']

Or should I build multiple "OR"s manually ?

Answer

slawek picture slawek · Apr 27, 2015

There's also terms query which should save you some work. Here example from docs:

{
  "terms" : {
      "tags" : [ "blue", "pill" ],
      "minimum_should_match" : 1
  }
}

Under hood it constructs boolean should. So it's basically the same thing as above but shorter.

There's also a corresponding terms filter.

So to summarize your query could look like this:

{
  "filtered": {
    "query": {
      "match": { "title": "hello world" }
    },
    "filter": {
      "terms": {
        "tags": ["c", "d"]
      }
    }
  }
}

With greater number of tags this could make quite a difference in length.