Elasticsearch bool query with filter

Refresh

December 2018

Views

3.4k time

1

I am trying to write a Elasticsearch bool query of 2 parts. I want two conditions for "must" and two for "should". The problem is that i want to get the score only for "should". I tried the "filter" without success.

To be more specific, the query i made is here:

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "attr1": "on"
          }
        },
        {
          "match": {
            "category": "7eb84c804a8c824fd608e05f78d42f10"
          }
        }
      ],
      "should": [
        {
          "term": {
            "attr2": "on"
          }
        },
        {
          "term": {
            "attr3": "on"
          }
        }
      ],
      "minimum_should_match": "10%"
    }
  }
}

UPDATE Here is the query that failed and i want to find the error!:

  {
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "attr1": "on"
          }
        },
        {
          "term": {
            "category": "7eb84c804a8c824fd608e05f78d42f10"
          }
        }
      ],
      "should": [
        {
          "term": {
            "attr2": "on"
          }
        },
        {
          "term": {
            "attr3": "on"
          }
        }
      ],
      "minimum_should_match": "10%"
    }
  }
}

How can re-write this query in order: 1) get all rows that attr1 and category are exact 2) then query these results with should

Any idea please?

1 answers

3

Seems like you are not on Elasticsearch 2.x.

For Elasticsearch 1.x use a FilteredQuery: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-filtered-query.html

{
  "filtered": {
    "query": {
      "bool": {
        "should": [
          {
            "term": {
              "attr2": "on"
            }
          },
          {
            "term": {
              "attr3": "on"
            }
          }
        ]
      }
    },
    "filter": {
      "bool": {
        "must": [
          {
            "match": {
              "attr1": "on"
            }
          },
          {
            "match": {
              "category": "7eb84c804a8c824fd608e05f78d42f10"
            }
          }
        ]
      }
    }
  }
}