业务场景
一个方法中涉及到先插入一条es数据,然后再修改刚刚新增的这条数据(丰富这条数据的内容)。
//新增es信息
esUtil.addEsInfo(indexName, id, map)
//修改es信息
esUtil.updateEsInfo(updateByQuery);
新增操作的代码
public boolean addEsInfo(String index, String id, Map<String, Object> jsonMap) {
try {
IndexRequest indexRequest = new IndexRequest(index);
if (null != id) {
indexRequest = new IndexRequest(index).id(id);
}
indexRequest.source(jsonMap);
IndexResponse indexResponse = restHighLevelClient.index(indexRequest,
RequestOptions.DEFAULT);
return indexResponse != null;
} catch (IOException e) {
log.error("elasticsearch indexBase错误:{}", e.getMessage(), e);
throw new SunyardException(ResultCode.SYSTEM_ERROR, e.toString());
}
}
修改操作的代码
public boolean updateEsInfo(UpdateByQueryRequest updateByQuery) {
try {
BulkByScrollResponse response = restHighLevelClient.updateByQuery(updateByQuery,
RequestOptions.DEFAULT);
return response.getStatus().getUpdated() > 0 ? true : false;
} catch (IOException e) {
log.error("elasticsearch updateByQuery错误:{}", e.getMessage(), e);
return false;
}
}
出现问题
导致es中只能看到新增操作中的信息,修改操作中的信息没有显示,修改失败了,然后我打断电一步一步执行发现修改成功了,然后我就在中间设置了睡眠两秒,修改也成功了。
//新增es信息
esUtil.addEsInfo(indexName, id, map)
try {
Thread.sleep(2000);
log.info("睡了2秒");
} catch (InterruptedException e) {
e.printStackTrace();
}
//修改es信息
esUtil.updateEsInfo(updateByQuery);
当时我就蒙了,这也没有涉及到异步并发,为什么非要睡一会才行,当时问ChatGPT问了好久没问出个什么结果和原因,实在没办法了选择下班回家,在地铁上不死心,我就再csdn上查了一下,就看了一篇文章感觉这个博主说的很有道理准备第二天上班就试验一下。到了第二天果然就是这个问题,问题完美解决,CSDN YYDS!!!
问题解决
这个博主说:
elasticsearch是近实时搜索引擎,数据的可见性取决于索引刷盘间隔,正常设置1s刷一次你的写入最差的情况下要1秒后刷盘才可能被检索,但是写入可以通过参数控制强制刷盘来达到立即可见。
这就解释了为什么新增数据后非要睡一会才能修改成功该数据,
修改新增操作的代码
public boolean addEsInfo(String index, String id, Map<String, Object> jsonMap) {
try {
IndexRequest indexRequest = new IndexRequest(index);
if (null != id) {
indexRequest = new IndexRequest(index).id(id);
}
indexRequest.source(jsonMap);
IndexResponse indexResponse = restHighLevelClient.index(indexRequest,
RequestOptions.DEFAULT);
//TODO 提高插入效率可以将刷新索引单独提出,修改数据前调刷新索引方法
// 立即刷新索引
RefreshRequest refreshRequest = new RefreshRequest(index);
restHighLevelClient.indices().refresh(refreshRequest, RequestOptions.DEFAULT);
return indexResponse != null;
} catch (IOException e) {
log.error("elasticsearch indexBase错误:{}", e.getMessage(), e);
throw new SunyardException(ResultCode.SYSTEM_ERROR, e.toString());
}
}
添加数据后强制刷盘,然后再修改这条数据,修改成功。
参考文档:
关于ElasticSearch7.x 异步并发读写的一些疑问_大数据-CSDN问答