Ehud Lev
Ehud Lev

Reputation: 2901

Elasticsearch (v 5.2) tags with ranking implementation

I have a system that calculates tags of documents and index it into Elasticsearch, later server will search for those documents according to those tags. Now my problem is that I would like to add my own ranking / weight for each tag, and later search and have score of those documents according to the rankings / weights I set.

Assuming I have some documents like the below documents, how do I search and consider my_rank field per specific tag value (In this example user.first = Jhon)?

Example documents:

[
  {
    "_index": "ehud_test_nested",
    "_type": "my_type",
    "_id": "2",
    "_score": 1,
    "_source": {
      "group": "tags",
      "user": [
        {
          "first": "John",
          "my_rank": 100
        },
        {
          "first": "Alice",
          "my_rank": 1
        },
        {
          "first": "bob",
          "my_rank": 3
        }
      ]
    }
  },
  {
    "_index": "ehud_test_nested",
    "_type": "my_type",
    "_id": "1",
    "_score": 1,
    "_source": {
      "group": "tags",
      "user": [
        {
          "first": "John",
          "my_rank": 1
        },
        {
          "first": "Alice",
          "my_rank": 10
        },
        {
          "first": "bob",
          "my_rank": 30
        }
      ]
    }
  }
]

Upvotes: 0

Views: 184

Answers (1)

Ehud Lev
Ehud Lev

Reputation: 2901

Found it.

  1. User object must be of type nested.
  2. Use Field value factor in order to set rank inside scoring.

Example query:

 {
  "query": {
    "nested": {
      "path": "user",
      "query": {
        "function_score": {
          "query": {
            "bool": {
              "should": [
                {
                  "match": {
                    "user.first": "John"
                  }
                },
                {
                  "match": {
                    "high.tag": "Alice"
                  }
                }
              ]
            }
          },
          "boost": "1",
          "functions": [
            {
              "field_value_factor": {
                "field": "user.my_rank",
                "factor": 1,
                "modifier": "none",
                "missing": 1
              }
            }
          ]
        }
      }
    }
  }
}

Upvotes: 1

Related Questions