Elasticsearch 零停机重建索引实践

有时候创建好的索引库需要增加,删除或者更改一些字段,又或者想修改分词器等参数,这个时候就需要保证索引变更过程中搜索服务的正常运行。
Elasticsearch 官方就此也给出了零停机重建索引方案。能够这样做的前提是你在代码中使用别名访问索引,因为零停机重建索引本质上就是复制一份索引再把别名指向新索引,这样用户就没法感知索引有没有被切换,就是所谓的零停机。

具体步骤如下:

假设你的索引库名称叫 index , 其结构如下,别名为 docs

{
  "mappings": {
    "properties": {
      "id": {
        "type": "keyword"
      },
      "docNumber": {
        "type": "keyword"
      },
      "releaseDate": {
        "type": "date",
        "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd"
      },
      "docName": {
        "type": "keyword"
      },
      "docContent": {
        "type": "text",
        "analyzer": "ik_max_word",
        "search_analyzer": "ik_smart"
      }
    }
  },
  "settings": {
    "number_of_shards": 1,
    "number_of_replicas": 0
  }
}

需要把它改成如下结构

{
  "mappings": {
    "properties": {
      "id": {
        "type": "keyword"
      },
      "docNumber": {
        "type": "keyword"
      },
      "releaseDate": {
        "type": "date",
        "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd"
      },
      "docName": {
        "type": "text",
        "analyzer": "ik_max_word",
        "search_analyzer": "ik_smart"
      },
      "docContent": {
        "type": "text",
        "analyzer": "ik_max_word",
        "search_analyzer": "ik_smart"
      }
    }
  },
  "settings": {
    "number_of_shards": 1,
    "number_of_replicas": 0
  }
}
  • 首先,新建一个索引,名字需要和旧索引做区分

建索引命令如下,命令在Kibana->Management->Dev Tools 执行:

PUT /index_1
{
  "mappings": {
    "properties": {
      "id": {
        "type": "keyword"
      },
      "docNumber": {
        "type": "keyword"
      },
      "releaseDate": {
        "type": "date",
        "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd"
      },
      "docName": {
        "type": "text",
        "analyzer": "ik_max_word",
        "search_analyzer": "ik_smart"
      },
      "docContent": {
        "type": "text",
        "analyzer": "ik_max_word",
        "search_analyzer": "ik_smart"
      }
    }
  },
  "settings": {
    "number_of_shards": 1,
    "number_of_replicas": 0
  }
}
  • 把旧索引库的数据写入到新索引库中,执行以下命令即可
POST _reindex
{
  "source": {
    "index": "index"
  },
  "dest": {
    "index": "index_1"
  }
}
  • 把旧索引库的别名移到新索引库中,
POST /_aliases
{
  "actions": [
    {
      "remove": {
        "index": "index",
        "alias": "docs"
      }
    },
    {
      "add": {
        "index": "index_1",
        "alias": "docs"
      }
    }
  ]
}
  • 最后把旧索引库删除,在Kibana->Management->Index Management 选择并删除即可
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值