序
最近工作中用到了 UpdateRequest ,踩了一些坑,于是去阅读了一下 UpdateRequest 的核心代码。
源码位置
es update 的核心代码位于 org.elasticsearch.action.update.UpdateHelper 这个类中。具体的方法如下:
public Result prepare(UpdateRequest request, IndexShard indexShard, LongSupplier nowInMillis) {
final GetResult getResult = indexShard.getService().getForUpdate(
request.type(), request.id(), request.ifSeqNo(), request.ifPrimaryTerm());
return prepare(indexShard.shardId(), request, getResult, nowInMillis);
}
过程分析
大体逻辑分为两步:
- 获取待更新文档的相关信息。
- 执行更新文档的操作。
获取待更新文档
其中在第一步,最终会调用 org.elasticsearch.index.engine.InternalEngine 中的以下方法:
public GetResult get(Get get, BiFunction<String, SearcherScope, Engine.Searcher> searcherFactory) throws EngineException {
assert Objects.equals(get.uid().field(), IdFieldMapper.NAME) : get.uid().field();
try (ReleasableLock ignored = readLock.acquire()) {
ensureOpen();
SearcherScope scope;
if (get.realtime(