from elasticsearch import AsyncElasticsearch from elasticsearch.helpers import async_bulk import sys import os import asyncio import aiofiles import json from dotenv import load_dotenv from zipfile import ZipFile from time import sleep import gc class elastic_helper_async: def __init__(self, es_url="http://127.0.0.1:6900", es_pass="", es_user="elastic", path_mapping = ""): # self.limit_data = os.getenv("ELASTIC_LIMIT_IMPORT") # self.app_key = os.getenv("APP_KEY") if path_mapping : self.path_mapping = path_mapping if es_pass == '' : self.aes = AsyncElasticsearch(es_url, timeout=100000000) else: self.aes = AsyncElasticsearch(es_url, basic_auth=(es_user, es_pass),timeout=100000000) print(es_url) print(self.aes) self.success_connect = False for a in range(0,10): try : if not self.es.ping(): print('elastic not ping, sleep 30 s : ', a) sleep(5) continue else: self.success_connect = True break except Exception as e: break if not self.success_connect : print('******','not access to elastic service') return self.counter = 0 self.total = 0 self.id = "" async def test_file(self,array: list, name_s): for a in array: if a == name_s: return True return False async def name_file(self,array: list, namber_claer:str): data = [] for a in array: data.append(a[:-namber_claer]) print(data) return data async def read_file_json_mapping(self, name_map_general ): async with aiofiles.open(f"{self.path_mapping}/general/" + name_map_general + ".json", mode="r", encoding="utf8") as file_json: data_mapping_josn = await file_json.read() data_mapping_josn = json.loads(data_mapping_josn) return data_mapping_josn async def create_general_indexes(self): mapping_general = f"{self.path_mapping}/general/" list_general=['gn_setting','gn_calendar' ,'gn_dataset','gn_entity','gn_log_action','gn_log_change','gn_log_search','gn_research' ] for seed_general in list_general: print("mapping "+seed_general) data_json_mapping = await self.read_file_json_mapping(seed_general) try: await self.aes.indices.create(index=seed_general, body=data_json_mapping) except: print("This file has already been created, and I cannot create it again.") async def create_mapping_delete(self,location_file_zip:str, app_key="majles"): locations_data_ok = [] location_mapping_majles = os.listdir(f"{self.path_mapping}/{app_key}/") location_mapping_general = os.listdir(f"{self.path_mapping}/general/") location_filezip = os.listdir(location_file_zip) name_locations_mapping_majles = await self.name_file(location_mapping_majles, 5) name_locations_mapping_general = await self.name_file(location_mapping_general, 5) name_locations_filezip = await self.name_file(location_filezip, 4) for a in name_locations_filezip: if await self.test_file(name_locations_mapping_majles, a): print(a) async with aiofiles.open(f"{self.path_mapping}/{app_key}/" + a + ".json", mode="r", encoding="utf8") as file_json: data_mapping_josn = await file_json.read() data_mapping_josn = json.loads(data_mapping_josn) locations_data_ok.append(a) try: print("+++++++++++++ delete_index "+a+"+++++++++++++++++++") await self.delete_index(a) await asyncio.sleep(10) await self.aes.indices.create(index=a, body=data_mapping_josn) await self.aes.indices.refresh(index=a) except: print( f" ******************* There is a mapping {a} ***********************" ) elif await self.test_file(name_locations_mapping_general, a): print(a) async with aiofiles.open( f"{self.path_mapping}/general/" + a + ".json", mode="r", encoding="utf8" ) as file_json: data_mapping_josn = await file_json.read() data_mapping_josn = json.loads(data_mapping_josn) locations_data_ok.append(a) try: print("+++++++++++++ delete_index "+a+"+++++++++++++++++++") await self.delete_index(a) await asyncio.sleep(10) await self.aes.indices.create(index=a, body=data_mapping_josn) await self.aes.indices.refresh(index=a) except: print( f" ******************* There is a mapping {a} ***********************" ) else: if a == "mj_rg_section" or a == "semantic_search": mapping_read = "mj_qa_section" async with aiofiles.open( f"{self.path_mapping}/{app_key}/" + mapping_read + ".json", mode="r", encoding="utf8" ) as file_json: data_mapping_josn = await file_json.read() data_mapping_josn = json.loads(data_mapping_josn) locations_data_ok.append(a) try: print("+++++++++++++ delete_index "+a+"+++++++++++++++++++") await self.delete_index(a) await asyncio.sleep(10) await self.aes.indices.create(index=a, body=data_mapping_josn) await self.aes.indices.refresh(index=a) except: print( f" ******************* There is a mapping {a} ***********************" ) elif a[-3:] == "_ai": mapping_read = a[:-3] try: async with aiofiles.open( f"{self.path_mapping}/general/" + mapping_read + ".json", mode="r", encoding="utf8" ) as file_json: data_mapping_josn = await file_json.read() data_mapping_josn = json.loads(data_mapping_josn) locations_data_ok.append(a) try: print("+++++++++++++ delete_index "+a+"+++++++++++++++++++") await self.delete_index(a) await asyncio.sleep(10) await self.aes.indices.create(index=a, body=data_mapping_josn) await self.aes.indices.refresh(index=a) except: print( f" ******************* There is a mapping {a} ***********************" ) except: async with aiofiles.open( f"{self.path_mapping}/{app_key}/" + mapping_read + ".json", mode="r", encoding="utf8" ) as file_json: data_mapping_josn = await file_json.read() data_mapping_josn = json.loads(data_mapping_josn) locations_data_ok.append(a) try: print("+++++++++++++ delete_index "+a+"+++++++++++++++++++") await self.delete_index(a) await asyncio.sleep(10) await self.aes.indices.create(index=a, body=data_mapping_josn) await self.aes.indices.refresh(index=a) except: print( f" ******************* There is a mapping {a} ***********************" ) else: print(f"not funds map {a}") return locations_data_ok ## error for to for async def create_mapping(self,location_file_zip:str, app_key="majles"): locations_data_ok = [] location_mapping_majles = os.listdir(f"{self.path_mapping}/{app_key}/") location_mapping_general = os.listdir(f"{self.path_mapping}/general/") location_filezip = os.listdir(location_file_zip) name_locations_mapping_majles = await self.name_file(location_mapping_majles, 5) name_locations_mapping_general = await self.name_file(location_mapping_general, 5) name_locations_filezip = await self.name_file(location_filezip, 4) for a in name_locations_filezip: if await self.test_file(name_locations_mapping_majles, a): print(a) async with aiofiles.open( f"{self.path_mapping}/{app_key}/" + a + ".json", mode="r", encoding="utf8" ) as file_json: data_mapping_josn = await file_json.read() data_mapping_josn = json.loads(data_mapping_josn) locations_data_ok.append(a) try: await self.aes.indices.create(index=a, body=data_mapping_josn) await self.aes.indices.refresh(index=a) except: print( f" ******************* There is a mapping {a} ***********************" ) elif await self.test_file(name_locations_mapping_general, a): print(a) async with aiofiles.open( f"{self.path_mapping}/general/" + a + ".json", mode="r", encoding="utf8" ) as file_json: data_mapping_josn = await file_json.read() data_mapping_josn = json.loads(data_mapping_josn) locations_data_ok.append(a) try: await self.aes.indices.create(index=a, body=data_mapping_josn) await self.aes.indices.refresh(index=a) except: print( f" ******************* There is a mapping {a} ***********************" ) else: if a == "mj_rg_section" or a == "semantic_search": mapping_read = "mj_qa_section" async with aiofiles.open( f"{self.path_mapping}/{app_key}/" + mapping_read + ".json", mode="r", encoding="utf8" ) as file_json: data_mapping_josn = await file_json.read() data_mapping_josn = json.loads(data_mapping_josn) locations_data_ok.append(a) try: await self.aes.indices.create(index=a, body=data_mapping_josn) await self.aes.indices.refresh(index=a) except: print( f" ******************* There is a mapping {a} ***********************" ) elif a[-3:] == "_ai": mapping_read = a[:-3] try: async with aiofiles.open( f"{self.path_mapping}/general/" + mapping_read + ".json", mode="r", encoding="utf8" ) as file_json: data_mapping_josn = await file_json.read() data_mapping_josn = json.loads(data_mapping_josn) locations_data_ok.append(a) try: await self.aes.indices.create(index=a, body=data_mapping_josn) await self.aes.indices.refresh(index=a) except: print( f" ******************* There is a mapping {a} ***********************" ) except: async with aiofiles.open( f"{self.path_mapping}/{app_key}/" + mapping_read + ".json", mode="r", encoding="utf8" ) as file_json: data_mapping_josn = await file_json.read() data_mapping_josn = json.loads(data_mapping_josn) locations_data_ok.append(a) try: await self.aes.indices.create(index=a, body=data_mapping_josn) await self.aes.indices.refresh(index=a) except: print( f" ******************* There is a mapping {a} ***********************" ) else: print(f"not funds map {a}") return locations_data_ok ## error for to for async def data_unzip(self,location_file_zip:str,namefile: str): current_directory = os.getcwd() file_name = f"{location_file_zip}/{namefile}.zip" sleep(10) print(" -----> start to unzip ... ",file_name) data1 = [] os.system(f"del /q /S .\\data\\tmp\\edb\\{namefile}") os.system(f"mkdir .\\data\\tmp\\edb\\{namefile}") # os.system(f"del -rf /q .\\data\\tmp\\edb\\{namefile}\\*") os.system(f"tar -xf {file_name} -C .\\data\\tmp\\edb\\{namefile}\\") #await asyncio.sleep(1) list_file_json = os.listdir(f".\\data\\tmp\\edb\\{namefile}\\") await asyncio.sleep(10) for a in list_file_json: try: with open(f"{current_directory}\\data\\tmp\\edb\\{namefile}\\{a}", "r", encoding="utf8") as file_json: data = file_json.read() data = json.loads(data) for a1 in data: #await asyncio.sleep(0.001) try: yield ( { "_op_type": "index", "_index": namefile, "_id": a1["_id"], "_source": a1["_source"], } ) except: print("error type document") except Exception as e: print(f"read file {current_directory}\\data\\tmp\\edb\\{namefile}\\{a}" + " " + {e}) async def go_to_data(list_data: list, namefile: str): with open(f"T:{namefile}.json", "a") as a: a.write(str(list_data)) a.close() async def run_elastic_import(self,loc:str): locations_data = await self.create_mapping(loc) print(locations_data) await self.create_general_indexes() #await asyncio.sleep(5) for file_list in locations_data: # try : await async_bulk(self.aes, self.data_unzip(loc,file_list), True) gc.collect() # except: # await asyncio.sleep(10) # await async_bulk(self.aes, self.data_unzip(file_list), True) print("finash") #await asyncio.sleep(10) async def run_elastic_import_delete(self,loc:str): locations_data = await self.create_mapping_delete(loc) #await asyncio.sleep(1000) print(locations_data) await self.create_general_indexes() #await asyncio.sleep(5) for file_list in locations_data: # try : await async_bulk(self.aes, self.data_unzip(loc,file_list), True) gc.collect() # except: # await asyncio.sleep(10) # await async_bulk(self.aes, self.data_unzip(file_list), True) print("finash") #await asyncio.sleep(10) async def delete_index(self,name_index:str): await self.aes.indices.delete(index=name_index, ignore=[400, 404]) # await go_to_data( data2,"gn_dataset")