Prashant Agrawal
Prashant Agrawal

Reputation: 381

How to update date field in elasticsearch

I have data in my Elastic index as below :

Indexed data as:

curl -XPUT 'http://localhost:9200/twitter/tweet/1' -d '{
    "user" : "kimchy",
    "post_date" : "2009-11-15T14:12:12",
    "message" : "trying out Elasticsearch"
}'

Mapping obtained using

curl -XGET localhost:9200/twitter

{"twitter":{"aliases":{},"mappings":{"tweet":{"properties":{"message":{"type":"string"},"post_date":{"type":"date","format":"strict_date_optional_time||epoch_millis"},"user":{"type":"string"}}}},"settings":{"index":{"creation_date":"1456739938440","number_of_shards":"5","number_of_replicas":"1","uuid":"DwhS57l1TsKQFyzY23LSiQ","version":{"created":"2020099"}}},"warmers":{}}}

Now if I am modifying user as below I am able to do the same:

curl -XPOST 'http://localhost:9200/twitter/tweet/1/_update' -d '{
   "script" : "ctx._source.user=new_user",
   "params" : {
      "new_user" : "search"
   }
}'

But when I tried modifying the date fields as below it is giving an exception :

curl -XPOST 'http://localhost:9200/twitter/tweet/1/_update' -d '{
   "script" : "ctx._source.post_date='new-date'",
   "params" : {
      "new-date" : "2016-02-02T16:12:23"
   }
}'

Exception received is :

{"error":{"root_cause":[{"type":"remote_transport_exception","reason":"[Anomaly][127.0.0.1:9300][indices:data/write/update[s]]"}],"type":"illegal_argument_exception","reason":"failed to execute script","caused_by":{"type":"script_exception","reason":"Failed to compile inline script [ctx._source.post_date=new-date] using lang [groovy]","caused_by":{"type":"script_exception","reason":"failed to compile groovy script","caused_by":{"type":"multiple_compilation_errors_exception","reason":"startup failed:\ne90a551666b36d90e4fc5b08d04250da5c4d552d: 1: unexpected token: - @ line 1, column 26.\n ctx._source.post_date=new-date\n
^\n\n1 error\n"}}}}

Now can anyone let me know how I can handle the same.

~Prashant

Upvotes: 0

Views: 4541

Answers (2)

Oyeme
Oyeme

Reputation: 11225

POST your_index_name/_update_by_query?conflicts=proceed
{
    "script" : {
      "source": "ctx._source.publishedDate=new SimpleDateFormat('yyyy-MM-dd').parse('2021-05-07')",
      "lang": "painless"  
    }
}
  • publishedDate - the name of your date field.
  • Your_index_name the name of you index

Upvotes: 2

Jérémie B
Jérémie B

Reputation: 11022

In Groovy (or in Java), an identifier can't contain a '-'. If you write

ctx._source.last-login = new-login

Groovy (and java!) parses this into :

(ctx._source.last)-(login) = (new)-(login)

You should quote these properties :

ctx._source.'last-login' = 'new-login'

Upvotes: 0

Related Questions