九.全文检索ElasticSearch经典入门-ElasticSearch映射修改

Posted 墨家巨子@俏如来

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了九.全文检索ElasticSearch经典入门-ElasticSearch映射修改相关的知识,希望对你有一定的参考价值。

前言

这篇文章的内容是ElasticSearch映射修改,写这篇文章是有水友公司里面遇到了映射修改问题,我这里做了一个整理,希望对你有所帮助。

映射修改问题

在ElasticSearch中一旦创建了映射想要进行修改是不被允许的。比如我这里有一个案例

#创建索引
PUT employee

#创建映射
POST employee/_doc/_mapping

  "properties":
    "id":
      "type":"integer"
    ,
    "name":
      "type":"keyword"
    
  

上面创建了索引employee ,同时为其创建映射,指定了id和name的类型为integer和keyword,下面尝试修改

POST employee/_doc/_mapping

  "properties":
    "id":
      "type":"long"
    ,
    "name":
      "type":"keyword"
    
  


当我尝试把id的类型由integer修改为long时,发生下面这个错误

说的是不能把integer修改为long,这个也很好理解,因为ES考虑到索引库已经存放了数据,如果你要修改字段类型会导致类型不兼容。

但是我们在开发中难免遇到字段类型没设定好而导致映射的修改。这里分为两种情况,一是添加字段做映射,二是修改已有字段的类型做映射。我们先说第一种。

添加映射

添加字段映射是比较方便的,因为添加不涉及到已有字段类型的修改,是可以直接添加语法如下

PUT employee/_doc/_mapping

  "properties":
    "age":
      "type":"integer"
    
  

这里使用PUT,为employee添加了一个 age,指定的类型为 integer。然后我们获取employee的映射 : GET employee/_doc/_mapping ,结果如下

修改映射

前面有说到,修改已有索引的映射是不被允许的,那么当我们遇到这样的需求应该怎么做呢?官方文档 是这样说明的

Updating existing field mappings
Other than where documented, existing field mappings cannot be updated. Changing the mapping would mean invalidating already indexed documents. Instead, you should create a new index with the correct mappings and reindex your data into that index. If you only wish to rename a field and not change its mappings, it may make sense to introduce an alias field

大概意思就是:现有的字段映射无法更新,更改映射将意味着使已有索引的文档无效。相反,您应该使用正确的映射创建一个新索引,并将数据重新索引到该索引中。简单理解就是让我们创建一个新的索引,做好映射,把数据重新写入到新的索引中。

第一步:创建一个新的索引和映射 , id的类型我做了修改,指定为 long

#创建映射
PUT employees

PUT employees/_doc/_mapping

  "properties":
    "id":
      "type":"long"
    ,
    "name":
      "type":"keyword"
    
  

第二步:数据的迁移,把老索引中的数据迁移到新的索引中,官方文档给出了语法:如下

POST _reindex

  "source": 
    "index": "employee"
  ,
  "dest": 
    "index": "employees"
  

  • source:是老索引
  • dest :是新的索引

如果是在7以前,老的索引和新的索引都有不同的type,那么要使用如下语法

POST _reindex

  "source": 
    "index": "",
    "type": ""
  ,
  "dest": 
    "index": "",
    "type": ""
  

文章结束,希望对于有所帮助,喜欢的话点赞评论加收藏

以上是关于九.全文检索ElasticSearch经典入门-ElasticSearch映射修改的主要内容,如果未能解决你的问题,请参考以下文章

二.全文检索ElasticSearch经典入门-ElasticSearch核心概念

一.全文检索ElasticSearch经典入门-ElasticSearch介绍与安装

五.全文检索ElasticSearch经典入门-ElasticSearch Java实战

四.全文检索ElasticSearch经典入门-ElasticSearch DSL查询

十一.全文检索ElasticSearch经典入门-SpringBoot整合ElasticSearch7

十一.全文检索ElasticSearch经典入门-SpringBoot整合ElasticSearch7