Elasticsearch部分更新集合

时间:2017-12-15 12:00:40

标签: spring elasticsearch spring-data spring-data-elasticsearch

我在Spring启动项目中使用Spring Data Elasticsearch API,我有以下DeviceVO类:

@Document(indexName = "devices", type = "device")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class DeviceVO {

    @Id
    private String id;

    @Field(type = FieldType.text)
    private String name;

    //other fields

    @Field(type = FieldType.Nested)
    private Set<DeviceTagVO> deviceTags;

    private LocalDateTime createdOn;
}

我需要通过在DeviceTag集中添加/删除标记来部分更新此文档。

我知道我可以使用以下用户来更新属性:

        IndexRequest indexRequest = new IndexRequest();
        indexRequest.source("name", newName);
        UpdateQuery updateQuery = new UpdateQueryBuilder().withId(DeviceVO.getId()).withClass(DeviceVO.class).withIndexRequest(indexRequest).build();
        elasticsearchTemplate.update(updateQuery);

如何使用更新查询将删除项添加到集?

1 个答案:

答案 0 :(得分:0)

由于Jest(由Spring使用)尚不支持,我们在更新查询中使用了内联脚本:

private void updateSearchIndexRemoveDeviceTag(DeviceVO deviceVO, DeviceTagVO tag) {


        String scriptTagId = "{\n" +
                "  \"script\": {\n" +
                "    \"lang\": \"painless\",\n" +
                "    \"inline\": \"(ctx._source.deviceTagIds = ctx._source.deviceTagIds ?: []).remove(ctx._source.deviceTagIds.indexOf(params.tags))\",\n" + //check if device tags is null
                "    \"params\": {\n" +
                "      \"tags\": \"" + tag.getId() + "\"\n" +
                "    }\n" +
                "  }\n" +
                "}";

        try {
            client.execute(new Update.Builder(scriptTagId).index("devices").type("device").id(deviceVO.getId()).build());

        } catch (IOException e) {
            throw new ElasticSearchException("error.updating.device.index", "remove device tag from index");
        }
    }