iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >elasticsearch索引index之put mapping怎么设置
  • 236
分享到

elasticsearch索引index之put mapping怎么设置

2023-06-30 08:06:23 236人浏览 独家记忆
摘要

本篇内容主要讲解“elasticsearch索引index之put mapping怎么设置”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“elasticsearch索引index之put

本篇内容主要讲解“elasticsearch索引index之put mapping怎么设置”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“elasticsearch索引index之put mapping怎么设置”吧!

    mapping机制使得elasticsearch索引数据变的更加灵活,近乎于no schema。mapping可以在建立索引时设置,也可以在后期设置。后期设置可以是修改mapping(无法对已有的field属性进行修改,一般来说只是增加新的field)或者对没有mapping的索引设置mapping。put mapping操作必须是master节点来完成,因为它涉及到集群matedata的修改,同时它跟index和type密切相关。修改只是针对特定index的特定type。

    在Action support分析中我们分析过几种Action的抽象类型,put mapping Action属于TransportMasternodeOperationAction的子类。它实现了masterOperation方法,每个继承自TransportMasterNodeOperationAction的子类都会根据自己的具体功能来实现这个方法。这里的实现如下所示:

    protected void masterOperation(final PutMappingRequest request, final ClusterState state, final ActionListener<PutMappingResponse> listener) throws ElasticsearchException {        final String[] concreteIndices = clusterService.state().metaData().concreteIndices(request.indicesOptions(), request.indices());      //构造request        PutMappinGClusterStateUpdateRequest updateRequest = new PutMappingClusterStateUpdateRequest()                .ackTimeout(request.timeout()).masterNodeTimeout(request.masterNodeTimeout())                .indices(concreteIndices).type(request.type())                .source(request.source()).ignoreConflicts(request.ignoreConflicts());      //调用putMapping方法,同时传入一个Listener        metaDataMappingService.putMapping(updateRequest, new ActionListener<ClusterStateUpdateResponse>() {            @Override            public void onResponse(ClusterStateUpdateResponse response) {                listener.onResponse(new PutMappingResponse(response.isAcknowledged()));            }            @Override            public void onFailure(Throwable t) {                logger.debug("failed to put mappings on indices [{}], type [{}]", t, concreteIndices, request.type());                listener.onFailure(t);            }        });    }

    以上是TransportPutMappingAction对masterOperation方法的实现,这里并没有多少复杂的逻辑和操作。具体操作在matedataMappingService中。跟之前的CreateIndex一样,put Mapping也是向master提交一个updateTask。所有逻辑也都在execute方法中。这个task的基本跟CreateIndex一样,也需要在给定的时间内响应。它的代码如下所示:

    public void putMapping(final PutMappingClusterStateUpdateRequest request, final ActionListener<ClusterStateUpdateResponse> listener) {    //提交一个高基本的updateTask        clusterService.submitStateUpdateTask("put-mapping [" + request.type() + "]", Priority.HIGH, new AckedClusterStateUpdateTask<ClusterStateUpdateResponse>(request, listener) {            @Override            protected ClusterStateUpdateResponse newResponse(boolean acknowledged) {                return new ClusterStateUpdateResponse(acknowledged);            }            @Override            public ClusterState execute(final ClusterState currentState) throws Exception {                List<String> indicesToClose = Lists.newArrayList();                try {            //必须针对已经在matadata中存在的index,否则抛出异常                    for (String index : request.indices()) {                        if (!currentState.metaData().hasIndex(index)) {                            throw new IndexMissingException(new Index(index));                        }                    }                    //还需要存在于indices中,否则无法进行操作。所以这里要进行预建                    for (String index : request.indices()) {                        if (indicesService.hasIndex(index)) {                            continue;                        }                        final IndexMetaData indexMetaData = currentState.metaData().index(index);              //不存在就进行创建                        IndexService indexService = indicesService.createIndex(indexMetaData.index(), indexMetaData.settings(), clusterService.localNode().id());                        indicesToClose.add(indexMetaData.index());                        // make sure to add custom default mapping if exists                        if (indexMetaData.mappings().containsKey(MapperService.DEFAULT_MAPPING)) {                            indexService.mapperService().merge(MapperService.DEFAULT_MAPPING, indexMetaData.mappings().get(MapperService.DEFAULT_MAPPING).source(), false);                        }                        // only add the current relevant mapping (if exists)                        if (indexMetaData.mappings().containsKey(request.type())) {                            indexService.mapperService().merge(request.type(), indexMetaData.mappings().get(request.type()).source(), false);                        }                    }            //合并更新Mapping                    Map<String, DocumentMapper> newMappers = newHashMap();                    Map<String, DocumentMapper> existingMappers = newHashMap();            //针对每个index进行Mapping合并                    for (String index : request.indices()) {                        IndexService indexService = indicesService.indexServiceSafe(index);                        // try and parse it (no need to add it here) so we can bail early in case of parsing exception                        DocumentMapper newMapper;                        DocumentMapper existingMapper = indexService.mapperService().documentMapper(request.type());                        if (MapperService.DEFAULT_MAPPING.equals(request.type())) {//存在defaultmapping则合并default mapping                            // _default_ types do not Go through merging, but we do test the new settings. Also don't apply the old default                            newMapper = indexService.mapperService().parse(request.type(), new CompressedString(request.source()), false);                        } else {                            newMapper = indexService.mapperService().parse(request.type(), new CompressedString(request.source()), existingMapper == null);                            if (existingMapper != null) {                                // first, simulate                                DocumentMapper.MergeResult mergeResult = existingMapper.merge(newMapper, mergeFlags().simulate(true));                                // if we have conflicts, and we are not supposed to ignore them, throw an exception                                if (!request.ignoreConflicts() && mergeResult.hasConflicts()) {                                    throw new MergeMappingException(mergeResult.conflicts());                                }                            }                        }                        newMappers.put(index, newMapper);                        if (existingMapper != null) {                            existingMappers.put(index, existingMapper);                        }                    }                    String mappingType = request.type();                    if (mappingType == null) {                        mappingType = newMappers.values().iterator().next().type();                    } else if (!mappingType.equals(newMappers.values().iterator().next().type())) {                        throw new InvalidTypeNameException("Type name provided does not match type name within mapping definition");                    }                    if (!MapperService.DEFAULT_MAPPING.equals(mappingType) && !PercolatorService.TYPE_NAME.equals(mappingType) && mappingType.charAt(0) == '_') {                        throw new InvalidTypeNameException("Document mapping type name can't start with '_'");                    }                    final Map<String, MappingMetaData> mappings = newHashMap();                    for (Map.Entry<String, DocumentMapper> entry : newMappers.entrySet()) {                        String index = entry.geTKEy();                        // do the actual merge here on the master, and update the mapping source                        DocumentMapper newMapper = entry.getValue();                        IndexService indexService = indicesService.indexService(index);                        if (indexService == null) {                            continue;                        }                        CompressedString existingSource = null;                        if (existingMappers.containsKey(entry.getKey())) {                            existingSource = existingMappers.get(entry.getKey()).mappingSource();                        }                        DocumentMapper mergedMapper = indexService.mapperService().merge(newMapper.type(), newMapper.mappingSource(), false);                        CompressedString updatedSource = mergedMapper.mappingSource();                        if (existingSource != null) {                            if (existingSource.equals(updatedSource)) {                                // same source, no changes, ignore it                            } else {                                // use the merged mapping source                                mappings.put(index, new MappingMetaData(mergedMapper));                                if (logger.isDebugEnabled()) {                                    logger.debug("[{}] update_mapping [{}] with source [{}]", index, mergedMapper.type(), updatedSource);                                } else if (logger.isInfoEnabled()) {                                    logger.info("[{}] update_mapping [{}]", index, mergedMapper.type());                                }                            }                        } else {                            mappings.put(index, new MappingMetaData(mergedMapper));                            if (logger.isDebugEnabled()) {                                logger.debug("[{}] create_mapping [{}] with source [{}]", index, newMapper.type(), updatedSource);                            } else if (logger.isInfoEnabled()) {                                logger.info("[{}] create_mapping [{}]", index, newMapper.type());                            }                        }                    }                    if (mappings.isEmpty()) {                        // no changes, return                        return currentState;                    }            //根据mapping的更新情况重新生成matadata                    MetaData.Builder builder = MetaData.builder(currentState.metaData());                    for (String indexName : request.indices()) {                        IndexMetaData indexMetaData = currentState.metaData().index(indexName);                        if (indexMetaData == null) {                            throw new IndexMissingException(new Index(indexName));                        }                        MappingMetaData mappingMd = mappings.get(indexName);                        if (mappingMd != null) {                            builder.put(IndexMetaData.builder(indexMetaData).putMapping(mappingMd));                        }                    }                    return ClusterState.builder(currentState).metaData(builder).build();                } finally {                    for (String index : indicesToClose) {                        indicesService.removeIndex(index, "created for mapping processing");                    }                }            }        });    }

    到此,相信大家对“elasticsearch索引index之put mapping怎么设置”有了更深的了解,不妨来实际操作一番吧!这里是编程网网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

    --结束END--

    本文标题: elasticsearch索引index之put mapping怎么设置

    本文链接: https://www.lsjlt.com/news/327826.html(转载时请注明来源链接)

    有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

    本篇文章演示代码以及资料文档资料下载

    下载Word文档到电脑,方便收藏和打印~

    下载Word文档
    猜你喜欢
    • C++ 生态系统中流行库和框架的贡献指南
      作为 c++++ 开发人员,通过遵循以下步骤即可为流行库和框架做出贡献:选择一个项目并熟悉其代码库。在 issue 跟踪器中寻找适合初学者的问题。创建一个新分支,实现修复并添加测试。提交...
      99+
      2024-05-15
      框架 c++ 流行库 git
    • C++ 生态系统中流行库和框架的社区支持情况
      c++++生态系统中流行库和框架的社区支持情况:boost:活跃的社区提供广泛的文档、教程和讨论区,确保持续的维护和更新。qt:庞大的社区提供丰富的文档、示例和论坛,积极参与开发和维护。...
      99+
      2024-05-15
      生态系统 社区支持 c++ overflow 标准库
    • c++中if elseif使用规则
      c++ 中 if-else if 语句的使用规则为:语法:if (条件1) { // 执行代码块 1} else if (条件 2) { // 执行代码块 2}// ...else ...
      99+
      2024-05-15
      c++
    • c++中的继承怎么写
      继承是一种允许类从现有类派生并访问其成员的强大机制。在 c++ 中,继承类型包括:单继承:一个子类从一个基类继承。多继承:一个子类从多个基类继承。层次继承:多个子类从同一个基类继承。多层...
      99+
      2024-05-15
      c++
    • c++中如何使用类和对象掌握目标
      在 c++ 中创建类和对象:使用 class 关键字定义类,包含数据成员和方法。使用对象名称和类名称创建对象。访问权限包括:公有、受保护和私有。数据成员是类的变量,每个对象拥有自己的副本...
      99+
      2024-05-15
      c++
    • c++中优先级是什么意思
      c++ 中的优先级规则:优先级高的操作符先执行,相同优先级的从左到右执行,括号可改变执行顺序。操作符优先级表包含从最高到最低的优先级列表,其中赋值运算符具有最低优先级。通过了解优先级,可...
      99+
      2024-05-15
      c++
    • c++中a+是什么意思
      c++ 中的 a+ 运算符表示自增运算符,用于将变量递增 1 并将结果存储在同一变量中。语法为 a++,用法包括循环和计数器。它可与后置递增运算符 ++a 交换使用,后者在表达式求值后递...
      99+
      2024-05-15
      c++
    • c++中a.b什么意思
      c++kquote>“a.b”表示对象“a”的成员“b”,用于访问对象成员,可用“对象名.成员名”的语法。它还可以用于访问嵌套成员,如“对象名.嵌套成员名.成员名”的语法。 c++...
      99+
      2024-05-15
      c++
    • C++ 并发编程库的优缺点
      c++++ 提供了多种并发编程库,满足不同场景下的需求。线程库 (std::thread) 易于使用但开销大;异步库 (std::async) 可异步执行任务,但 api 复杂;协程库 ...
      99+
      2024-05-15
      c++ 并发编程
    • 如何在 Golang 中备份数据库?
      在 golang 中备份数据库对于保护数据至关重要。可以使用标准库中的 database/sql 包,或第三方包如 github.com/go-sql-driver/mysql。具体步骤...
      99+
      2024-05-15
      golang 数据库备份 mysql git 标准库
    软考高级职称资格查询
    编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
    • 官方手机版

    • 微信公众号

    • 商务合作