经过一些修改后,我需要将my_index
中的内容复制到另一个索引中。怎么做
以下是示例数据和用于插入索引的代码。
test = [{'id':1,'name': 'A', 'subject': ['Maths', 'Accounting'],
'type':'Contract', 'Location':'NY'},
{ 'id':2, 'name': 'AB', 'subject': ['Physics', 'Engineering'],
'type':'Permanent','Location':'NY'},
{'id':3, 'name': 'ABC', 'subject': ['Maths', 'Engineering'],
'type':'Permanent','Location':'NY'}]
from elasticsearch import Elasticsearch
es = Elasticsearch()
es.indices.create(index='myindex', ignore=400)
for e in test:
es.index(index="myindex", body=e, id=e['id'])
从myindex
我需要提取id
和name
并复制到另一个索引my_index_1
中
最佳答案
如果“myindex”中的文档数量不是很高,则可以使用搜索API来获取所有数据并提取所需的数据并对它们进行索引。为此,您可以使用如下代码:
res = es.search(index="myindex", body={"query":{"match_all":{}}})
for item in res.get("hits").get("hits"):
es.index(index="my_index_1", body={"id":item.get("_id"), "name": item.get("_source").get("name")})
如果您的数据数量较多(通常少于10000),则可以使用较高的代码,但最好使用以下限制和偏移量:limit = 30
total_count = es.count(index="my_index", body={"query":{"match_all":{}}}).get("count")
offset = 0
while offset < total_count:
res = es.search(index="myindex", body={"query":{"match_all":{}}}, size=limit, from_=offset)
offset+=limit
for item in res.get("hits").get("hits"):
es.index(index="my_index_1", body={"id":item.get("_id"), "name": item.get("_source").get("name")})
如果您的数据量很大,则需要使用滚动API来获取所有文档:es = es.search(index="myindex",body={"query":{"match_all":{}}},scroll="1m")
scroll_id = res.get("_scroll_id")
items = es.get("hits").get("hits")
while len(items):
for item in items:
es.index(index="my_index_1", body={"id":item.get("_id"), "name": item.get("_source").get("name")})
query = {
"scroll": "1m",
"scroll_id": scroll_id
}
res =es.scroll(scroll_id=scroll_id, body=query)
items = res.get("hits").get("hits")
关于python - 如何使用python在Elasticsearch中将索引修改后的内容复制到另一个内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64379063/