Elasticsearch exact search query

Viewed 69

I'm using query string to search on documents in my index.

GET my_index/_search
{
  "query": {
    "bool": {
      "must": [{
        "query_string": {
          "query": "table test",
          "default_field": "table.name",
          "default_operator":"AND"
        }
      }]
    }
  }
}

the problem is that it returns all additional strings that include search keywords.. I wanna to give strings that have exact phrase. for example the documents table test 1 and table test 12 and table test are in my index. when I search table test, I wanna it just return table test.

I used term also, but it could not consider space charter between strings!

how can I handle this?

2 Answers

your mapping is generated by Elasticsearch, than for every text field there will be a corresponding .keyword field and hence

{
  "query": {
    "term": {
      "table.name.kwyword": { // Note .keyword in the field name.
        "value": "table test",
        "boost": 1.0
      }
    }
  }

if you don't have a .keyword field, then you have to create a keyword field and use term query that is used for exact or keyword searches.

You can use Match Phrase Query as Amit suggested in another answer.

Also, if you want to use only Query String type of query then you can give your query in double quotes as shown below:

GET my_index/_search
{
  "query": {
    "bool": {
      "must": [{
        "query_string": {
          "query": "\"table test\"",
          "default_field": "table.name",
          "default_operator":"AND"
        }
      }]
    }
  }
}

Updated:

if you want to do exact match in entire field then you can go ahead with term query in elasticsearch:

{
  "query": {
    "term": {
      "table.name.keyword": {
        "value": "table test",
        "boost": 1.0
      }
    }
  }
}
Related