martins
martins

Reputation: 10009

How to use nested filters in Elasticsearch?

I have a set of articles. I want to filter on tags AND host.

E.g I want all articles that are tagged with 'news' OR 'sport' AND has the 'host' set to 'cnn.com' OR 'bbc.com'.

I tried to create this nested bool filter, but that did not work. It also returns articles from other hosts. Any suggestions?

GET _search
{
    "query": {
      "filtered": {
        "query": {
          "match_all": {}
        },
        "filter": {
          "bool": {
            "should": [
              // Match one or more of these tags.
              { "term" : { "tags" : "sport"} },
              { "term" : { "tags" : "news"} },
              { "bool": { 
                // Only from one of these hosts.
                "should": [
                  { "term": { "host": "bbc.com" } },
                  { "term": { "host": "cnn.com" } }
                ]
              }}
            ]
          }
        }
      }
    }
}

Upvotes: 1

Views: 31

Answers (1)

martins
martins

Reputation: 10009

Nesting the query like this worked. :-)

GET _search
{
    "query": {
      "filtered": {
        "query": {
          "match_all": {}
        },
        "filter": {
          "bool": {
            "must": [

              { "bool": {
                "should": [
                  { "term" : { "tags" : "sport"} },
                  { "term" : { "tags" : "news"} }
                ]
              }},

              { "bool": { 
                "should": [
                  { "term": { "host": "bbc.com" } },
                  { "term": { "host": "cnn.com" } }
                ]
              }}
            ]
          }
        }
      }
    }
}

Upvotes: 1

Related Questions