Painless - how to access "@timestamp" field in script

Hi All,

I have an index with a mapping for the field
"@timestamp": {
"format": "epoch_millis",
"type": "date"
}

Using painless i want to update it. However when i try to access this field in the script it throws an error. How to access this field in the script

POST index/doc/_update_by_query
script{
"lang":"painless",
"inline": "ctx._source.@timestamp = ctx._source.somedatefield"
}

You can do ctx._source['@timestamp'] = ctx._source['somedatefield']

2 Likes

@shanec thanks.

How would this be different as shown https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting-using.html

    "lang":   "expression",
    "source": "doc['@timestamp']" = doc['somedatefield']

Note that you/the docs have "lang": "expression" here, which is a different language than Painless, but for what I'm going to say next, you can safely ignore this.

There are different contexts in Elasticsearch that scripts can run in, which means that depending on where you run the script, you may have access to different stuff. As a concrete example, painless scripts in an ingest pipeline haven't yet indexed the document, which means they haven't placed in the doc_values structure we use and it wouldn't make any sense to have a "score" since there's no query going on at that time. But those are 2 things that do make a lot of sense to access from a script at query time. In contrast, there are things that do make sense to access at ingest/update/reindex time which should be avoided at query time -- things like accessing _source.

Documentation for this is at Accessing document fields and special variables | Elasticsearch Guide [8.11] | Elastic, but we definitely could improve the clarity here.

1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.