Azeem Akhter
Azeem Akhter

Reputation: 577

Elasticsearch Ranking on aggregation based on AND and OR

I have a query with multiple keywords with an aggregation on author ID.

I want the ranking to be based on combining must and should.

For example for query 'X', 'Y' the authors containing both 'X' and 'Y' in the document field should be ranked higher, followed by authors who have either 'X' or 'Y'.

Doing each of them (AND/OR) is easy, I need the idea/direction how to achieve both in one ES query.

The current query I have for both X and Y is:

GET /docs/_search
{
  "size": 0,
  "query": {
    "bool": {
      "must": [
        {
          "query_string": {
            "query": "X",
            "fields": [
              "fulltext"
            ],
            "default_operator": "AND"
          }
        },
        {
          "query_string": {
            "query": "Y",
            "fields": [
              "fulltext"
            ],
            "default_operator": "AND"
          }
        }
      ]
    }
  },
  "aggs": {
    "search-users": {
      "terms": {
        "field": "author.id.keyword",
        "size": 200
      },
      "aggs": {
        "top-docs": {
          "top_hits": {
            "size": 100
          }
        }
      }
    }
  }
}

Changing must to should change it to OR but I want the combination of both ranking authors with must a higher ranking in aggregation.

Upvotes: 0

Views: 191

Answers (1)

Val
Val

Reputation: 217564

The usual way of boosting results is by adding a should clause looking for both terms, like this.

GET /docs/_search
{
  "size": 10,
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "fulltext": "X Y",
            "operator": "AND"
          }
        }
      ],
      "must": [
        {
          "match": {
            "fulltext": "X Y",
            "operator": "OR"
          }
        }
      ]
    }
  },
  "aggs": {
    "search-users": {
      "terms": {
        "field": "author.id.keyword",
        "size": 200
      },
      "aggs": {
        "top-docs": {
          "top_hits": {
            "size": 100
          }
        }
      }
    }
  }
}

Upvotes: 2

Related Questions