欢迎来到 白山市某某电子科技有限责任公司
全国咨询热线:020-123456789
联系我们

地址:联系地址联系地址联系地址

电话:020-123456789

传真:020-123456789

邮箱:admin@aa.com

新闻中心
ES 源码分析之数据类型转换
  来源:白山市某某电子科技有限责任公司  更新时间:2024-05-03 03:04:01

ES 源码分析之数据类型转换

公司有的源码小伙伴问我 ,为什么不推荐我们使用 nested 结构呢  ,分析还说性能低。据类那么,型转ES 针对 nested 之类的源码结构 。因为ES 源码我也基本看完了。分析索性,据类直接写成笔记。型转比直接在代码里面写注释来的源码更舒心点。

1问题描述

  • ES 是分析 lucene 不仅仅是集群版的概念,还有涉及到支持丰富的据类数据类型。如 nested  、型转object 等等结构  。源码它是分析怎么支持的呢 ?
  • ES 还支持 _id 、_version 等等字段 。据类这种是怎么存储的呢?
  • 听说 ES 的 parent doc 和 nested doc 是分开来存储的 ,那么获取的时候,他们是通过哪种关系关联的呢  ?

2类型转换

2.1初步代码入口

代码具体入口 org.elasticsearch.index.shard.IndexShard#prepareIndex

