Elasticsearch 部分更新集合
Elasticsearch partial update collection
我在我的 Spring 引导项目中使用 Spring Data Elasticsearch API 并且我有以下 DeviceVO class:
@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;
}
我需要通过 adding/removing 标签将此文档部分更新到 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);
如何使用更新查询将删除项添加到集合中?
由于 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");
}
}
我在我的 Spring 引导项目中使用 Spring Data Elasticsearch API 并且我有以下 DeviceVO class:
@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;
}
我需要通过 adding/removing 标签将此文档部分更新到 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);
如何使用更新查询将删除项添加到集合中?
由于 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");
}
}