Query string in elastic search

3.7k Views Asked by At

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

am using elastic search 6.3

Please find my query below

GET /_search
{
   "must":{
      "query_string":{
         "query":"review:*test product*"
      }
   }
}

Search Result:

"hits": [ { "_index": "67107104", "_type": "_doc", "_id": "1", "_score": 0.6931471, "_source": { "title": "testing" } }, { "_index": "67107104", "_type": "_doc", "_id": "2", "_score": 0.6931471, "_source": { "title": "product good" } }, { "_index": "67107104", "_type": "_doc", "_id": "3", "_score": 0.6931471, "_source": { "title": "sample" } },{ "_index": "67107104", "_type": "_doc", "_id": "4", "_score": 0.7897571, "_source": { "title": "superr" } } ]

Expected Search Result:

"hits": [ { "_index": "67107104", "_type": "_doc", "_id": "1", "_score": 0.6931471, "_source": { "title": "testing" } }, { "_index": "67107104", "_type": "_doc", "_id": "2", "_score": 0.6931471, "_source": { "title": "product good" } } ]

2

There are 2 best solutions below

6
On

If you have not explicitly defined any mapping then you need to add .keyword to the title field. This uses the keyword analyzer instead of the standard analyzer (notice the ".keyword" after title field).

Adding a working example with index data, search query and search result

Index Data:

{
  "title": "This is test product"
}
{
  "title": "test product"
}

Search Query:

{
  "query": {
    "query_string": {
      "fields": [
        "title.keyword"
      ],
      "query": "test product"
    }
  }
}

Search Result:

"hits": [
      {
        "_index": "67107104",
        "_type": "_doc",
        "_id": "1",
        "_score": 0.6931471,
        "_source": {
          "title": "test product"
        }
      }
    ]

Search Query using Match query:

{
  "query": {
    "match": {
      "title.keyword": "test product"
    }
  }
}

Search Query using term query

    {
      "query": {
        "term": {
          "title.keyword": "test product"
        }
      }
    }
2
On

You can use boolean queries for the exact match with the filter by using the term. As the term is used for exact match and you need to add keyword for the text fields

{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "review_title.keyword": "test product"
          }
        }
      ]
    }
  }
}