我们知道es在字段的mapping建立后就不可再次修改mapping的值。在我们实际的情况下有些时候就是需要修改mapping的值,解决方案就是重新构建索引数据。
方式一 :
使用索引别名,创建另外一个索引、使用scroll滚屏搜索插入数据、等等,(网上有很多这样的例子,略)
方式二:(参考链接:https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-reindex.html)
使用es的 _reindex api进行解决。
注意: _reindex获取的索引的快照的数据,也就是说在重建索引的过程中可能会丢失部分数据
索引重建的演示步骤:
1、创建oldindex
2、给索引创建别名
3、想oldindex中插入9条数据
4、创建新的索引newindex
5、重建索引
6、实现不重启服务索引的切换
------------------------------------------------------------------------------------------------------------------------------
1、创建oldindex
curl -XPUT "http://192.168.99.1:9200/oldindex" -d' { "settings": { "number_of_shards": 1, "number_of_replicas": 1 }, "mappings": { "product" : { "properties": { "name" : { "type": "text" }, "price" : { "type": "double" } } } } }'
2、给索引创建别名
curl -XPUT "http://192.168.99.1:9200/oldindex/_alias/alias_oldindex"
3、想oldindex中插入9条数据
curl -XPOST "http://192.168.99.1:9200/alias_oldindex/product/_bulk" -d' {"create":{"_id":1}} {"name":"name 01","price":1} {"create":{"_id":2}} {"name":"name 02","price":2} {"create":{"_id":3}} {"name":"name 03","price":3} {"create":{"_id":4}} {"name":"name 04","price":4} {"create":{"_id":5}} {"name":"name 05","price":5} {"create":{"_id":6}} {"name":"name 06","price":6} {"create":{"_id":7}} {"name":"name 07","price":7} {"create":{"_id":8}} {"name":"name 08","price":8} {"create":{"_id":9}} {"name":"name 09","price":9} '
4、创建新的索引newindex
curl -XPUT "http://192.168.99.1:9200/newindex" -d' { "settings": { "number_of_shards": 1, "number_of_replicas": 1 }, "mappings": { "product" : { "properties": { "name" : { "type": "keyword" }, "price" : { "type": "double" } } } } }'
5、重建索引
_source中的意思是只将旧索引的price字段的数据插入到新索引中。
6、实现不重启服务索引的切换
curl -XPOST "http://192.168.99.1:9200/_aliases" -d' { "actions": [ { "remove": { "index": "oldindex", "alias": "alias_oldindex" } }, { "add": { "index": "newindex", "alias": "alias_oldindex" } } ] }'
以上就完成了索引重建的过程,并实现不停止服务就可以应用上新建后的索引。(前提:程序中使用的是索引的别名)
更多复杂的用法,参考网址:https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-reindex.html