3

I am trying to implement NOT condition in elasticsearch query. Can I Implement filter inside bool or I need to write separate filter as below. Any optimum solution is there?

{
   "query": {
      "bool": {
     "must": [
        {
           "query_string": {
          "query": "fashion"
           }
        },
        {
           "term": {
          "post_status": "publish"
           }
        }
     ]
      }
   },
   "filter": {
      "not": {
     "filter": {
        "term": {
           "post_type": "page"
        }
     }
      }
   }
}

1 Answer 1

7

You can use a must_not clause:

{
    "query": {
        "bool": {
            "must": [
                {
                    "match": {
                        "_all": "fashion"
                    }
                },
                {
                    "term": {
                        "post_status": "publish"
                    }
                }
            ],
            "must_not": {
                "term": {
                    "post_type": "page"
                }
            }
        }
    }
}

Also, I'd recommend using a match filter instead of query_string, as query_string requires the much more strict Lucene syntax (and is therefor more error prone), whereas match works more like a search box: it will automatically transform a human readable query to a Lucene query.

Sign up to request clarification or add additional context in comments.

4 Comments

I really appreciate your suggestion. But I have tried your solution it does not return any records.
it seems problem in match query to search fashion keyword. when I remove match query part it returns data.
Ah, I see: try changing the query property of the match clause to the name of the field you want to search. If you want to search multiple fields, have a look at multi_match.
Yeah !! Now working smoothly :) and also I am applicable to mark this as solutions. Thanks a lot @Victor Welling

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.