Search code examples
elasticsearchquerydslelasticsearch-query

ElasticSearch advanced query_string query


What I need is, elastic should search in multiple fields and return data by field priority.

For example: For the search string obil hon, elastic should search in fields[title, description, modelCaption] and return data when at first it finds Mobile Phone in Title field, then in other fields.

Query I use:

{
  "from": 0,
  "query": {
    "bool": {
      "must": [
        {
          "query_string": {
            "default_operator": "or",
            "fields": [
              "title^5",
              "description",
              "modelCaption",
              "productFeatureValues.featureValue",
              "productFeatureValues.featureCaption"
            ],
            "query": "*obil* *hone*"
          }
        }
      ]
    }
  },
  "size": 16
}

Any suggestions?

Thanks!


Solution

  • You can simply use the multi-match query to query multiple fields and it supports boosting a particular field like a title in your case and different operators like OR in your case.

    Sample ES query for your use case:

    {
      "query": {
        "multi_match" : {
          "query" : "mobile phones",
          "fields" : [ "title^5", "description","modelCaption","productFeatureValues.featureVal"],
          "fuzziness" : "AUTO" --> Adding fuzziness to query
        }
      }
    }
    

    Here title filed is boosted by factor 5, hence if mobile phones match in title field then it would be scored higher.

    Also please note, you are using wild-card in your query string which is very costly so it's better to avoid them if you can.

    EDIT: Based on OP comments, included fuzziness parameter AUTO in query for better results