从ES索引库中读取数据的代码逻辑如下:
import os
import sys
import json
import inspect
filename = inspect.getframeinfo(inspect.currentframe()).filename
matrix_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(filename))))
sys.path.insert(0, matrix_dir)
from datetime import datetime
from elasticsearch import Elasticsearch
class ReadData(object):
def __init__(self):
self.es_client = Elasticsearch(hosts="localhost:xxxx/")
self.index_name = "xx-xx-index"
self.index_name = "ssk-public-index-1"
self.data_path = os.path.join(matrix_dir, "xxx/xxx/")
self.debug = True
def save_data(self, data_list):
with open(os.path.join(self.data_path, "xxx_xxx.data"), 'w', encoding="utf-8") as file:
for temp_dict in data_list:
temp_dict = json.dumps(temp_dict, ensure_ascii=False)
file.write(temp_dict)
file.write("\n")
print("*******save finish*****")
def read_es(self):
result_list = list()
if self.es_client.indices.exists(index=self.index_name):
page = self.es_client.search(index=self.index_name, scroll="20m", size=200)
scroll_id = page['_scroll_id']
if self.debug == True:
print("the scroll_id is : %s" %(scroll_id))
print("=*="*10)
scroll_size = page['hits']['total']
if self.debug == True:
print("the total number is : %d" %(scroll_size))
print("=*=" * 10)
for source_dict in page['hits']['hits']:
temp_dict = source_dict["_source"]
result_list.append(temp_dict)
while scroll_size > 0:
page = self.es_client.scroll(scroll_id=scroll_id, scroll="20m")
scroll_id = page['_scroll_id']
scroll_size = len(page['hits']['hits'])
if self.debug == True:
print("the scroll number is : %d" % (scroll_size))
print("=*=" * 10)
for source_dict in page['hits']['hits']:
temp_dict = source_dict["_source"]
result_list.append(temp_dict)
if self.debug == True:
print("*******read finish start save*******")
print("=*=" * 10)
self.save_data(result_list)
else:
print('{} not find in es'.format(self.index_name))
return None
if __name__ == "__main__":
start_time = datetime.now()
dataObject = ReadData()
dataObject.read_es()
end_time = datetime.now()
use_time = end_time - start_time
print("run time is:%ss||time:%s" % (use_time.seconds, use_time))
|