Elasticsearch: custom tally with tags

I have documents of the following form:

{
    "content": "lorem ipsum...",
    "tags": [
        { "tag": "red", weight: 3 },
        { "tag": "green", weight: 1 },
    ]
}

I want to search for documents with full-text search and change the rating depending on the matching tags.

Suppose I'm looking for a phrase ipsumand tag red. A text search would evaluate, say, 2for the above document. There is also a redweight tag in the document 3, so I want the score to be multiplied by that weight for the resulting metric 6.

My current approach is to use script_score:

{
  "query": {
    "function_score": {
      "query": {
        "match": { ... }
      },
      "functions": [
        {
          "filter": {
            "nested": {
              "path": "tags",
              "filter": {
                "term": {
                  "key": "red"
                }
              }
            }
          },
          "script_score": {
            "script": "_score * doc['tags']['red'].weight"
          }
        },
        {
          "script_score": {
            "script": "_score"
          }
        }
      ],
      "score_mode": "first"
    }
  }
}

The part that does not work "script": "_score * doc['tags']['red'].weight".

How do I need to write a script to access weight?

+4
source share

Source: https://habr.com/ru/post/1540654/


All Articles