May Y
May Y

Reputation: 179

nested boolean with match query in elasticsearch

I would like to match within a boolean query in Elasticsearch. I have the match query and boolean query working as expected now, but I am not sure how to have a AND to combine them.

nested boolean

{
"query": {
    "constant_score" : {
     "filter":{
    "bool":{
    "must":[
    {"terms":{"address.keyword": addr}},
    {"bool":{
    "should":[
    {"terms": {"state.keyword": state}}
    ,{"terms": {"city.keyword": city}}
    ]
    }}
    ]
    }
    }
    }}}

match

{"query": {
      "match": {
          "auct_title": {
            "query": keyword,
            "operator": "and"
          }
        }
      }
    ,  "collapse" : {
        "field" : "id" 
    }
     ,"sort" : [
     { sort_field: {"order" : sort_order} }]
     ,"size":20
    }

Upvotes: 0

Views: 577

Answers (1)

jaspreet chahal
jaspreet chahal

Reputation: 9099

You can move natch to the must clause . So document has to satisfy three conditions 1.address 2.either of state/city 2.match on auct_title

It will then return one document per Id based on sort order passed

GET <index>/_search
{
  "query": {
    "constant_score": {
      "filter": {
        "bool": {
          "must": [
            {
              "term": {
                "address.keyword": "addr"
              }
            },
            {
              "bool": {
                "should": [
                  {
                    "term": {
                      "state.keyword": "state"
                    }
                  },
                  {
                    "term": {
                      "city.keyword": "city"
                    }
                  }
                ]
              }
            },
            {
              "match": {
                "auct_title": {
                  "query": "keyword",
                  "operator": "and"
                }
              }
            }
          ]
        }
      }
    }
  },
  "collapse": {
    "field": "id"
  },
  "sort": [
    {
      "FIELD": {
        "order": "desc"
      }
    }
  ],
  "size": 20
}

Upvotes: 1

Related Questions