前言

elasticsearch官方文档关于数据迁移的方案,提供了3种思路,分别是从源数据进行索引(index from the source)、从远程集群迁移数据(reindex from a remote cluster)、从快照恢复数据(restore from a snapshot),可以选择合适的方案进行操作。原文链接 原文链接

  • 如果数据量很小(1000条),且源es与目的es网络互通推荐方案2,如果目的es允许重启,推荐方案4
  • 如果数据量大,且源es与目的es网络互通,推荐方案1
  • 如果网络不互通,且源es和目标es允许停机重启,推荐方案3

index from the source

在可以访问原始数据(拥有源es的完整控制权限,随时查询数据)的情况下,比如想把公司内网的数据迁移到云平台的es中,或者内网中2个es之间数据迁移,只要能还能访问源es集群,就可以使用这种方式。
在执行数据迁移的过程中,可以选择任何提取方法,如logstash、beats、es客户端(如elasticsearch-dump).

方案1. 使用logstash(也可以使用beats)

来源

阿里云
阿里云DataWorks
logstash官方文档-input elasticsearch插件
logstash官方文档-output elasticsearch插件

原理

使用logstash,从数据源读取数据,写入新的数据源

优缺点

  • 优点
    • 可以根据时间范围查询导出
    • 可以输出的插件除了elasticsearch,还可以是文件、zabbix、redis等,非常灵活
  • 缺点
    • logstash安装包太大,压缩后仍有150MB
    • 启动慢,占用系统资源大

      常用参数

  1. input
    1. query : 输入query DSL字符串
  2. output

    1. timeout: 超时,默认60秒,如果连接es超时,则60秒后重试

      操作

  3. 下载logstash ,在指定位置解压

  4. 在conf目录,创建 logstash-es-data-migration.conf ,文件内容如下
  1. input {
  2. elasticsearch {
  3. hosts => ["http://源ip或域名:80"]
  4. index => "需要导入的索引"
  5. #user => "elastic"
  6. #password => "changeme"
  7. }
  8. }
  9. output {
  10. elasticsearch {
  11. hosts => ["http://目的ip或域名:80"]
  12. index => "目的索引"
  13. #user => "elastic"
  14. #password => "changeme"
  15. }
  16. }

