elastic search, is it possible to update nested objects without updating the entire document?

后端 未结 3 1772
陌清茗
陌清茗 2020-12-02 17:25

I\'m indexing a set of documents (imagine them as forum posts) with a nested object which is the user related to that post. My problem is that the user fields might be updat

3条回答
  •  暖寄归人
    2020-12-02 17:46

    You can use the 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"}
        }
    }'
    

    See this SO answer for full detail.

    Note that update scripts support conditional logic, as shown here. So you could tag forum posts when the user changes, then iterate over the posts to update only posts with changed users.

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

    UPDATED

    Perhaps my ternary operator example was incomplete. This was not mentioned in the question, but assuming that users change their info in a separate part of the app, it would be nice to apply those changes to the forum posts in one script. Instead of using tags, try checking the user field directly for changes:

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

    As mentioned, though, this may be a slower operation than reindexing the full posts.

提交回复
热议问题