小编典典

Elastic search,是否可以在不更新整个文档的情况下更新嵌套对象?

elasticsearch

我正在使用嵌套对象(与该帖子相关的用户)为一组文档建立索引(将它们想象为论坛帖子)。我的问题是用户字段可能已更新,但是由于帖子未更改,因此它们未重新索引,并且用户嵌套的对象已过时。有没有一种方法可以更新嵌套对象,而无需再次为整个文档重新编制索引?还是唯一的解决方案是在用户每次更改时重新索引该用户的所有相关帖子?


阅读 941

收藏
2020-06-22

共1个答案

小编典典

您可以使用Update API。

curl -XPOST localhost:9200/docs/posts/post/_update -d '{
    "script" : "ctx._source.nested_user = updated_nested_user",
    "params" : {
        "updated_nested_user" : {"field": "updated"}
    }
}'

需要注意的是更新脚本支持条件逻辑,如图所示这里。因此,您可以在用户更改时标记论坛帖子,然后遍历帖子以仅更新具有更改用户的帖子。

curl -XPOST 'localhost:9200/docs/posts/post/_update' -d '{
    "script" : "ctx._source.tags.contains(tag) ? "ctx._source.nested_user = updated_nested_John" : ctx.op = "none"",
    "params" : {
        "tag": "updated_John_tag",
        "updated_nested_John" : {"field": "updated"}
    }
}'

更新

也许我的三元运算符示例不完整。问题中没有提到这一点,但是假设用户在应用程序的单独部分中更改了他们的信息,最好将这些更改以一个脚本应用于论坛帖子。代替使用标签,尝试直接检查用户字段中的更改:

curl -XPOST 'localhost:9200/docs/posts/post/_update' -d '{
    "script" : "ctx._source.nested_user.contains(user) ? "ctx._source.nested_user = updated_nested_John" : ctx.op = "none"",
    "params" : {
        "user": "John",
        "updated_nested_John" : {"field": "updated"}
    }
}'

如上所述,这可能比重新索引完整帖子的速度要慢。

2020-06-22