一 序
本文属于极客时间Elasticsearch核心技术与实战学习笔记系列。
二 使用场景
一般在以下几种情况时,我们需要重建索引:
- 索引的 Mappings 发生变更:字段类型更改,分词器及字典更新
- 索引的 Setting 发生变更:索引的主分片数发生改变
- 集群内,集群间需要做数据迁移
ElastiicSearch 的内置提供的 API
- Update By Query : 在现有索引上重建
- Reindex:在其他索引上重建索引
2.1案例一 为索引增加子字段
- 改变 Mapping , 增加子字段,使用英文分词器
- 此时尝试对子字段进行查询
- 虽然有数据已经存在,但是没有返回结果
数据准备:
DELETE blogs/
# 写入文档
PUT blogs/_doc/1
{
"content":"Hadoop is cool",
"keyword":"hadoop"
}
# 查看 Mapping
GET blogs/_mapping
# 修改 Mapping,增加子字段,使用英文分词器
PUT blogs/_mapping
{
"properties" : {
"content" : {
"type" : "text",
"fields" : {
"english" : {
"type" : "text",
"analyzer":"english"
}
}
}
}
}
# 写入文档
PUT blogs/_doc/2
{
"content":"Elasticsearch rocks",
"keyword":"elasticsearch"
}
# 查询新写入文档
POST blogs/_search
{
"query": {
"match": {
"content.english": "Elasticsearch"
}
}
}
新插入的文档能查询到。
老的文档查不到。
通过_update_by_query,原有的文档就能被搜索到了,
2.2 更改已有字段类型的 Mappings
- ES 不允许在原有 Mapping 上对字段类型进行修改
- 只能创建新的索引,并设定正确的字段类型,在重新导入数据
# 查询
GET blogs/_mapping
PUT blogs/_mapping
{
"properties" : {
"content" : {
"type" : "text",
"fields" : {
"english" : {
"type" : "text",
"analyzer" : "english"
}
}
},
"keyword" : {
"type" : "keyword"
}
}
}
DELETE blogs_fix
# 创建新的索引并且设定新的Mapping
PUT blogs_fix/
{
"mappings": {
"properties" : {
"content" : {
"type" : "text",
"fields" : {
"english" : {
"type" : "text",
"analyzer" : "english"
}
}
},
"keyword" : {
"type" : "keyword"
}
}
}
}
# Reindx API
POST _reindex
{
"source": {
"index": "blogs"
},
"dest": {
"index": "blogs_fix"
}
}
GET blogs_fix/_doc/1
# 测试 Term Aggregation
POST blogs_fix/_search
{
"size": 0,
"aggs": {
"blog_keyword": {
"terms": {
"field": "keyword",
"size": 10
}
}
}
}
Reindex API
- Reindex API 支持把文档从一个索引拷贝到另外一个索引
- 使用 Reindex API 的一些场景
- 修改索引的主分片数
- 改变字段的 Mapping 中的字段类型
- 集群中数据迁移、跨集群的数据迁移
两个注意点
- 索引的 mapping _source 要开启
- 先创建一个新索引,然后在执行 reindex
OP Type
- _reindex 指挥创建不存在的文档
- 文档如果存在,会导致版本冲突
跨集群reindex
需要修改 elasticsearch.yml , 并且重启节点
查看 Task API
- Reindex API 支持一步操作,执行只返回 Task Id
- POST _reindex?wait_for_completion=false
小结:
update_by_query——在原索引的基础上进行,索引重建,针对修改索引字段类型的场景,如果没有执行这个操作,则查询不到之前的数据。
_reindex——在新的mapping上新建索引,注意新的mapping是存在的才行,她能从一个索引上获取数据放入另外一个索引,在放入数据时进行索引的重建。
通过查看 Task API,了解 Reindex 的状况。
reindex时可以继续搜索。建议为索引创建alias,当reindex完成后 通过alias切到新的index,也能实现零停机维护。