具体参数,可以在【来源】的elasticsearch插件中查找
其中注意点:

  • hosts中的url必须指定端口,如果不指定端口,则会访问9200端口
    1. 执行logstash logstash -f config/logstash-es-data-migration.conf
      # /usr/local/src/logstash-7.5.1 $ls
      bin  config  CONTRIBUTORS  data  Gemfile  Gemfile.lock  lib  LICENSE.txt  logs  logstash-core  logstash-core-plugin-api  modules  NOTICE.TXT  tools  vendor  x-pack
      # /usr/local/src/logstash-7.5.1 $./bin/logstash -f config/logstash-es-data-migration.conf 
      Thread.exclusive is deprecated, use Thread::Mutex
      WARNING: Could not find logstash.yml which is typically located in $LS_HOME/config or /etc/logstash. You can specify the path using --path.settings. Continuing using the defaults
      Sending Logstash logs to /usr/local/src/logstash-7.5.1/logs which is now configured via log4j2.properties
      [2020-03-03T10:53:29,459][WARN ][logstash.config.source.multilocal] Ignoring the 'pipelines.yml' file because modules or command line options are specified
      [2020-03-03T10:53:29,633][INFO ][logstash.runner          ] Starting Logstash {"logstash.version"=>"7.5.1"}
      [2020-03-03T10:53:32,960][INFO ][org.reflections.Reflections] Reflections took 56 ms to scan 1 urls, producing 20 keys and 40 values 
      [2020-03-03T10:53:34,356][INFO ][logstash.outputs.elasticsearch][main] Elasticsearch pool URLs updated {:changes=>{:removed=>[], :added=>[http://elasticsearch.vtstar.net:80/]}}
      [2020-03-03T10:53:34,777][WARN ][logstash.outputs.elasticsearch][main] Restored connection to ES instance {:url=>"http://elasticsearch.vtstar.net:80/"}
      [2020-03-03T10:53:34,886][INFO ][logstash.outputs.elasticsearch][main] ES Output version determined {:es_version=>7}
      [2020-03-03T10:53:34,900][WARN ][logstash.outputs.elasticsearch][main] Detected a 6.x and above cluster: the `type` event field won't be used to determine the document _type {:es_version=>7}
      [2020-03-03T10:53:35,020][INFO ][logstash.outputs.elasticsearch][main] New Elasticsearch output {:class=>"LogStash::Outputs::ElasticSearch", :hosts=>["http://elasticsearch.vtstar.net:80"]}
      [2020-03-03T10:53:35,246][INFO ][logstash.outputs.elasticsearch][main] Using default mapping template
      [2020-03-03T10:53:35,360][WARN ][org.logstash.instrument.metrics.gauge.LazyDelegatingGauge][main] A gauge metric of an unknown type (org.jruby.specialized.RubyArrayOneObject) has been create for key: cluster_uuids. This may result in invalid serialization.  It is recommended to log an issue to the responsible developer/development team.
      [2020-03-03T10:53:35,393][INFO ][logstash.javapipeline    ][main] Starting pipeline {:pipeline_id=>"main", "pipeline.workers"=>4, "pipeline.batch.size"=>125, "pipeline.batch.delay"=>50, "pipeline.max_inflight"=>500, "pipeline.sources"=>["/usr/local/src/logstash-7.5.1/config/logstash-es-data-migration.conf"], :thread=>"#<Thread:0x51a70ae5 run>"}
      [2020-03-03T10:53:35,579][INFO ][logstash.outputs.elasticsearch][main] Attempting to install template {:manage_template=>{"index_patterns"=>"logstash-*", "version"=>60001, "settings"=>{"index.refresh_interval"=>"5s", "number_of_shards"=>1}, "mappings"=>{"dynamic_templates"=>[{"message_field"=>{"path_match"=>"message", "match_mapping_type"=>"string", "mapping"=>{"type"=>"text", "norms"=>false}}}, {"string_fields"=>{"match"=>"*", "match_mapping_type"=>"string", "mapping"=>{"type"=>"text", "norms"=>false, "fields"=>{"keyword"=>{"type"=>"keyword", "ignore_above"=>256}}}}}], "properties"=>{"@timestamp"=>{"type"=>"date"}, "@version"=>{"type"=>"keyword"}, "geoip"=>{"dynamic"=>true, "properties"=>{"ip"=>{"type"=>"ip"}, "location"=>{"type"=>"geo_point"}, "latitude"=>{"type"=>"half_float"}, "longitude"=>{"type"=>"half_float"}}}}}}}
      [2020-03-03T10:53:36,441][INFO ][logstash.javapipeline    ][main] Pipeline started {"pipeline.id"=>"main"}
      [2020-03-03T10:53:36,616][INFO ][logstash.agent           ] Pipelines running {:count=>1, :running_pipelines=>[:main], :non_running_pipelines=>[]}
      [2020-03-03T10:53:37,641][INFO ][logstash.agent           ] Successfully started Logstash API endpoint {:port=>9600}
      [2020-03-03T10:53:40,436][INFO ][logstash.runner          ] Logstash shut down.
      

方案2. ElasticSearch-dump

参考

  • 官网github+使用案例

    原理

    从源elasticsearch中读取数据,并输出到新elasticsearh、file中

    优缺点

  • 优点

    • 小巧,安装迅速
    • 使用方便、配置参数比较全面,有输出文件切分、输出es数量、超时设置等功能
  • 缺点
    • 输入只支持elasticsearch,没有logstash灵活

      使用

      详细使用可以参考github中的案例

从快照恢复

方案3. snapshot

参考

  • 【博客】elasticsearch数据迁移
  • 【官网】Snapshot and restore

    原理

    在源es集群中,设置快照存储库,并对指定索引进行拍摄并转储快照。导出快照文件,在目的es中恢复快照

    优缺点

  • 缺点

    • 需要重新配置es,修改配置文件 elasticsearch.yml ,并重启,会影响生产
    • 操作复杂,操作步骤多,不如logstash、elasticsearch-dump方案操作简单
    • 只能针对索引全量创建快照,创建、恢复快照时时间过长,创建快照时会将索引内的全部数据加载到内存,对内存压力大
  • 优点
    • 可以压缩快照文件,跨主机迁移,比起logstash、esdump方案不需要长久占用带宽

      注意点

  1. 为了减少不必要的麻烦,不要创建全局快照,只对指定的索引创建快照
  2. 每次要对新索引做数据迁移时,重新注册一个新的快照仓库,在新的目录中创建,便于复制粘贴快照文件。即【操作】步骤1中的 location 字段,快照根目录文件夹在 /usr/share/elasticsearch/backup ,注册新快照仓库就在根目录文件夹的下级目录中,比如 /usr/share/elasticsearch/backup/new_backup

    操作

  3. 前置概念

    1. 快照仓库(snapshot repository),一个快照仓库可以包含多个快照
    2. 快照(snapshot),快照是实际存存储备份数据的单位
  4. 注册快照仓库

在 elasticsearch.yml 中配置 path.repo 参数,path.repo定义了快照仓库的跟存储位置,所有快照仓库只能在定义的目录下创建,不能更改

cluster.name: "docker-cluster"
network.host: 0.0.0.0

# minimum_master_nodes need to be explicitly set when bound on a public IP
# # # set to 1 to allow single node clusters
# # # Details: https://github.com/elastic/elasticsearch/pull/17288
# # discovery.zen.minimum_master_nodes: 1
path.repo: ["/usr/share/elasticsearch/backup"]
PUT /_snapshot/my_backup
{
  "type": "fs",
  "settings": {
    "location": "/usr/share/elasticsearch/backup/my_backup"
  }
}

GET _snapshot

验证 POST /_snapshot/my_backup/_verify

// 结果
{
  "nodes" : {
    "griHJ7c0SkiqV9bhOUQMRQ" : {
      "name" : "0ae7e8cc19ea"
    }
  }
}
  1. 源es和目的es的共享文件系统必须挂载到相同路径(跨主机复制文件,可行)

image.png

  1. 对索引创建快照

在快照创建期间,快照之前的所有快照信息都会加载到内存中,这意味着会花费超过几分钟的时间用来创建快照。所以可以通过 wait_for_completion 参数来决定是否等待快照创建完成

  • 为所有索引创建快照
    PUT /_snapshot/my_backup/snapshot_1?wait_for_completion=true
    

注意:在kibana操作中,不建议使用 wait_for_completion=true 操作,如果数据量过大,则kibana会超时中断。可以通过 GET /_snapshot/_status 指令查看快照创建进度,如果获取到的有内容,则表示快照正在创建中,并且详细内容中可以看到进度展示,如果获取到的是空数组,则表示快照创建完成。同一时刻只能有1个快照正在创建,当存在一个正在创建的快照时,再次创建快照会报错

  • 为指定的索引创建快照
    PUT /_snapshot/my_backup/snapshot_2?wait_for_completion=true
    {
    "indices": "index_1,index_2",
    "ignore_unavailable": true,
    "include_global_state": false,
    "metadata": {
    "taken_by": "kimchy",
    "taken_because": "backup before upgrading"
    }
    }
    
    ignore_unavailable 如果设置为true,则创建期间不存在的索引将被忽略;不设置此参数,则创建期间不存在的索引将会报错
    include_global_state 为false可以防止将集群全局状态存储为快照的一部分
  1. 恢复(restore)快照

    • 在目的es中,执行步骤1和2,完成快照注册。不要执行3,es可以根据快照目录内的内容自动找到对应的索引,否则创建的indices目录中索引的编码不一致会导致数据无法恢复
    • 将源es中, /usr/share/elasticsearch/backup 内容全部复制到目的es中相同路径下
    • 在目的es中,执行一下操作恢复快照内的数据

      // 查看所有快照
      GET /_snapshot/my_backup/_all
      // 恢复指定快照,比如第三步中创建的snapshot_2
      POST /_snapshot/my_backup/snapshot_2/_restore
      
    • 待恢复的主题如果已经存在数据,则恢复快照,会使已经存在的数据丢失。为了保留已经存在的数据,则需要恢复快照中的数据到临时主题,在将临时主题中的重建索引到待恢复的主题中。

      POST /_snapshot/my_backup/index_1/_restore?wait_for_completion=false
      {
      "indices": "index_1", // 快照中存在的索引
      "ignore_unavailable": true,
      "include_global_state": false,
      "rename_pattern": "index_1", // 待恢复的索引
      "rename_replacement": "temp_index_1", // 创建的临时索引
      "include_aliases": false
      }
      

      查看restore进度 GET temp_index_1/_recovery
      如果 rename_replacement 中指定的索引已经存在,则es会要求关闭索引或者删除索引。关闭索引的操作为POST index_1/_close ,待索引恢复好后,将索引开启 POST index_1/_open 。是否需要删除、关闭索引,需要根据业务需求确定。

    • 查看数据

      GET index_1/_search
      
    • 重建索引操作如下:

      POST _reindex?wait_for_completion=false
      {
      "source": {
      "index": "temp_index_1"
      },
      "dest": {
      "index": "index_1"
      }
      }
      

      同样,reindex中也不推荐使用 wait_for_completion=true 操作,该参数选择false时,es会返回taskId,通过task API 可以查看任务状态。常见的task api操作有:

      1. GET _tasks/fSxxLlSrRW2yqxldvHyiIw:6683089 查看task进度
      2. GET _tasks/ 查看所有task
      3. GET _tasks?actions=*reindex 查看所有重建索引的task
      4. POST _tasks/fSxxLlSrRW2yqxldvHyiIw:254431/_cancel 取消taskId对应的task

快照+ReIndex的组合

可以通过组合使用快照和reindex组合的方式,进行数据迁移。可以套用模板

# 1. 查找是否存在index
GET index_1/_search
# 1.1 查看index中文档的数量
GET index_1/_count

# 2. 如果存在,则锁定index(可选步骤)
POST vtcloud_fms_prod_equipment_taidaplc/_close

# 3. 从snapshot中恢复数据到中间临时索引temp_xxx_index
POST /_snapshot/xxxx_backup/index_1/_restore?wait_for_completion=false
{
  "indices": "index_1",
  "ignore_unavailable": true,
  "include_global_state": false,
  "rename_pattern": "index_1",
  "rename_replacement": "temp_index_1",
  "include_aliases": false
}

#### 查看快照恢复进度
GET temp_index_1/_recovery
# DELETE temp_vtcloud_fms_prod_equipment_taidaplc(删除)
# 4. 使用reindex, 将temp_xxx_index重新索引到原index
POST _reindex?wait_for_completion=false
{
  "source": {
    "index": "temp_index_1"
  },
  "dest": {
    "index": "index_1"
  }
}

# 5. 检查临时索引和重建后的索引中文档的数目,判断是否正确
POST index_1/_count
POST index_1/_count

# 6. 开启index
POST index_1/_open
POST temp_index_1/_open

reindex from a remote cluster

直接将新集群配置远程连接到旧的集群上,新集群将从旧集群获取数据,并重新索引,因此叫做(reindex from a remote cluster)。重新索引本质上是从头开始重建索引,会占用运算资源

方案4

优缺点

  • 优点
    • 省时省力,只需要一个语句即可
    • 可以设置query,查询指定数据
  • 缺点
    • 需要在新集群设置IP白名单,不过因为是新集群,可能重启成本会低,但是如果集群不能重启则会很麻烦

      前置条件

  1. 新集群通过ip+端口的方式访问老es集群时,需要在新集群配置白名单
  2. 官网说开放9243端口用于数据传输,实际没开放也行

    使用

  3. 配置IP白名单单,并重启新集群

下面是 elasticsearch.yml 文件,在文件最后添加了 reindex.remote.whitelist ,可以配置多个,单条内容结构必须是IP:port或者域名:port,不配置port会提示 [xxx.xxx.xxx.xxx:xxxx] not whitelisted in reindex.remote.whitelist

cluster.name: "docker-cluster"
network.host: 0.0.0.0

# minimum_master_nodes need to be explicitly set when bound on a public IP
# # # set to 1 to allow single node clusters
# # # Details: https://github.com/elastic/elasticsearch/pull/17288
# # discovery.zen.minimum_master_nodes: 1
path.repo: ["/usr/share/elasticsearch/backup"]
reindex.remote.whitelist: ["10.100.172.59:9200"]
  1. 同步数据

remote 字段中的 username 和 password 字段必须填写,如果远程es没有配置,也需要按照代码中的示例填写,否则会报HTTP 401错误

POST _reindex
{
  "source": {
    "remote": {
      "host": "http://10.100.172.59:9200",
      "username": "",
      "password": ""
    },
    "index": "custome_users",
    "query": {
      "match_all": {}
    }
  },
  "dest": {
    "index": "customer_user"
  }
}