Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch query not giving exact match

Am searching elasticsearch with the below match query, which is not giving me the exact match instead its giving some more irrevalant match also.

am using elasticsearch 6.2.3

Please find my query below

get items/_search
{
   "query" : {
      "match" : {
         "code" : "7000-8900"
      }
   }
}

Please find the response am getting it from match query

7000-8900
7000-8002-WK
7000-8002-W
like image 292
Karthikeyan Avatar asked Jun 12 '18 13:06

Karthikeyan


3 Answers

I had the same issue with the match, so I tried to use term. But it is a bad practice. ES says, we should not use term for string matching.

If you specify the field as keyword, the match will do the exact match anyway.

If you haven't defined the field as keyword, you can still do the query like this:

get items/_search
{
   "query" : {
      "match" : {
         "code.keyword" : "7000-8900"
      }
   }
}
like image 104
Sándor Tóth Avatar answered Oct 10 '22 09:10

Sándor Tóth


Instead of match you have to use term query, as the documentation describe:

The term query finds documents that contain the exact term specified in the inverted index

So you have to change your query as follow:

get items/_search
{
   "query" : {
      "term" : {
         "code.keyword" : "7000-8900"
      }
   }
}

If you don't get any result there are two possibilities:

  • The term searched is not what you think it really is (for example is not trimmed)
  • The index has no explicit mapping and the automatic mapping didn't recognize the field code as a string.

Note: if the mapping is correct and code is a term field it is possible to use "code". If the mapping was automatic and the mapping recognize it as text you need to use "code.keyword"

like image 40
Davide Lorenzo MARINO Avatar answered Oct 10 '22 10:10

Davide Lorenzo MARINO


You can try this method.This query return exact match record.

import json
from elasticsearch import Elasticsearch

es = Elasticsearch('http://localhost:9200')
res = es.search(index="test_index", doc_type="test_doc", body=json.dumps({"query": {"match_phrase": {"name": "Jhon"}}})))
like image 4
waruna k Avatar answered Oct 10 '22 09:10

waruna k