ElasticSearch之通过update_by_query和_reindex重建索引
warning:
这篇文章距离上次修改已过206天,其中的内容可能已经有所变动。
from datetime import datetime
from elasticsearch import Elasticsearch
# 连接到Elasticsearch
es = Elasticsearch("http://localhost:9200")
# 定义要更新的索引和新索引名称
old_index = "my_old_index"
new_index = "my_new_index" + datetime.now().strftime("%Y%m%d%H%M%S")
# 更新旧索引中的数据,以确保所有文档都有一个新的_id
update_query = {
"script": {
"source": "ctx._id = ctx._version.toString()",
"lang": "painless"
},
"query": {
"match_all": {}
}
}
es.update_by_query(index=old_index, body=update_query)
# 使用_reindex API来从旧索引复制数据到新索引
reindex_query = {
"source": {
"index": old_index
},
"dest": {
"index": new_index,
"op_type": "create"
}
}
response = es.reindex(body=reindex_query)
# 检查重建索引的结果
print(f"Total documents reindexed: {response['total']}")
print(f"Number of successful documents: {response['created']}")
这段代码首先连接到Elasticsearch,然后定义了旧索引和新索引的名称。使用update_by_query
方法更新旧索引中的所有文档,将它们的\_id设置为\_version的字符串形式,以确保每个文档都有一个唯一的\_id。接下来,使用reindex
方法将更新后的数据从旧索引复制到新索引中。最后,打印出重建索引的结果。
评论已关闭