1
votes

I am using query_string to search for records from Elastic,

Example Query :

GET /stories_qa/_search
{
  "query": {
    "query_string": {
      "query": "Johnson && Johnson"
    }
  }
}

This query gives me relevant records, but the exact match record is not on top, I figured out on how we can boost records based on specific fields, but in my case, I don't want to provide field and make search restrictive, Is there an option in ElasticSearch to achieve the same.

2
if you don't want to make your search restrictive/specific, it will be hard to make it precise. But maybe someone can give you some hintsPierre Mallet
Can you add at least two sample docs, mentioning the one that should be on top?Nishant

2 Answers

1
votes

You can probably do something like below, but do thorough testing and test multiple scenarios before you move it to production.

POST <your_index_name>/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must": [
              {
                "query_string": {
                  "query": "\"Karnataka Delhi\"",
                  "default_operator": "AND"
                }
              }
            ]
          }
        },
        {
          "query_string": {
            "query": "Karnataka Delhi",
            "default_operator": "OR",
            "boost": 2
          }
        },
        {
          "query_string": {
            "query": "Karnataka Delhi",
            "default_operator": "AND",
            "boost": 4
          }
        }
      ]
    }
  }
}

Hope this helps!

0
votes

It would help with examples, but you can use phrase_match query by adding double quote. If you add a boost to the phrase_match query you will be able to get to exact match ranked higher.

The following query should do what you want.

GET /stories_qa/_search
{
  "query": {
    "query_string": {
      "query": "(\"Johnson && Johnson\")^2 OR (Johnson && Johnson)"
    }
  }
}