记录一:批量更新数据saveAll
引入maven依赖
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>4.0.9.RELEASE</version>
</dependency>
public interface DeviceRepository extends ElasticsearchRepository<Device,String> {
}
saveAll批量新增,如果数据存在则会更新数据
public void checkOnline() {
List<Device> filterList = new ArrayList<>();
QueryBuilder query = QueryBuilders.boolQuery()
.must(QueryBuilders.termQuery("checkLine", Constant.CHECK_OFFLINE));
Iterable<Device> searchResult = deviceRepository.search(query);
searchResult.forEach(item -> {
item.setCheckLine(Constant.CHECK_ONLINE);
filterList.add(item);
});
if (ObjectUtils.isNotEmpty(filterList)) {
deviceRepository.saveAll(filterList);
}
}
记录二:批量更新数据Script脚本更新字段
参考:Script query | Elasticsearch Guide [8.5] | Elastic
QueryBuilder query = QueryBuilders.boolQuery()
.must(QueryBuilders.termQuery("checkLine", Constant.CHECK_OFFLINE))
.must(QueryBuilders.rangeQuery("createTime").lte(new Date().getTime()));
Map<String, Object> params = new HashMap<>();
params.put("checkLine", Constant.CHECK_ONLINE);
Script script = new Script(ScriptType.INLINE,"painless","ctx._source.checkLine = params.checkLine",params);
UpdateByQueryRequest updateByQueryRequest = new UpdateByQueryRequest(indexName);
updateByQueryRequest.setQuery(query);
updateByQueryRequest.setScript(script);
BulkByScrollResponse response = elasticsearchRestTemplate.getClient().updateByQuery(updateByQueryRequest, RequestOptions.DEFAULT);
记录三:空字段查询处理
如果查询字段createTime在ES数据中不存在,直接用.must(QueryBuilders.rangeQuery("createTime").lte(new Date().getTime()))查询会报错;需要组装createTime介于时间范围和没有这个createTime字段的查询条件。
使用ES复合查询
参考:Boolean query | Elasticsearch Guide [7.4] | Elastic文章来源:https://www.toymoban.com/news/detail-669475.html
组合过滤器 | Elasticsearch: 权威指南 | Elastic文章来源地址https://www.toymoban.com/news/detail-669475.html
QueryBuilder query = QueryBuilders.boolQuery()
.must(QueryBuilders.termQuery("checkLine", Constant.CHECK_OFFLINE))
.should(QueryBuilders.rangeQuery("createTime").lte(new Date().getTime()))
.should(QueryBuilders.boolQuery().mustNot(QueryBuilders.existsQuery("createTime")));
Map<String, Object> params = new HashMap<>();
params.put("checkLine", Constant.CHECK_ONLINE);
Script script = new Script(ScriptType.INLINE,"painless","ctx._source.checkLine = params.checkLine",params);
UpdateByQueryRequest updateByQueryRequest = new UpdateByQueryRequest(indexName);
updateByQueryRequest.setQuery(query);
updateByQueryRequest.setScript(script);
BulkByScrollResponse response = elasticsearchRestTemplate.getClient().updateByQuery(updateByQueryRequest, RequestOptions.DEFAULT);
到了这里,关于Spring Data Elasticsearch 一些异常报错、注意事项(1)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!