how to update by query to create incrementing ranking from sorted query in elasticsearch 6.4

Viewed 380

I'm trying to update_by_query to rank items in sorted search. Is it possible to get the current "index" of the document in the script?

eg.

create index:

PUT test
{
    "mappings" : {
        "person" : {
            "properties" : {
                "score" : { "type" : "integer" },
                "rank" : { "type" : "integer" }
            }
        }
    }
}  

add documents:

POST /test/person/1
{
  "score": 100,
  "rank": 0
}
POST /test/person/2
{
  "score": 200,
  "rank": 0
}

update_by_query

POST /test/_update_by_query
{
  "script": {
    "source": "ctx._source.rank=3", // how to get document "index" in sort here?
    "lang": "painless"
  },
  "sort": { "score": "desc" }
}

results when sorting by ascending rank should be

score: 200, rank: 1 score: 100, rank: 2

1 Answers

Looks like you are trying to update a single document. For this, the _update API would be a more appropriate choice. For example:

POST test/_update/1
{
    "script" : {
        "source": "ctx._source.rank=params.rank",
        "lang": "painless",
        "params" : {
            "rank" : 4
        }
    }
}

In the above case, you can see the document ID is provided to the API which updates only that document.

In contrast, the _update_by_query API performs an update on every document in the index. So, if you need to update more than one document based on a script, this would be your go to.

Hope it helps...

Related