在Elasticsearch中,如何使用无痛脚本获得字段长度?

vkc1a9a2  于 2023-03-17  发布在  ElasticSearch
关注(0)|答案(2)|浏览(189)

如果字段比索引中现有的字段长,我尝试更新字段,但是这两个函数似乎都无法获取字段的长度

ctx._source.description.length() < params.description.length()
ctx._source.description.size() < params.description.size()
ctx._source.description.length < params.description.length

我得到了同样的错误,方法不存在。有什么想法如何实现这一点?
编辑:
这是我得到的错误:

array:1 [
  "update" => array:5 [
    "_index" => "products_a"
    "_type" => "_doc"
    "_id" => "XjouMXoBeY37PI1TSOQl"
    "status" => 400
    "error" => array:3 [
      "type" => "illegal_argument_exception"
      "reason" => "failed to execute script"
      "caused_by" => array:6 [
        "type" => "script_exception"
        "reason" => "runtime error"
        "script_stack" => array:2 [
          0 => """
            if (ctx._source.description.length()<params.description.length()) {\n
            \t\t\t\t\t\t\t\t
            """
          1 => "                           ^---- HERE"
        ]
        "script" => "add_new_seller_to_existing_doc"
        "lang" => "painless"
        "caused_by" => array:2 [
          "type" => "illegal_argument_exception"
          "reason" => "dynamic method [java.util.ArrayList, length/0] not found"
        ]
      ]
    ]
  ]
]

编辑二:
存储的脚本

$params = [
        'id' => 'add_new_seller_to_existing_doc',
        'body' => [
            'script' => [
                'lang' => 'painless',
                'source' =>
                    'if(params.containsKey(\'description\')){
                        if (!ctx._source.containsKey(\'description\')) {
                            ctx._source.description=params.description;
                        } else if (ctx._source.description.length()<params.description.length()) {
                            ctx._source.description=params.description;
                        }
                    }'
            ]
        ]
    ];

批量更新命令:

$bulk_obj['body'][] = ['update' => ['_id' => $id, '_index' => 'products']];

    $bulk_obj['body'][] = ['id' => 'add_new_seller_to_existing_doc', 'params' => ['description'=>'some_description']];
liwlm1x9

liwlm1x91#

问题似乎是description字段是一个ArrayList,而您认为它是一个String。
您可以使用ArrayList.size(),也可以将ArrayList转换为String(如果它只包含一个字符串),然后使用String.length()

b4qexyjb

b4qexyjb2#

下面应该可以获得字段的长度:

doc['description'].value.length()

相关问题