首页 > 解决方案 > 如何为索引中的文档设置选择属性

问题描述

如何为索引中的文档设置选择属性,例如使用 spring-data-elasticsearchupdate foo_index set attr1=<attr1_value> where id=<document.id>

标签: elasticsearchspring-data-elasticsearch

解决方案


使用UpdateQuery(以下代码取自https://github.com/spring-projects/spring-data-elasticsearch/blob/a2ca312fb2812bd34781206e47be31e9e43dac00/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateTests.java# L1565-L1594 ):

@Test
public void shouldDoPartialUpdateForExistingDocument() {

    // given
    String documentId = nextIdAsString();
    String messageBeforeUpdate = "some test message";
    String messageAfterUpdate = "test message";

    SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message(messageBeforeUpdate)
            .version(System.currentTimeMillis()).build();

    IndexQuery indexQuery = getIndexQuery(sampleEntity);

    operations.index(indexQuery, index);
    indexOperations.refresh();

    org.springframework.data.elasticsearch.core.document.Document document = org.springframework.data.elasticsearch.core.document.Document
            .create();
    document.put("message", messageAfterUpdate);
    UpdateQuery updateQuery = UpdateQuery.builder(documentId)//
            .withDocument(document) //
            .build();

    // when
    operations.update(updateQuery, index);

    // then
    SampleEntity indexedEntity = operations.get(documentId, SampleEntity.class, index);
    assertThat(indexedEntity.getMessage()).isEqualTo(messageAfterUpdate);
}

推荐阅读