Leibale Eidelman
Leibale Eidelman

Reputation: 3184

Search according to the best field match in Elasticsearch

Searching for "foo bar" on the document below will score an accumulative result of name*, but I would like to get the score of the best matched field (i.e name1 score).

{
  "name1": "foo bar",
  "name2": "foo",
  "name3": "bar"
}

Query for example:

{
  "query": {
    "filtered": {
      "query": {
        "bool": {
          "should": [{
            "match": {
              "name1": {
                "query": "foo bar"
              }
            }
          }, {
            "match": {
              "name2": {
                "query": "foo bar"
              }
            }
          }, {
            "match": {
              "name3": {
                "query": "foo bar"
              }
            }
          }]
        }
      }
    }
  }
}

Using Elasticsearch 2.4

Upvotes: 2

Views: 53

Answers (1)

Byron Voorbach
Byron Voorbach

Reputation: 4485

A boolean query combines the score of all subqueries . From docs:

The bool query takes a more-matches-is-better approach, so the score from each matching must or should clause will be added together to provide the final _score for each document.

For your case, you would like to use another joining query: The dis_max query

A query that generates the union of documents produced by its subqueries, and that scores each document with the maximum score for that document as produced by any subquery, plus a tie breaking increment for any additional matching subqueries.

Example:

{
  "query": {
    "dis_max": {
      "queries": [
        {
          "match": {
            "name1": {
              "query": "foo bar"
            }
          }
        },
        {
          "match": {
            "name2": {
              "query": "foo bar"
            }
          }
        },
        {
          "match": {
            "name3": {
              "query": "foo bar"
            }
          }
        }
      ]
    }
  }
}

*Note, I wrote this on ES6, which doesn't have filtered query anymore, but I hope you get the gist :)

Hope this helps!

Upvotes: 1

Related Questions