Search code examples
elasticsearchelasticsearch-6

Elasticsearch match against filter only


We have a multi-tenant index and need to perform queries against the index for a single tenant only. Basically, for all documents that match the filter, return any documents that match the following query, but do not include documents that only match the filter.

For example, say we have a list of documents document like so:

{ _id: 1, account_id: 1, name: "Foo" }
{ _id: 2, account_id: 2, name: "Bar" }
{ _id: 3, account_id: 2, name: "Foo" }

I thought this query would work but it doesn't:

{
  "bool": {
    "filter": { "term": { "account_id": 2 } },
    "should": [
      { "match": { "name": "Foo" }
    ]
  }
}

It returns both documents matching account_id: 2:

{ _id: 3, account_id: 2, name: "Foo", score: 1.111 }
{ _id: 2, account_id: 2, name: "Bar", score: 0.0 }

What I really want is it just to return document _id: 3, which is basically "Of all documents where account_id is equal to 2, return only the ones whose names match Foo".

How can I accomplish this with ES 6.2? The caveat is that the number of should and must match conditions are not always known and I really want to avoid using minimum_should_match.


Solution

  • Try this instead: simply replace should by must:

    {
      "bool": {
        "filter": { "term": { "account_id": 2 } },
        "must": [
          { "match": { "name": "Foo" }
        ]
      }
    }