九.全文检索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": ""
  }
}

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

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

墨家巨子@俏如来

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值