Elasticsearch索引重建

82 阅读1分钟

1、背景:

当我们在更改索引模板或者索引换一个分词器的情况下,我们如果还想让之前的索引也能使用新的配置,那么需要对索引进行重建。

2、索引重建:

在kibana的开发工具-控制台执行如下命令(举例) image.png

# 新的索引名称
PUT /sn-nb-test-api-info-2022-10-29-refac/
{
  # 索引别名,和旧的索引别名一致或者不一致都行,看是否需要一致
  "aliases": {
    "sn-nb-test-alias": {}
  },
  # 字段映射
  "mappings": {
    "properties": {
      "@timestamp": {
        "type": "date"
      },
      "class": {
        "type": "keyword"
      },
      "level": {
        "type": "keyword"
      },
      "line_no": {
        "type": "integer"
      },
      "msg": {
        "type": "text",
        "analyzer": "ik_max_word",
        "search_analyzer": "ik_smart"
      },
      "tags": {
        "type": "keyword"
      },
      "thread_name": {
        "type": "keyword"
      },
      "trace_id": {
        "type": "keyword"
      }
    }
  },
  # 设置索引生命周期策略,还是采用之前的,没有可不用添加
  "settings": {
    "lifecycle": {
      "name": "sn-nb-test-policy",
      "rollover_alias": "sn-nb-test-history"
    },
    "number_of_shards": "1",
    "auto_expand_replicas": "0-1"
  }
}
# 将旧的索引sn-nb-test-api-info-2022-10-29内容给到新的索引sn-nb-test-api-info-2022-10-29-refac
POST /_reindex?wait_for_completion=false
{
  "source": {
    "index": "sn-nb-test-api-info-2022-10-29"
  },
  "dest": {
    "index": "sn-nb-test-api-info-2022-10-29-refac"
  }
}
# 执行完上面的任务会返回一个taskId,比如:p9LujYO1SbGeQ8h1be-MUA:2996123,可以查看一下
GET /_tasks/p9LujYO1SbGeQ8h1be-MUA:2996123
# 将原有的索引的别名删掉,将原来的索引别名给到新的索引
POST /_aliases
{
  "actions": [
    {
      "remove": {
        "alias": "sn-nb-test-alias",
        "index": "sn-nb-test-api-info-2022-10-29"
      }
    },
    {
      "add": {
        "alias": "sn-nb-test-alias",
        "index": "sn-nb-test-api-info-2022-10-29-refac"
      }
    }
  ]
}
# 删除原来的索引即可
DELETE sn-nb-test-api-info-2022-10-29