0

I'm trying to use the match_phrase_prefix query with an exclude query, so that it matches all terms except for the terms to be exclude. I have it figured out in a basic URI query, but not the regular JSON query. How do I convert this URI into a JSON type query?

"http://127.0.0.1:9200/topics/_search?q=name:"
                        + QUERY + "* AND !name=" + CURRENT_TAGS

Where CURRENT_TAGS is a list of tags not to match with.

This is what I have so far:

{
  "query": {
    "bool": {
      "must": {
        "match_phrase_prefix": {
          "name": "a"
        }
      },
      "filter": {
        "terms": {
          "name": [
            "apple"
          ]
        }
      }
    }
  }
}

However, when I do this apple is still included in the results. How do I exclude apple?

0

1 Answer 1

3

You are almost there, you can use must_not, which is part of boolean query to exclude the documents which you don't want, below is working example on your sample.

Index mapping

{
 
  "mappings": {
    "properties": {
      "name": {
        "type": "text"
      }
  }
}
}

Index sample docs as apple and amazon worlds biggest companies which matches your search criteria :)

Search query to exclude apple

{
  "query": {
    "bool": {
      "must": {
        "match_phrase_prefix": {
          "name": "a"
        }
      },
      "must_not": {
        "match": {
          "name": "apple"
        }
      }
    }
  }
}

Search results

 "hits": [
      {
        "_index": "matchprase",
        "_type": "_doc",
        "_id": "2",
        "_score": 0.6931471,
        "_source": {
          "name": "amazon"
        }
      }
    ]
Sign up to request clarification or add additional context in comments.

2 Comments

I could suggest a small improvement by using the must_not into a filter. It will improve elastic cache capabilities, and then performances
oh thank you I did not know that. My query will be more simple. Thanks Opster

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.