赞
踩
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
为了支持更复杂的条件查询,再日益膨胀的数据下提供高性能查询,elasticsearch 成为了不错的选择,在使用过程中遇到了一些问题,也摸索出了解决方案(且在当时没百度到),在此记录下
希望能帮助到遇到同样问题的人
PublishSearchRepository 有save和saveall方法 一般少量数据插入是没问题的,但是大批量插入,如数据初始化时, 将会引起异常(这个也与服务器性能相关),当时我就遇到了两种不同的异常, 1 too many connections 2.too large data
解决方案是采用 bulkIndex 插入 ,此处献上部分代码
- @Autowired
- private ElasticsearchRestTemplate elasticsearchTemplate;
- //部分代码....
- //将doc数据转成 IndexQuery
- List<IndexQuery> indexQueryList;
- indexQueryList = Lists.transform(recordDocList, s -> {
- IndexQuery query = new IndexQuery();
- query.setObject(s);
- return query;
- });
-
- //分批次插入 这个量可以更大 视服务器性能而定(带宽/数据量大小/服务器性能)
- int last;
- int batchSize = 500;
- for (int i = 0; i < indexQueryList.size()/batchSize + 1; i++) {
- last = Math.min((i + 1) * batchSize, indexQueryList.size());
- elasticsearchTemplate.bulkIndex(indexQueryList.subList(i*batchSize, last), IndexCoordinates.of("shipment"));
- }

百度上有篇博客说
PublishSearchRepository.save(Docment) docment如果传id执行新增,不传执行更新,实测下来发现,确实实现了更新效果,这个实现方式类似于mysql中 delete + insert
更新是更新了,但是数据只能全量覆盖,不能指定更新的列(Docment中为 field)
查看文档后发现
ElasticsearchRestTemplate存在update方法,尝试使用,发现可以实现更新指定列
- //实现全量更新
- ShipmentRecordDoc recordDoc = new ShipmentRecordDoc();
- UpdateQuery updateQuery = UpdateQuery.builder(recordDoc.getShipmentRecordId())
- .withDocument(Document.from(BeanUtil.beanToMap(recordDoc)))
- .withParams(BeanUtil.beanToMap(recordDoc))
- .build();
-
-
-
-
- //实现部分更新
- ShipmentRecordDoc recordDoc = new ShipmentRecordDoc();
- UpdateQuery updateQuery = UpdateQuery.builder(recordDoc.getShipmentRecordId())
- .withDocument(Document.from(BeanUtil.beanToMap(recordDoc, false, true)))
- .withParams(BeanUtil.beanToMap(recordDoc, false, true))
- .build();
-
-
- //发现区别了吗,BeanUtil.beanToMap(recordDoc, false, true),这个是hutool的工具类,第一个false表示是否驼峰转下划线,第二个boolean代表是否忽略null值,withDocument会生成对应更新脚本,只传入相应字段,便可以实现部分更新了

~~~
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。