0

Very new to this Painless Scripting, and I'm finding a lot of Pain with it. It's nothing like any scripting languages I've used in the past. I'm 100% sure that this is a syntax issue but cannot figure it out.

I have a static index with a large amount of documents, and wanting to create a unique identifiable field. I have created a mapping called "doc_id" as an Integer and set all values to 0 to begin with.

I'm trying to form a for-loop to iterate through all items in the index and increase the doc_id by 1, for each document that exists.

POST index-name/_update_by_query?conflicts=proceed&&wait_for_completion=false
{
  "script": : {
    "source": """
      int i = 0;
      for (item in ctx._source['doc_id']) {
        ctx._source['doc_id']=i;
        i++;
        }
      """
    }.
    "query": {
      "match_all": {}
    }
}

Error: Type: Illegal_argument_exception" Reason: "Cannot iterate over [java.lang.Integer]"

Am I approaching this the right way? How am I meant to define a list to iterate over? I thought this is what the "query" was.

  • this excepton you are getting because you are using `ctx._source['doc_id']` which will return just one number and you can not iterate that integer. – Sagar Patel Mar 13 '23 at 05:02
  • Thanks Sagar - so with that said, how would I specify the hits from the query to iterate through? – OSIronBrian Mar 13 '23 at 05:12

1 Answers1

0

Hope this helps:

POST increment_index/_update_by_query
{
  "script": {
    "source": "ctx._source.doc_id += params.inc",
    "lang": "painless",
    "params": {
      "inc": 1
    }
  },
  "query": {
    "match_all": {}
  }
}

The above is self explanatory but if anything unclear, you can comment - I will try to answer.

Smit
  • 2,078
  • 2
  • 17
  • 40
  • Hey Smit - thanks for your comment. This will increment doc_id by 1, but then all documents will have the same value as doc_id because it's not iterating through the results from the query. So running this, all documents will have a doc_id of 1, instead of 1..1000000. I think the most important thing to know here is how to iterate through the results of the query? – OSIronBrian Mar 13 '23 at 19:04
  • @OSIronBrian why you want to iterate through all the result ? if you want to put id then put at application level or index time itself. Elasticsearch is not like DB that will give you increment value every time it is index document. index level you can not have counter in Elasticsearch. you can put at document level by using this answer. – Sagar Patel Mar 14 '23 at 13:21