【问题标题】:Elasticsearch java api update API with json as value以json为值的Elasticsearch java api更新API
【发布时间】:2016-04-27 21:07:34
【问题描述】:

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

这是来自 elasticsearch 参考站点的一个示例,用于使用新字段更新现有文档。 https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html

我想用“新字段”更新现有文档,但用 json 作为“新字段的值”而不是单个字符串作为“新字段的值”。就像下面一样。

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

返回如下错误。

{
  "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
}

是否可以用“json value”更新现有文档?还是每个更新请求都应该有单个字符串值?

【问题讨论】:

    标签: json elasticsearch


    【解决方案1】:

    你可以试试Updates with a partial document:https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html#_updates_with_a_partial_document

    喜欢:

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

    【讨论】:

    • 我仍然低于.. { "error": { "root_cause": [ { "type": "mapper_parsing_exception", "reason": "failed to parse [test]" } ] ,“type”:“mapper_parsing_exception”,“reason”:“无法解析 [test]”,“caused_by”:{“type”:“illegal_argument_exception”,“reason”:“未知属性 [newTest]”}},“状态”:400 }
    【解决方案2】:

    如果你想添加一个 JSON 对象,只需使用 groovy 哈希,就像这样

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

    之后您的对象将如下所示

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

    【讨论】:

    • 您是否将 ['newTest': 'hello'] 称为常规哈希?这和 json 有什么不同?
    • 也是一样的,索引的时候会转成JSON。 groovy 哈希在概念上等同于 JSON 哈希。
    猜你喜欢
    • 1970-01-01
    • 2014-05-12
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    相关资源
    最近更新 更多