简体   繁体   中英

Elasticsearch java api update API with json as value

curl -XPOST 'localhost:9200/test/type1/1/_update' -d '{ "script" : "ctx._source.name_of_new_field = \\"value_of_new_field\\"" }'

This is one example from elasticsearch reference site to update existing document with new field. https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html

And I want to update existing document with "new filed" but with json as a "value of new field" instead of single string as "value of new filed". just like below.

curl -XPOST 'localhost:9200/test/type1/1/_update' -d '{ "script" : "ctx._source.test = {\\"newTest\\":\\"hello\\"}" }'

which returns error like below.

{
  "error": {
    "root_cause": [
      {
        "type": "remote_transport_exception",
        "reason": "[Ravage 2099][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.test2 = {\"test2\":\"hihi\"}] using lang [groovy]",
      "caused_by": {
        "type": "script_exception",
        "reason": "failed to compile groovy script",
        "caused_by": {
          "type": "multiple_compilation_errors_exception",
          "reason": "startup failed:\n4e487d5bc8afde27adf29b77e8427f5da1534843: 1: expecting '}', found ':' @ line 1, column 29.\n   ctx._source.test2 = {\"test2\":\"hihi\"}\n                               ^\n\n1 error\n"
        }
      }
    }
  },
  "status": 400
}

Is it even possible to update existing document with "json value"? or every update request should have single string value?

You can try Updates with a partial document : https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html#_updates_with_a_partial_document

Like:

curl -XPOST 'localhost:9200/test/type1/1/_update' -d '{
"doc" : {
    "test" : {
         "newTest" : "hello"
        }
    }
}'

If you want to add a JSON object, simply use a groovy hash, like this

curl -XPOST 'localhost:9200/test/type1/1/_update' -d '{ 
   "script" : "ctx._source.test = ['newTest':'hello']" 
}'

Your object will look like this afterwards

{
    "test": {
        "newTest": "hello"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM