Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch bool query with filter

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?

like image 841
Chris El Avatar asked Feb 15 '26 12:02

Chris El


1 Answers

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"
            }
          }
        ]
      }
    }
  }
}
like image 121
Ronald Avatar answered Feb 18 '26 23:02

Ronald



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!