public static Engine.Index prepareIndex(DocumentMapperForType docMapper, SourceToParse source, long seqNo,n long primaryTerm, long version, VersionType versionType, Engine.Operation.Origin origin,n long autoGeneratedIdTimestamp, boolean isRetry,n long ifSeqNo, long ifPrimaryTerm) { n long startTime = System.nanoTime();nn // 涉及到 nested 等等结构的转换,直接看【2.2 类型具体转换代码】n ParsedDocument doc = docMapper.getDocumentMapper().parse(source);nn // Mapping 是否要处理n if (docMapper.getMapping() != null) { n doc.addDynamicMappingsUpdate(docMapper.getMapping());n }nn // _id 转 uid 。这里是为了数据能保持整齐  ,方便压缩。可以参考 【哈夫曼编码】 。n Term uid = new Term(IdFieldMapper.NAME, Uid.encodeId(doc.id()));nn return new Engine.Index(uid, doc, seqNo, primaryTerm, version, versionType, origin, startTime, autoGeneratedIdTimestamp, isRetry,n ifSeqNo, ifPrimaryTerm);n }n

2.2类型具体转换代码

/**n * 内部转换文档,如果有 nested 结构,需要再次转换一下n * @param mappingn * @param contextn * @param parsern * @throws IOExceptionn */n private static void internalParseDocument(Mapping mapping, MetadataFieldMapper[] metadataFieldsMappers,n ParseContext context, XContentParser parser) throws IOException { n final boolean emptyDoc = isEmptyDoc(mapping, parser);nn /**n * 预处理,为 root document 拆开,添加如下 :比如,_id、_version 也是一个 document ,具体看下面的 【2.3 支持 _id 之类的字段】n */n for (MetadataFieldMapper metadataMapper : metadataFieldsMappers) { n metadataMapper.preParse(context);n }nn if (mapping.root.isEnabled() == false) { n // entire type is disabledn parser.skipChildren();n } else if (emptyDoc == false) { n // 转换对象或者 nested 结构 ,这个方法会反复递归调用 。主要是 object 结构或者 nested 结构n parseObjectOrNested(context, mapping.root);n }nn // 为各个非 root document 添加 _version 等等字段n for (MetadataFieldMapper metadataMapper : metadataFieldsMappers) { n metadataMapper.postParse(context);n }n }n

2.3前置处理之支持_id之类的字段

代码位置 :org.elasticsearch.index.mapper.MetadataFieldMapper#preParse
下面只贴出 _id 的处理

/**n * _id 也是一个 docn * @param contextn */n @Overriden public void preParse(ParseContext context) { n BytesRef id = Uid.encodeId(context.sourceToParse().id());n context.doc().add(new Field(NAME, id, Defaults.FIELD_TYPE));n }n

这里只是了其中的一个例子 :_id  ,其他的比如 _version、_seqno、_source 等等处理也类似。

2.4转换复杂的结构 ,比如nested结构

ES 在转换 nested 结构的时候,比较有意思 。

2.4.1类型转换整体入口

/**n * 转换 object 或者 nested 结构的 ,这里会出现递归调用,主要是为了解决 object 、nested 结构n * @param contextn * @param mappern * @throws IOExceptionn */n static void parseObjectOrNested(ParseContext context, ObjectMapper mapper) throws IOException { n if (mapper.isEnabled() == false) { n context.parser().skipChildren();n return;n }n XContentParser parser = context.parser();n XContentParser.Token token = parser.currentToken();n if (token == XContentParser.Token.VALUE_NULL) { n // the object is null ("obj1" : null), simply bailn return;n }nn String currentFieldName = parser.currentName();n if (token.isValue()) { n throw new MapperParsingException("object mapping for [" + mapper.name() + "] tried to parse field [" + currentFieldNamen + "] as object, but found a concrete value");n }nn ObjectMapper.Nested nested = mapper.nested();n // 如果是 nested 结构,每次都会new 一个空白的 document ,而且 ,这个方法 #{ innerParseObject},是递归实现,把 object 或者 document 变成多个 documentn if (nested.isNested()) { n // 进入下方的 :【2.4.2 nested 转换初步入口】n context = nestedContext(context, mapper);n }nn // if we are at the end of the previous object, advancen if (token == XContentParser.Token.END_OBJECT) { n token = parser.nextToken();n }n if (token == XContentParser.Token.START_OBJECT) { n // if we are just starting an OBJECT, advance, this is the object we are parsing, we need the name firstn token = parser.nextToken();n }nn // 转换对象n innerParseObject(context, mapper, parser, currentFieldName, token);nn // restore the enable path flagn if (nested.isNested()) { n nested(context, nested);n }n }n

2.4.2nested转换初步入口

/**n * 内部转换 nested 结构,生成一个空白的 nested 结构n * TODO nested 文档的 _id 既然跟父文档的一样 ,lucene 写入每个 doc ,都是拼接 。那么,在get 的时候,自然会获取到相同的 _id 多个文档,包含了 nested 结构 。然后,再内部转换为我们 最想要的结果。n * @param contextn * @param mappern * @returnn */n private static ParseContext nestedContext(ParseContext context, ObjectMapper mapper) { nn // 创建 nested 上下文,并且,new 一个空白的 document 。为后面的 nested 的字段或者对象之类的 ,全部加上n context = context.createNestedContext(mapper.fullPath());nn ParseContext.Document nestedDoc = context.doc();n ParseContext.Document parentDoc = nestedDoc.getParent();nn // We need to add the uid or id to this nested Lucene document too,n // If we do not do this then when a document gets deleted only the root Lucene document gets deleted andn // not the nested Lucene documents! Besides the fact that we would have zombie Lucene documents, the ordering ofn // documents inside the Lucene index (document blocks) will be incorrect, as nested documents of different rootn // documents are then aligned with other root documents. This will lead tothe nested query, sorting, aggregationsn // and inner hits to fail or yield incorrect results.n IndexableField idField = parentDoc.getField(IdFieldMapper.NAME);n if (idField != null) { n // We just need to store the id as indexed field, so that IndexWriter#deleteDocuments(term) can thenn // delete it when the root document is deleted too.n nestedDoc.add(new Field(IdFieldMapper.NAME, idField.binaryValue(), IdFieldMapper.Defaults.NESTED_FIELD_TYPE));n } else { n throw new IllegalStateException("The root document of a nested document should have an _id field");n }nn // the type of the nested doc starts with __, so we can identify that its a nested one in filtersn // note, we don't prefix it with the type of the doc since it allows us to execute a nested queryn // across types (for example, with similar nested objects)n nestedDoc.add(new Field(TypeFieldMapper.NAME, mapper.nestedTypePathAsString(), TypeFieldMapper.Defaults.NESTED_FIELD_TYPE));n return context;n }n

仔细看看里面的英文。主要的一点是 :nested 结构的 _id 和 parent 的 _id 保持一致 。那么,通过 GET docId 这种操作,就可以拿到所有的文档了 。而且  ,删除的时候,特别的方便。算是 ES 这种的一个方案吧。

2.4.3数据处理

每个字段的填充入口在 :org.elasticsearch.index.mapper.DocumentParser#innerParseObject
这里是一个递归调用的操作 。比较绕 。

2.5后置处理之设置_version等等

下面贴出来 _version 的处理
代码的入口  :org.elasticsearch.index.mapper.VersionFieldMapper#postParse ,可以看看具体的实现。

@Overriden public void postParse(ParseContext context) { n // In the case of nested docs, let's fill nested docs with version=1 so that Lucene doesn't write a Bitset for documentsn // that don't have the field. This is consistent with the default value for efficiency.n Field version = context.version();n assert version != null;n for (Document doc : context.nonRootDocuments()) { n // 为此 doc 添加一个 _version 字段n doc.add(version);n }n }n

这里支持举了 _version 举个例子 ,其他类似。

3总结

  • ES 是 lucene 不仅仅是集群版的概念 ,还有涉及到支持丰富的数据类型。如 nested  、object 等等结构 。它是怎么支持的呢 ?
    答:ES 针对 nested 、object 直接拍平处理
  • ES 还支持 _id、_version 等等字段 。这种是怎么存储的呢?
    答 :ES 针对 _id 、_version 是保存为独立的文档的 。
  • 听说 ES 的 parent doc 和 nested doc 是分开来存储的,那么获取的时候,他们是通过那种关系关联的呢?
    答:通过 root Doc 的 ID 来做关联的 。

4其他

后续请关注 ES 写入流程。让我们看看 ES 是如何处理分布式请求及保证高可用的 。


友情链接警惕!微信出现这两个界面,马上停手七爪源码:如何在 JavaScript 中将分钟转换为小时和分钟为什么有人能徒手拍钢水?莱顿弗罗斯特效应又是什么?如何在Java中将两个类模块连接在一起?java学习笔记(二):类型转换和运算符2台S7-1200PLC modbus 通信Victoriametrics大胆地将边缘计算带入太空边缘新能源特征设计五菱宏光MINI有对手了!新SUV更漂亮,只卖6.57万麻省理工学院的微型机器人:闪电虫子飞起来啦FLOKI即将颠覆和震撼整个加密空间啥叫MCN名词-机构?跨境电商卖家如何突破知识产权“围猎”?要玩转华为多屏协同,少一台华为笔记本能行吗?易观千帆银行用户体验中心成立,助力银行业用户体验升级解决续航焦虑,奥睿科新能源汽车随车充让我外出游玩更加放心骁龙8+旗舰怎么选?这三款便宜又好用超出预期的文石BOOX墨水屏,来看看他们是怎么说的Apollo全线赋能百度地图,北京市高级别自动驾驶示范区首发全新版本七爪源码:使用 Django 和 HTMX 构建简单的 CRM—项目设置卖到8000以上的两款手机,看看顶级旗舰的产品力怎么样8月12日A股精选资讯:小米多点局部,这些企业又有新动态7月安全更新:三星Galaxy A52s 5G获更新,修复50多个安全漏洞新能源车上这几个配置看似高大上,实际全是“败笔”7月新能源厂商销量榜:比亚迪遥遥领先,吉利领涨,理想落榜网达软件(603189.SH)拟于北京设全资子公司以拓展业务可观测宇宙到底有多少星辰荣耀5500mAh新机亮相,7.英寸+天玑8100,定位中端市场NET+EF+MVC实现后台文章链接批量推送到百度搜索引擎进行收录B. Mark the Dust Sweeper(思维)华为已成为广告推送机?5大手机系统横评,小米竟然是“背锅侠”美国6月通货膨胀创新高,跨境电商该如何应对?漫画阅读平台Mangatoon泄露2300万用户信息实测过后确认,宝马i4就是纯电版的新4系人类最渴望的时间穿越,有望实现吗?一口气交付10000辆!长安Lumin喜提“第一桶金”中亚灌溉的区域气候效应研究获进展腾讯战争手游《征服与霸业》宣布停止运营微信内测朋友圈共同回忆功能Sentry 一个错误跟踪和性能监控平台
联系我们

地址:联系地址联系地址联系地址

电话:020-123456789

传真:020-123456789

邮箱:admin@aa.com

6.6129

Copyright © 2024 Powered by 白山市某某电子科技有限责任公司   sitemap