【问题标题】:Upserting an elasticsearch document插入弹性搜索文档
【发布时间】:2017-08-16 17:05:02
【问题描述】:

这是我使用的代码。 DocumentModel 类用作 elasticsearch 文档。目前我使用 url 作为 elasticsearch '_id' ,并使用 java 为其他字段 documentId 生成 UUID。当我尝试使用此代码索引文档时,它会更新文档(如果存在)或索引(如果不存在)。问题是当它更新文档时,它也会更新documentId。但我不需要更新 documentId 并使用现有的 documentId。 我应该对此代码进行哪些更改?

    String uuid = UUID.randomUUID().toString();
                        documentModel.setDocumentID(uuid);
                        String jsonForIndex = gson.toJson(documentModel);
                        IndexRequest indexRequest = new IndexRequest(indexName, typeName, documentModel.getId());
                        indexRequest.source(jsonForIndex);
                        UpdateRequest updateRequest = new UpdateRequest(indexName, typeName, documentModel.getId());
                        updateRequest.doc(jsonForUpdate);
                        updateRequest.upsert(indexRequest);
                        UpdateQuery updateQuery = new UpdateQueryBuilder().withIndexName(indexName).withType(typeName)
                                .withId(documentModel.getId()).withDoUpsert(true).withUpdateRequest(updateRequest).withIndexRequest(indexRequest).build();
elasticsearchTemplate.update(updateQuery).getId();

【问题讨论】:

    标签: java elasticsearch


    【解决方案1】:

    如果你想把它作为一个elasticsearch原子操作来执行,你可以使用ES脚本来处理documentId字段并保留已经存在的字段。

    但是如果你想改用Java,你可以执行get,如果存在则使用文档ID创建新的,并且仅在没有版本更改时才索引。

    类似(伪代码):

    old = client.prepareGet(indexName, type, uuid).get();
    
    client.prepareIndex(indexName, type, uuid).setSource(<or the way you build it>).setVersion(old.getVersion() <if old is not null>).setRefresh(true).get();
    

    如果并发事务修改了您尝试更新的文档,它将引发 VersionConflictEngineException。您可以使用带有此异常的 Spring Retry 并再次执行 get/index(如果它是所需的行为,则 let if fail)。

    【讨论】:

    • 谢谢。有没有办法使用 UpdateQuery 使用 IndexRequest 和 UpdateRequest(不使用 prepareGet)来做到这一点?
    猜你喜欢
    • 2021-06-20
    • 2015-12-18
    • 1970-01-01
    • 2022-08-12
    • 1970-01-01
    • 1970-01-01
    • 2015-06-01
    • 2016-08-19
    • 1970-01-01
    相关资源
    最近更新 更多