Query question: must not match anything but xyz


(Patrick Br├╝ckner) #1

Hi again,

we are very happy with elastic for now, and we need to tweak our query a little bit, but I am unsure how. I'm using a bool query, similar to this one:

{
  "query": {
    "bool": {
      "must": {
        "multi_match": {
          "query": "sth",
          "type": "best_fields",
          "fields": "field1 field2",
          "tie_breaker": 1
        }
      },
      "should": {
        "boosting": {
          "positive": {
            "constant_score": {
              "filter": {
                "exists": {
                  "field": "fieldx"
                }
              }
            }
          },
          "negative": {
            "constant_score": {
              "filter": {
                "missing": {
                  "field": "fieldx"
                }
              }
            }
          },
          "negative_boost": 0.1
        }
      }
    }
  }
}

I am looking for a way to add a must_not field to the bool query that removes all matches that contain a field that contains a value that differs from something specific, but also includes results that do not contain that field.

Thanks for all help so far and keep up the good work!


(Colin Goodheart-Smithe) #2

I don't think you need to use must_not here. You can wrap your query in a filtered query and then use a bool with two should clauses, one to retain documents with your specific value and one using the missing filter to retain documents with no entry for the field.

It would be something like this:

{
  "query": {
    "filtered": {
      "query": {
        QUERY CRITERIA GOES HERE
      },
      "filter": {
        "bool": {
          "should": [
            {
              "term": {
                "my_field": {
                  "value": "something_specific"
                }
              }
            },
            {
              "missing": {
                "field": "my_field"
              }
            }
          ]
        }
      }
    }
  }
}

Hope that helps


(system) #3