Elasticsearch multi term filter

Rein Van Leirsberghe picture Rein Van Leirsberghe · Jan 18, 2014 · Viewed 85k times · Source

I'm quite new to Elasticsearch, so here's my question. I wanna do a search query with elasticsearch and wanna filter with multiple terms.

If I want to search for a user 'tom', then I would like to have all the matches where the user 'isActive = 1', 'isPrivate = 0' and 'isOwner = 1'.

Here's my search query

"query":{
    "filtered": {
        "query": {
            "query_string": {
                "query":"*tom*",
                "default_operator": "OR",
                "fields": ["username"]
            }
        },
        "filter": {
            "term": { 
                "isActive": "1",
                "isPrivate": "0",
                "isOwner": "1"
            }
        }
    }
}   

When I use 2 terms, it works like a charm, but when i use 3 terms it doesn't.

Thanks for the help!!

Answer

Duc.Duong picture Duc.Duong · Jan 18, 2014

You should use bool filter to AND all your terms:

"query":{
    "filtered": {
        "query": {
            "query_string": {
                "query":"*tom*",
                "default_operator": "OR",
                "fields": ["username"]
            }
        },
        "filter": {
            "bool" : {
                "must" : [
                    {"term" : { "isActive" : "1" } },
                    {"term" : { "isPrivate" : "0" } },
                    {"term" : { "isOwner" : "1" } }
                ]
             }
         }
     }
}   

For version 2.x+ you can use bool query instead of filtered query with some simple replacement: https://www.elastic.co/guide/en/elasticsearch/reference/7.4/query-dsl-filtered-query.html