Elasticsearch源码分析之二------索引过程源码概要分析

Elasticsearch源码分析之二------索引过程源码概要分析

索引逻辑简单分析,这里只是理清主要的脉络,一些细节方面以后的文章或会阐述。
 
假如通过java api来调用es的索引接口,先是构造成一个json串(es里表示为XContent,是对要处理的内容进行抽象),在IndexRequest里面指定要索引文档到那个索引库(index)、其类型(type)还有文档的id,如果没有指定文档的id,es会通过UUID工具自动生成一个uuid,代码在IndexRequest的process方法内。
[java]  view plain copy
 
 
  1. if (allowIdGeneration) {  
  2.      if (id == null) {  
  3.          id(UUID.randomBase64UUID());  
  4.          opType(IndexRequest.OpType.CREATE);  
  5.      }  
  6.  }  
然后使用封装过netty的TransportService通过tcp协议发送请求到es服务器(rest的话就是通过http协议)。
 
服务器获得TransportAction后解析索引请求(TransportShardReplicationOperationAction)。到AsyncShardOperationAction.start()方法开始进行分片操作,先读取集群状态,把目标索引及其分片信息提取出来,根据索引数据的id、类型以及索引分片信息进行哈希取模,确定把该条数据分配到那个分片。
[java]  view plain copy
 
 
  1. private int shardId(ClusterState clusterState, String index, String type, @Nullable String id, @Nullable String routing) {  
  2.      if (routing == null) {  
  3.          if (!useType) {  
  4.              return Math.abs(hash(id) % indexMetaData(clusterState, index).numberOfShards());  
  5.          } else {  
  6.              return Math.abs(hash(type, id) % indexMetaData(clusterState, index).numberOfShards());  
  7.          }  
  8.      }  
  9.      return Math.abs(hash(routing) % indexMetaData(clusterState, index).numberOfShards());  
  10.  }  
 
并找到数据要分配到的分片的主分片,先把索引请求提交到主分片处理(TransportIndexAction.shardOperationOnPrimary)。
 
判断是否必须要指定routing值
[java]  view plain copy
 
 
  1. MappingMetaData mappingMd = clusterState.metaData().index(request.index()).mappingOrDefault(request.type());  
  2.   if (mappingMd != null && mappingMd.routing().required()) {  
  3.       if (request.routing() == null) {  
  4.           throw new RoutingMissingException(request.index(), request.type(), request.id());  
  5.       }  
  6.   }  
 
判断索引操作的类型,索引操作有两种,一种是INDEX,当要索引的文档id已经存在时,不会覆盖原来的文档,只是更新原来文档。一种是CREATE,当索引文档id存在时,会抛出该文档已存在的错误。
[java]  view plain copy
 
 
  1. if (request.opType() == IndexRequest.OpType.INDEX)   
调用InternalIndexShard进行索引操作
[java]  view plain copy
 
 
  1. Engine.Index index = indexShard.prepareIndex(sourceToParse)  
  2.         .version(request.version())  
  3.         .versionType(request.versionType())  
  4.         .origin(Engine.Operation.Origin.PRIMARY);  
  5. indexShard.index(index);  
通过(InternalIndexShard)查找与请求索引数据类型(type)相符的mapping。对要索引的json字符串进行解析,根据mapping转换为对应的解析结果ParsedDocument 。
[java]  view plain copy
 
 
  1. public Engine.Index prepareIndex(SourceToParse source) throws ElasticSearchException {  
  2.     long startTime = System.nanoTime();  
  3.     DocumentMapper docMapper = mapperService.documentMapperWithAutoCreate(source.type());  
  4.     ParsedDocument doc = docMapper.parse(source);  
  5.     return new Engine.Index(docMapper, docMapper.uidMapper().term(doc.uid()), doc).startTime(startTime);  
  6. }  
最后调用RobinEngine中的相关方法(添加或修改)对底层lucene进行操作,这里是写入到lucene的内存索引中(RobinEngine.innerIndex)。
[java]  view plain copy
 
 
  1. if (currentVersion == -1) {  
  2.        // document does not exists, we can optimize for create  
  3.        if (index.docs().size() > 1) {  
  4.            writer.addDocuments(index.docs(), index.analyzer());  
  5.        } else {  
  6.            writer.addDocument(index.docs().get(0), index.analyzer());  
  7.        }  
  8.    } else {  
  9.        if (index.docs().size() > 1) {  
  10.            writer.updateDocuments(index.uid(), index.docs(), index.analyzer());  
  11.        } else {  
  12.            writer.updateDocument(index.uid(), index.docs().get(0), index.analyzer());  
  13.        }  
  14.    }  
写入内存索引后还会写入到Translog(Translog是对索引的操作日志,会记录没有持久化的操作)中,防止flush前断电导致索引数据丢失。
[java]  view plain copy
 
 
  1. Translog.Location translogLocation = translog.add(new Translog.Create(create));  
主分片索引请求完就把请求发给副本进行索引操作。最后把成功信息返回给客户端。

猜你喜欢

转载自aoyouzi.iteye.com/blog/2126578
今日推荐