大数据利器Elasticsearch重新索引数据reindex

295 阅读2分钟

这是我参与8月更文挑战的第28天,活动详情查看:8月更文挑战
本Elasticsearch相关文章的版本为:7.4.2

Elasticsearch允许我们对索引新增新的字段, 但是如果我们需要新增分析器或者需要对现有的字段进行变更,最简单的方法就是使用reindex接口进行重新索引数据到新的索引上。

reindex介绍

reindex允许我们把现有索引的数据通过一条简单的reindex数据转移到新的索引上。
例如,我们有一个old_book_index索引,description字段一开始设定为keyword类型,现在业务上需要对description字典进行全文检索,提供更友好的体验。
假设这个索引上已存在大量的数据,那么我们可以这样通过reindex快捷操作完成。
我们先来看一下old_book_index索引的mapping:

GET /old_book_index/_mapping

{
  "old_book_index" : {
    "mappings" : {
      "properties" : {
        "description" : {
          "type" : "keyword"
        }
      }
    }
  }
}

旧索引上的某个数据:

POST /old_book_index/_doc/1
{
  "description": "A book about Elasticsearch started guide"
}

假如我们现在对description使用match进行全文搜索:

POST /old_book_index/_search
{
  "query": {
    "match": {
      "description": "guide"
    }
  }
}

返回没有命中任何数据:

{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 0,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  }
}

首先创建一个符合需求(description支持全文搜索)的新的索引mapping:

PUT /new_book_index
{
  "mappings": {
    "properties": {
      "description": {
        "type": "text"
      }
    }
  }
}

那么现在把description设置为text类型后,就可进行全文检索了。

那么现在开始把原来的数据迁移到新的索引上了:

POST /_reindex
{
  "source": {
    "index": "old_book_index"
  },
  "dest": {
    "index": "new_book_index"
  }
}

reindex返回的数据:

{
  "took" : 84,
  "timed_out" : false,
  "total" : 1,
  "updated" : 0,
  "created" : 1,
  "deleted" : 0,
  "batches" : 1,
  "version_conflicts" : 0,
  "noops" : 0,
  "retries" : {
    "bulk" : 0,
    "search" : 0
  },
  "throttled_millis" : 0,
  "requests_per_second" : -1.0,
  "throttled_until_millis" : 0,
  "failures" : [ ]
}

从返回的数据中我们可以知道这次总共迁移完成了"created" : 1个文档

那么我们看看这次是否可以进行全文检索了:

POST /new_book_index/_search
{
  "query": {
    "match": {
      "description": "guide"
    }
  }
}

这次返回了我们需要的guide的数据了:

{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 0.2876821,
    "hits" : [
      {
        "_index" : "new_book_index",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 0.2876821,
        "_source" : {
          "description" : "A book about Elasticsearch started guide"
        }
      }
    ]
  }
}

到此,我们使用reindex成功把原有索引的数据迁移到了新索引了,是不是非常简单便捷?