diff --git a/.gitignore b/.gitignore index 3caf61c..d68ba5e 100644 --- a/.gitignore +++ b/.gitignore @@ -33,12 +33,3 @@ yarn-error.log* *.zip analyzed_domains.json # monir test -app/monir/ -app/monir/new_schema/ -monir/ -monir/new_schema/ -app/monir/elastic_helper.py -app/monir/sanad_stuff.py -app/monir/new_schema/mn_term.json -app/monir/new_schema/mn_meet.json -app/monir/new_schema/mn_meet_entity.json diff --git a/app/common/elastic_helper.py b/app/common/elastic_helper.py index db48107..73364cf 100644 --- a/app/common/elastic_helper.py +++ b/app/common/elastic_helper.py @@ -3,58 +3,63 @@ import sys import os import json from time import sleep -from elasticsearch import Elasticsearch,helpers +from elasticsearch import Elasticsearch, helpers + + +class ElasticHelper: + """ + کلاس ElasticHelper: + نوع ورودی: بدون ورودی مستقیم در تعریف کلاس + نوع خروجی: شیء از نوع ElasticHelper + عملیات: + - متغیرهای کلاسی برای شمارش و مدیریت عملیات تعریف می‌کند + - مسیر پیش‌فرض مپینگ‌ها را تنظیم می‌کند + """ -class ElasticHelper(): - # ----------------------------start--------------------------- - # کلاس ElasticHelper: - # نوع ورودی: بدون ورودی مستقیم در تعریف کلاس - # نوع خروجی: شیء از نوع ElasticHelper - # عملیات: - # - متغیرهای کلاسی برای شمارش و مدیریت عملیات تعریف می‌کند - # - مسیر پیش‌فرض مپینگ‌ها را تنظیم می‌کند - # -----------------------------end---------------------------- - counter = 0 total = 0 id = "" - path_mappings = os.getcwd() + '/repo/_other/' - - # ----------------------------start--------------------------- - # متد __init__: - # نوع ورودی: - # - es_url: آدرس Elasticsearch (str) - پیش‌فرض "http://127.0.0.1:6900" - # - es_pass: رمز عبور (str) - پیش‌فرض خالی - # - es_user: نام کاربری (str) - پیش‌فرض "elastic" - # - path_mappings: مسیر مپینگ‌ها (str) - پیش‌فرض خالی - # نوع خروجی: شیء ElasticHelper - # عملیات: - # - اتصال به Elasticsearch را برقرار می‌کند - # - در صورت وجود رمز عبور، از احراز هویت استفاده می‌کند - # - تا 10 بار برای اتصال مجدد تلاش می‌کند (هر بار 5 ثانیه انتظار) - # - در صورت عدم موفقیت، پیام خطا نمایش داده می‌شود - # -----------------------------end---------------------------- - def __init__(self, es_url="http://127.0.0.1:6900", es_pass="", es_user="elastic", path_mappings = ""): + path_mappings = os.getcwd() + "/repo/_other/" - if path_mappings : - self.path_mappings = path_mappings + def __init__( + self, + es_url="http://127.0.0.1:6900", + es_pass="", + es_user="elastic", + path_mappings="", + ): + """ + نوع ورودی: + - es_url: آدرس Elasticsearch (str) - پیش‌فرض "http://127.0.0.1:6900" + - es_pass: رمز عبور (str) - پیش‌فرض خالی + - es_user: نام کاربری (str) - پیش‌فرض "elastic" + - path_mappings: مسیر مپینگ‌ها (str) - پیش‌فرض خالی + نوع خروجی: شیء ElasticHelper + عملیات: + - اتصال به Elasticsearch را برقرار می‌کند + - در صورت وجود رمز عبور، از احراز هویت استفاده می‌کند + - تا 10 بار برای اتصال مجدد تلاش می‌کند (هر بار 5 ثانیه انتظار) + - در صورت عدم موفقیت، پیام خطا نمایش داده می‌شود + """ + if path_mappings: + self.path_mappings = path_mappings - if es_pass == '' : + if es_pass == "": self.es = Elasticsearch(es_url) else: self.es = Elasticsearch( es_url, http_auth=(es_user, es_pass), ) - + # print(es_url) # print(self.es) self.success_connect = False - for a in range(0,10): - try : + for a in range(0, 10): + try: if not self.es.ping(): - print('elastic not ping, sleep 30 s : ', a) + print("elastic not ping, sleep 30 s : ", a) sleep(5) continue else: @@ -63,11 +68,10 @@ class ElasticHelper(): except Exception as e: break - if not self.success_connect : - print('******','not access to elastic service') + if not self.success_connect: + print("******", "not access to elastic service") return - self.counter = 0 self.total = 0 self.id = "" @@ -76,158 +80,159 @@ class ElasticHelper(): try: res = self.es.search(**params) except: - return {'hits':{'hits':[]}} + return {"hits": {"hits": []}} return res - - def get_doctument(self, index_name, id): + + def get_document(self, index_name, id): res = self.es.get(index=index_name, id=id) return res - - def exist_doctument(self, index_name, id): + + def exist_document(self, index_name, id): res = self.es.exists(index=index_name, id=id) return res - - # ----------------------------start--------------------------- - # متد update_index_doc: - # نوع ورودی: - # - is_update_state: تعیین عملیات (update یا index) (bool) - # - index_name_o: نام اندیس (str) - # - eid: شناسه سند (str) - # - data: داده‌های سند (dict) - # نوع خروجی: پاسخ Elasticsearch (dict) - # عملیات: - # - اگر is_update_state=True باشد: سند را آپدیت می‌کند - # - در غیر این صورت: سند جدید ایجاد می‌کند - # -----------------------------end---------------------------- + def update_index_doc(self, is_update_state, index_name_o, eid, data): + """ + نوع ورودی: + - is_update_state: تعیین عملیات (update یا index) (bool) + - index_name_o: نام اندیس (str) + - eid: شناسه سند (str) + - data: داده‌های سند (dict) + نوع خروجی: پاسخ Elasticsearch (dict) + عملیات: + - اگر is_update_state=True باشد: سند را آپدیت می‌کند + - در غیر این صورت: سند جدید ایجاد می‌کند + """ if is_update_state: resp = self.es.update(index=index_name_o, id=eid, doc=data) # resp = self.es.update(index=index_name_o, id=eid, body={'doc':data}) else: resp = self.es.index(index=index_name_o, id=eid, document=data) - return resp + return resp - - # ----------------------------start--------------------------- + # ----------------------------start--------------------------- # متد exportToJsonForAI: - # نوع ورودی: + # نوع ورودی: # - path_back: مسیر ذخیره فایل (str) # - index_name: نام اندیس (str) # - out_name: نام فایل خروجی (str) - پیش‌فرض خالی # - body: بدنه جستجو (dict) - پیش‌فرض خالی # - fields: لیست فیلدهای مورد نیاز (list) - پیش‌فرض خالی # نوع خروجی: بدون خروجی مستقیم - # عملیات: + # عملیات: # - داده‌های اندیس را با استفاده از scroll API دریافت می‌کند # - پیشرفت عملیات را نمایش می‌دهد # - داده‌ها را در فایل JSON ذخیره می‌کند # - اگر fields مشخص شده باشد، فقط فیلدهای مورد نظر را استخراج می‌کند # -----------------------------end---------------------------- - def exportToJsonForAI(self, path_back, index_name, out_name= '', body={}, fields=[], mode='normal', collapse_field = '') : - print('*' * 50, ' start backup -->', index_name) + def exportToJsonForAI( + self, + path_back, + index_name, + out_name="", + body={}, + fields=[], + mode="normal", + collapse_field="", + ): + print("*" * 50, " start backup -->", index_name) self.counter = 0 sid = None out = out_name - if out_name == '' : - out = index_name + if out_name == "": + out = index_name - s_res = self.es.search( - index=index_name, - scroll='5m', - size=1000, - body=body - ) - self.total = s_res["hits"]["total"]['value'] + s_res = self.es.search(index=index_name, scroll="5m", size=1000, body=body) + self.total = s_res["hits"]["total"]["value"] - print('start index = %s' % index_name) - print('total = %d' % self.total) + print("start index = %s" % index_name) + print("total = %d" % self.total) - sid = s_res['_scroll_id'] - scroll_size = len(s_res['hits']['hits']) + sid = s_res["_scroll_id"] + scroll_size = len(s_res["hits"]["hits"]) pack_count = 1 out_json = [] - if mode == 'dict' or collapse_field: - out_json = {} - - prev_collapse_value = '' + if mode == "dict" or collapse_field: + out_json = {} + + prev_collapse_value = "" pack_collapse = [] while scroll_size > 0: "Scrolling..." self.counter += scroll_size - print("progress -> %.2f %%" % ((self.counter / self.total)*100)) - + print("progress -> %.2f %%" % ((self.counter / self.total) * 100)) + #### for test # if pack_count > 2 : - # break + # break pack_count += 1 ############################# - for item in s_res['hits']['hits']: - id = item['_id'] - item2=None - if mode =='id' : # فقط شناسه ها نیاز هست - item2=id - elif fields : - item2={} - item2['id']= id - for kf in fields : - #print(kf) - if kf in item['_source'] : - # print(item['_source'][kf]) - item2[kf] = item['_source'][kf] - elif '.' in kf : - cols = kf.split('.') - subsource = item['_source'] - for sub in cols : - if sub in subsource : - subsource = subsource[sub] + for item in s_res["hits"]["hits"]: + id = item["_id"] + item2 = None + if mode == "id": # فقط شناسه ها نیاز هست + item2 = id + elif fields: + item2 = {} + item2["id"] = id + for kf in fields: + # print(kf) + if kf in item["_source"]: + # print(item['_source'][kf]) + item2[kf] = item["_source"][kf] + elif "." in kf: + cols = kf.split(".") + subsource = item["_source"] + for sub in cols: + if sub in subsource: + subsource = subsource[sub] continue else: break key = kf.replace(".", "__") - item2[key] = subsource + item2[key] = subsource - #exit() - else : - item2={} - item2=item + # exit() + else: + item2 = {} + item2 = item - if collapse_field and collapse_field in item['_source']: - collapse_value = item['_source'][collapse_field] - if not prev_collapse_value : + if collapse_field and collapse_field in item["_source"]: + collapse_value = item["_source"][collapse_field] + if not prev_collapse_value: prev_collapse_value = collapse_value - - if not collapse_value == prev_collapse_value : + + if not collapse_value == prev_collapse_value: out_json[prev_collapse_value] = pack_collapse pack_collapse = [] prev_collapse_value = collapse_value - + pack_collapse.append(item2) - - elif mode == 'dict': - out_json[id]=item2 - else : - out_json.append(item2) + elif mode == "dict": + out_json[id] = item2 + else: + out_json.append(item2) - s_res = self.es.scroll(scroll_id=sid, scroll='2m', request_timeout=100000) - sid = s_res['_scroll_id'] - scroll_size = len(s_res['hits']['hits']) + s_res = self.es.scroll(scroll_id=sid, scroll="2m", request_timeout=100000) + sid = s_res["_scroll_id"] + scroll_size = len(s_res["hits"]["hits"]) sid = None - - if collapse_field and prev_collapse_value and pack_collapse : - out_json[prev_collapse_value] = pack_collapse - - with open(path_back + "/"+ out, "w", encoding="utf-8") as fout: - json.dump(out_json, fout, ensure_ascii=False, indent=4) + + if collapse_field and prev_collapse_value and pack_collapse: + out_json[prev_collapse_value] = pack_collapse + + with open(path_back + "/" + out, "w", encoding="utf-8") as fout: + json.dump(out_json, fout, ensure_ascii=False, indent=4) ############################## - # ----------------------------start--------------------------- + # ----------------------------start--------------------------- # متد backupIndexToZipfile: - # نوع ورودی: + # نوع ورودی: # - path_back: مسیر ذخیره فایل (str) # - index_name: نام اندیس (str) # - out_name: نام فایل خروجی (str) - پیش‌فرض خالی @@ -236,255 +241,264 @@ class ElasticHelper(): # - fields: لیست فیلدهای مورد نیاز (list) - پیش‌فرض خالی # - noFields: لیست فیلدهای مورد حذف (list) - پیش‌فرض خالی # نوع خروجی: bool (True اگر داده وجود داشته باشد) - # عملیات: + # عملیات: # - داده‌های اندیس را با استفاده از scroll API دریافت می‌کند # - پیشرفت عملیات را نمایش می‌دهد # - داده‌ها را در فایل ZIP یا JSON ذخیره می‌کند # - اگر fields مشخص شده باشد، فقط فیلدهای مورد نظر را استخراج می‌کند # - اگر noFields مشخص شده باشد، فیلدهای مورد نظر را حذف می‌کند # -----------------------------end---------------------------- - def backupIndexToZipfile(self, path_back, index_name, file_name= '', body={"size":1000}, byzip = True, fields=[], noFields=[]) : - print('*' * 50, ' start backup -->', index_name) + def backupIndexToZipfile( + self, + path_back, + index_name, + file_name="", + body={"size": 1000}, + byzip=True, + fields=[], + noFields=[], + ): + print("*" * 50, " start backup -->", index_name) self.counter = 0 - sid = None + sid = None - out = index_name - - if file_name == '' : - file_name = index_name + out = index_name + if file_name == "": + file_name = index_name - if body == {} : - s_res = self.es.search( - index=index_name, - scroll='5m', - size=1000 - ) + if body == {}: + s_res = self.es.search(index=index_name, scroll="5m", size=1000) else: - s_res = self.es.search( - index=index_name, - scroll='5m', - body=body - ) - self.total = s_res["hits"]["total"]['value'] - if self.total == 0 : - print('total index_name by query = %d' % self.total) - return False + s_res = self.es.search(index=index_name, scroll="5m", body=body) + self.total = s_res["hits"]["total"]["value"] + if self.total == 0: + print("total index_name by query = %d" % self.total) + return False if byzip: - fout = zipfile.ZipFile(path_back + "/"+ file_name + '.zip', 'w') - else: - fout = open( path_back + "/"+ file_name + '.json', 'a+' , encoding='utf-8') + fout = zipfile.ZipFile(path_back + "/" + file_name + ".zip", "w") + else: + fout = open(path_back + "/" + file_name + ".json", "a+", encoding="utf-8") + print("start index = %s" % index_name) + print("total = %d" % self.total) - print('start index = %s' % index_name) - print('total = %d' % self.total) - - sid = s_res['_scroll_id'] - scroll_size = len(s_res['hits']['hits']) + sid = s_res["_scroll_id"] + scroll_size = len(s_res["hits"]["hits"]) file_count = 1 prev_percent = 0 while scroll_size > 0: "Scrolling..." self.counter += scroll_size - percent = int((self.counter / self.total)*100) - if percent != prev_percent : + percent = int((self.counter / self.total) * 100) + if percent != prev_percent: print("progress -> %.2f %%" % percent) prev_percent = percent ############################# out_json = [] - for item in s_res['hits']['hits']: - if fields : - item2={} - item2['id']=item['_id'] - item2['_source']={} - for kf in fields : - if kf in item['_source'] : - item2['_source'][kf] = item['_source'][kf] - else : - item2=item + for item in s_res["hits"]["hits"]: + if fields: + item2 = {} + item2["id"] = item["_id"] + item2["_source"] = {} + for kf in fields: + if kf in item["_source"]: + item2["_source"][kf] = item["_source"][kf] + else: + item2 = item - if noFields : - for kf in noFields : - if kf in item2['_source']: - del item2['_source'][kf] - + if noFields: + for kf in noFields: + if kf in item2["_source"]: + del item2["_source"][kf] out_json.append(item2) - - text = json.dumps(out_json, ensure_ascii=False) + text = json.dumps(out_json, ensure_ascii=False) out_json = [] if byzip: - filename = out + str(file_count) + '.json' - file_count +=1 - fout.writestr(filename, text.encode('utf-8'), zipfile.ZIP_DEFLATED ) - else: + filename = out + str(file_count) + ".json" + file_count += 1 + fout.writestr(filename, text.encode("utf-8"), zipfile.ZIP_DEFLATED) + else: fout.write(text) ############################## - s_res = self.es.scroll(scroll_id=sid, scroll='2m', request_timeout=100000) - sid = s_res['_scroll_id'] - scroll_size = len(s_res['hits']['hits']) - sid = None + s_res = self.es.scroll(scroll_id=sid, scroll="2m", request_timeout=100000) + sid = s_res["_scroll_id"] + scroll_size = len(s_res["hits"]["hits"]) + sid = None fout.close() - - # ----------------------------start--------------------------- + # ----------------------------start--------------------------- # متد restorFileToElastic: - # نوع ورودی: + # نوع ورودی: # - path_back: مسیر فایل (str) # - index_name: نام اندیس (str) # - app_key: کلید برنامه برای مپینگ (str) - پیش‌فرض خالی # - queryDelete: تعیین حذف اندیس قبل از بازیابی (bool) - پیش‌فرض True # - map_name: نام فایل مپینگ (str) - پیش‌فرض خالی # نوع خروجی: bool - # عملیات: + # عملیات: # - وجود فایل ZIP را بررسی می‌کند # - اگر queryDelete=True باشد، از کاربر تأیید حذف را می‌گیرد # - اندیس را ایجاد می‌کند # - داده‌ها را از فایل ZIP به Elasticsearch بازیابی می‌کند # -----------------------------end---------------------------- - def restorFileToElastic(self, path_back, index_name, app_key = '', queryDelete = True, map_name='') : - if not os.path.exists(path_back) : - print(' **** error *** path not exist: ', path_back) + def restorFileToElastic( + self, path_back, index_name, app_key="", queryDelete=True, map_name="" + ): + if not os.path.exists(path_back): + print(" **** error *** path not exist: ", path_back) return False - file_path = path_back + '/' + index_name + '.zip' - if not os.path.exists(file_path ) : + file_path = path_back + "/" + index_name + ".zip" + if not os.path.exists(file_path): return False - if queryDelete : + if queryDelete: # اگر وجود داشته باشد، از کاربر برای حذفش سوال میکند - if self.deleteIndex(index_name) : + if self.deleteIndex(index_name): self.createIndex(index_name, app_key, map_name) self.zipFileToElastic(file_path, index_name) - else : # اگر وجود داشته باشد پرش می کند و کاری نمیکند + else: # اگر وجود داشته باشد پرش می کند و کاری نمیکند self.createIndex(index_name, app_key, map_name) - self.zipFileToElastic(file_path, index_name) + self.zipFileToElastic(file_path, index_name) - def restorFileToElastic2(self, path_file, index_name, app_key = '', queryDelete = True, map_name='') : - if not os.path.exists(path_file) : - print(' **** error *** path not exist: ', path_file) + def restorFileToElastic2( + self, path_file, index_name, app_key="", queryDelete=True, map_name="" + ): + if not os.path.exists(path_file): + print(" **** error *** path not exist: ", path_file) return False file_path = path_file - if not os.path.exists(file_path ) : + if not os.path.exists(file_path): return False - if queryDelete : + if queryDelete: # اگر وجود داشته باشد، از کاربر برای حذفش سوال میکند - if self.deleteIndex(index_name) : + if self.deleteIndex(index_name): self.createIndex(index_name, app_key, map_name) self.zipFileToElastic(file_path, index_name) - else : # اگر وجود داشته باشد پرش می کند و کاری نمیکند + else: # اگر وجود داشته باشد پرش می کند و کاری نمیکند self.createIndex(index_name, app_key, map_name) - self.zipFileToElastic(file_path, index_name) + self.zipFileToElastic(file_path, index_name) - - # ----------------------------start--------------------------- + # ----------------------------start--------------------------- # متد renameElasticIndex: - # نوع ورودی: + # نوع ورودی: # - index_name_i: نام اندیس منبع (str) # - index_name_o: نام اندیس مقصد (str) # - app_key: کلید برنامه برای مپینگ (str) - پیش‌فرض خالی # - map_name: نام فایل مپینگ (str) - پیش‌فرض خالی # نوع خروجی: بدون خروجی مستقیم - # عملیات: + # عملیات: # - اندیس مقصد را ایجاد می‌کند # - با استفاده از reindex API، داده‌ها را از اندیس منبع به مقصد منتقل می‌کند # - پیشرفت عملیات را نمایش می‌دهد # -----------------------------end---------------------------- - def renameElasticIndex(self, index_name_i, index_name_o, app_key = '', map_name='') : + def renameElasticIndex(self, index_name_i, index_name_o, app_key="", map_name=""): - if self.createIndex(index_name_o, app_key, map_name) : - res = self.es.reindex( - body={ - "source": {"index": index_name_i}, - "dest": {"index": index_name_o} - }, - wait_for_completion=False) - - print(type(res)) - print(res) + if self.createIndex(index_name_o, app_key, map_name): + res = self.es.reindex( + body={ + "source": {"index": index_name_i}, + "dest": {"index": index_name_o}, + }, + wait_for_completion=False, + ) - taskid = res["task"] if res["task"] else "" - #tasks = client.TasksClient(self.es) - tasks = self.es.tasks - while True : - res = tasks.get(task_id = taskid) - if res["completed"] : - break + print(type(res)) + print(res) - # print( res["task"]) - print( '----', index_name_o, ' imported : ', res["task"]["status"]["total"] , ' / ', res["task"]["status"]["created"]) - sleep(1) - print( '----', index_name_o, ' complated') + taskid = res["task"] if res["task"] else "" + # tasks = client.TasksClient(self.es) + tasks = self.es.tasks + while True: + res = tasks.get(task_id=taskid) + if res["completed"]: + break + # print( res["task"]) + print( + "----", + index_name_o, + " imported : ", + res["task"]["status"]["total"], + " / ", + res["task"]["status"]["created"], + ) + sleep(1) + print("----", index_name_o, " complated") - # ----------------------------start--------------------------- + # ----------------------------start--------------------------- # متد deleteIndex: - # نوع ورودی: + # نوع ورودی: # - index_name: نام اندیس (str) # نوع خروجی: bool - # عملیات: + # عملیات: # - وجود اندیس را بررسی می‌کند # - از کاربر تأیید حذف را می‌گیرد # - در صورت تأیید، اندیس را حذف می‌کند # -----------------------------end---------------------------- - def deleteIndex(self, index_name) : - if not self.es.indices.exists(index=index_name) : - print(' ' * 10, " for delete NOT exist index :", index_name ) + def deleteIndex(self, index_name): + if not self.es.indices.exists(index=index_name): + print(" " * 10, " for delete NOT exist index :", index_name) return True - question = 'Is DELETE elastic index (' + index_name +') ? ' - if self.query_yes_no(question) : - self.es.indices.delete(index = index_name) - print('%' * 10 , " Finish DELETE index :", index_name ) - return True - else : - return False + question = "Is DELETE elastic index (" + index_name + ") ? " + if self.query_yes_no(question): + self.es.indices.delete(index=index_name) + print("%" * 10, " Finish DELETE index :", index_name) + return True + else: + return False - # ----------------------------start--------------------------- + # ----------------------------start--------------------------- # متد query_yes_no: - # نوع ورودی: + # نوع ورودی: # - question: سوال نمایش داده شده (str) # - default: پاسخ پیش‌فرض (str) - پیش‌فرض "no" # نوع خروجی: bool - # عملیات: + # عملیات: # - سوال را به کاربر نمایش می‌دهد # - پاسخ کاربر را دریافت و اعتبارسنجی می‌کند # - True برای 'yes'/'y' و False برای 'no'/'n' برمی‌گرداند # -----------------------------end---------------------------- def query_yes_no(self, question, default="no"): - valid = { "yes": True, "y": True, "ye": True, "no": False, "n": False } + valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} if default is None: prompt = " [y/n] " elif default == "yes": prompt = " [Y/n] " elif default == "no": - prompt = " [y/N] " + prompt = " [y/N] " else: raise ValueError("invalid default answer: '%s'" % default) while True: - print('%'*10, ' quistion ', '%'*10 , '\n') - sys.stdout.write(question + prompt) + print("%" * 10, " quistion ", "%" * 10, "\n") + sys.stdout.write(question + prompt) choice = input().lower() if default is not None and choice == "": return valid[default] elif choice in valid: return valid[choice] else: - sys.stdout.write("لطفا یکی از موارد روبرو را وارد کنید : 'yes' or 'no' " "(or 'y' or 'n').\n") + sys.stdout.write( + "لطفا یکی از موارد روبرو را وارد کنید : 'yes' or 'no' " + "(or 'y' or 'n').\n" + ) - # ----------------------------start--------------------------- + # ----------------------------start--------------------------- # متد createIndexIfNotExist: - # نوع ورودی: + # نوع ورودی: # - index_name_o: نام اندیس (str) # - mapping_o: مپینگ اندیس (str) - پیش‌فرض خالی # نوع خروجی: بدون خروجی مستقیم - # عملیات: + # عملیات: # - وجود اندیس را بررسی می‌کند # - در صورت عدم وجود، اندیس را با مپینگ مشخص شده ایجاد می‌کند # -----------------------------end---------------------------- @@ -497,289 +511,333 @@ class ElasticHelper(): except: print("....... index exist ! ... not created") - - # ----------------------------start--------------------------- + # ----------------------------start--------------------------- # متد createIndex: - # نوع ورودی: + # نوع ورودی: # - index_name: نام اندیس (str) # - app_key: کلید برنامه برای مپینگ (str) - پیش‌فرض خالی # - map_name: نام فایل مپینگ (str) - پیش‌فرض خالی # نوع خروجی: bool - # عملیات: + # عملیات: # - وجود اندیس را بررسی می‌کند # - مسیر فایل مپینگ را تعیین می‌کند # - فایل مپینگ را خوانده و اندیس را ایجاد می‌کند # - در صورت عدم یافت فایل مپینگ، خطا نمایش داده می‌شود # -----------------------------end---------------------------- - def createIndex(self, index_name, app_key='', map_name=''): + def createIndex(self, index_name, app_key="", map_name=""): path_base = self.path_mappings - path_mapping1 = path_base + 'general/' - if app_key == '' : - app_key = 'tavasi' - path_mapping2 = path_base + app_key + '/' + path_mapping1 = path_base + "general/" + if app_key == "": + app_key = "tavasi" + path_mapping2 = path_base + app_key + "/" - - if map_name == '': + if map_name == "": map_name = index_name - - if self.es.indices.exists(index=index_name) : - print("============== exist index :", index_name ) - return True - if map_name == 'mj_rg_section' or map_name == 'semantic_search' : - map_name = 'mj_qa_section' - elif map_name[-3]=='_ai': - map_name=[0-len(map_name)-3] + if self.es.indices.exists(index=index_name): + print("============== exist index :", index_name) + return True + + if map_name == "mj_rg_section" or map_name == "semantic_search": + map_name = "mj_qa_section" + elif map_name[-3] == "_ai": + map_name = [0 - len(map_name) - 3] print(map_name) - - mapping_file_path = path_mapping1 + map_name + '.json' - print("mapping_file_path : " , mapping_file_path) + + mapping_file_path = path_mapping1 + map_name + ".json" + print("mapping_file_path : ", mapping_file_path) if not os.path.isfile(mapping_file_path): if not os.path.isfile(mapping_file_path): - mapping_file_path = path_mapping2 + map_name + '.json' + mapping_file_path = path_mapping2 + map_name + ".json" - print("mapping_file_path : " , mapping_file_path) + print("mapping_file_path : ", mapping_file_path) # Create Index With Mapping if os.path.isfile(mapping_file_path): - mapping_file = open( mapping_file_path,'r', encoding='utf-8' ) + mapping_file = open(mapping_file_path, "r", encoding="utf-8") mapping_file_read = mapping_file.read() mapping_data = json.loads(mapping_file_read) - mapping_file.close() - if self.es.indices.exists(index=index_name) : - print("============== exist index :", index_name ) - else : - self.es.indices.create(index = index_name , body = mapping_data) - return True - else: - print('*** error not find maping file elastic : *******', mapping_file_path) + mapping_file.close() + if self.es.indices.exists(index=index_name): + print("============== exist index :", index_name) + else: + self.es.indices.create(index=index_name, body=mapping_data) + return True + else: + print("*** error not find maping file elastic : *******", mapping_file_path) return False - - # ----------------------------start--------------------------- + # ----------------------------start--------------------------- # متد updateBulkList: - # نوع ورودی: + # نوع ورودی: # - listData: لیست داده‌ها (list) # - index_name: نام اندیس (str) # نوع خروجی: بدون خروجی مستقیم - # عملیات: + # عملیات: # - داده‌ها را به صورت bulk آپدیت می‌کند # - از helpers.bulk Elasticsearch استفاده می‌کند # -----------------------------end---------------------------- def updateBulkList(self, listData, index_name): - chunk_size=100000 - raise_on_error=False - raise_on_exception=False - stats_only=True + chunk_size = 100000 + raise_on_error = False + raise_on_exception = False + stats_only = True yield_ok = False - actions=[] + actions = [] for item in listData: - actions.append({ - "_op_type": "update", - "_index": index_name, - "_id" : item['_id'], - "doc": item['_source'] - } - ) - helpers.bulk(self.es, actions, chunk_size, raise_on_error, raise_on_exception, stats_only, yield_ok ) + actions.append( + { + "_op_type": "update", + "_index": index_name, + "_id": item["_id"], + "doc": item["_source"], + } + ) + helpers.bulk( + self.es, + actions, + chunk_size, + raise_on_error, + raise_on_exception, + stats_only, + yield_ok, + ) - # ----------------------------start--------------------------- + # ----------------------------start--------------------------- # متد importBulkList: - # نوع ورودی: + # نوع ورودی: # - listData: لیست داده‌ها (list) # - index_name: نام اندیس (str) # نوع خروجی: بدون خروجی مستقیم - # عملیات: + # عملیات: # - داده‌ها را به صورت bulk وارد می‌کند # - از helpers.bulk Elasticsearch استفاده می‌کند # -----------------------------end---------------------------- def importBulkList(self, listData, index_name): - chunk_size=100000 - raise_on_error=False - raise_on_exception=False - stats_only=True + chunk_size = 100000 + raise_on_error = False + raise_on_exception = False + stats_only = True yield_ok = False for item in listData: - actions = [{ - "_op_type": "index", - "_index": index_name, - "_id" : item['_id'], - "_source": item['_source'] - } - ] - helpers.bulk(self.es, actions, chunk_size, raise_on_error, raise_on_exception, stats_only, yield_ok ) + actions = [ + { + "_op_type": "index", + "_index": index_name, + "_id": item["_id"], + "_source": item["_source"], + } + ] + helpers.bulk( + self.es, + actions, + chunk_size, + raise_on_error, + raise_on_exception, + stats_only, + yield_ok, + ) - - # ----------------------------start--------------------------- + # ----------------------------start--------------------------- # متد importJsonDataToElastic: - # نوع ورودی: + # نوع ورودی: # - jsonData: داده‌های JSON (list) # - index_name: نام اندیس (str) # نوع خروجی: بدون خروجی مستقیم - # عملیات: + # عملیات: # - داده‌ها را به صورت bulk وارد می‌کند # - از helpers.bulk Elasticsearch استفاده می‌کند # -----------------------------end---------------------------- def importJsonDataToElastic(self, jsonData, index_name, fields=[]): - chunk_size=100000 - raise_on_error=False - raise_on_exception=False - stats_only=True + chunk_size = 100000 + raise_on_error = False + raise_on_exception = False + stats_only = True yield_ok = False - actions=[] + actions = [] for item in jsonData: - id = item['_id'] if item['_id'] else item['id'] - source = item['_source'] - if fields : + id = item["_id"] if item["_id"] else item["id"] + source = item["_source"] + if fields: source = {} - for col in fields : - if col in item['_source'] : - source[col] = item['_source'] + for col in fields: + if col in item["_source"]: + source[col] = item["_source"] + actions.append( + { + "_op_type": "index", + "_index": index_name, + "_id": id, + "_source": source, + } + ) + helpers.bulk( + self.es, + actions, + chunk_size, + raise_on_error, + raise_on_exception, + stats_only, + yield_ok, + ) - actions.append({ - "_op_type": "index", - "_index": index_name, - "_id" : id, - "_source": source - }) - helpers.bulk(self.es, actions, chunk_size, raise_on_error, raise_on_exception, stats_only, yield_ok ) - - - # ----------------------------start--------------------------- + # ----------------------------start--------------------------- # متد fileToElastic: - # نوع ورودی: + # نوع ورودی: # - file_path: مسیر فایل (str) # - index_name: نام اندیس (str) # - limit_pack: محدودیت تعداد بسته‌ها (int) - پیش‌فرض -1 # نوع خروجی: بدون خروجی مستقیم - # عملیات: + # عملیات: # - فایل JSON را خوانده و داده‌ها را به Elasticsearch وارد می‌کند # - اندیس را refresh می‌کند # - تعداد اسناد را نمایش می‌دهد # -----------------------------end---------------------------- - def fileToElastic(self, file_path, index_name, limit_pack = -1, fields=[]): - if not os.path.exists(file_path): - print("file zip:" , file_path , " not exist") - return - print("index:" , index_name , '=>' , file_path ) - self.counter = 0 - with open(file_path) as file: - data = json.loads(file.read()) - self.importJsonDataToElastic(data, index_name, fields) + def fileToElastic(self, file_path, index_name, limit_pack=-1, fields=[]): + if not os.path.exists(file_path): + print("file zip:", file_path, " not exist") + return + print("index:", index_name, "=>", file_path) + self.counter = 0 + with open(file_path) as file: + data = json.loads(file.read()) + self.importJsonDataToElastic(data, index_name, fields) - self.es.indices.refresh(index=index_name) - print(self.es.cat.count(index=index_name, format="json")) - - # ----------------------------start--------------------------- + self.es.indices.refresh(index=index_name) + print(self.es.cat.count(index=index_name, format="json")) + + # ----------------------------start--------------------------- # متد zipFileToElastic: - # نوع ورودی: + # نوع ورودی: # - file_path: مسیر فایل ZIP (str) # - index_name: نام اندیس (str) # - limit_pack: محدودیت تعداد فایل‌ها (int) - پیش‌فرض -1 # نوع خروجی: بدون خروجی مستقیم - # عملیات: + # عملیات: # - فایل ZIP را باز کرده و هر فایل JSON داخل آن را پردازش می‌کند # - داده‌ها را به Elasticsearch وارد می‌کند # - اندیس را refresh می‌کند # - تعداد اسناد را نمایش می‌دهد # -----------------------------end---------------------------- - def zipFileToElastic(self, file_path, index_name, limit_pack = -1, fields=[]): - if not os.path.exists(file_path): - print("file zip:" , file_path , " not exist for imort to elastic : ", index_name ) - return + def zipFileToElastic(self, file_path, index_name, limit_pack=-1, fields=[]): + if not os.path.exists(file_path): + print( + "file zip:", file_path, " not exist for imort to elastic : ", index_name + ) + return - fileNo = 0 - with zipfile.ZipFile(file_path, 'r') as zObject: - fileNo +=1 - print("="*10, " zip fileNo: " , fileNo ," - ( ", index_name," ) | File Numbers:" ,len(zObject.namelist()) , "=" * 10) + fileNo = 0 + with zipfile.ZipFile(file_path, "r") as zObject: + fileNo += 1 + print( + "=" * 10, + " zip fileNo: ", + fileNo, + " - ( ", + index_name, + " ) | File Numbers:", + len(zObject.namelist()), + "=" * 10, + ) - packNo = 0 - self.counter = 0 - for filename in zObject.namelist(): - packNo += 1 - if limit_pack != -1 : - if packNo > limit_pack : - print('limit_data ', index_name, ' ', limit_pack) - break + packNo = 0 + self.counter = 0 + for filename in zObject.namelist(): + packNo += 1 + if limit_pack != -1: + if packNo > limit_pack: + print("limit_data ", index_name, " ", limit_pack) + break - print("index:" , index_name , '=>' , filename ) - with zObject.open(filename) as file: - data = json.loads(file.read()) - self.importJsonDataToElastic(data, index_name, fields) - - self.es.indices.refresh(index=index_name) - print(self.es.cat.count(index=index_name, format="json")) - print(" END Of Import to elastic ", index_name ,"\n") - + print("index:", index_name, "=>", filename) + with zObject.open(filename) as file: + data = json.loads(file.read()) + self.importJsonDataToElastic(data, index_name, fields) - # ----------------------------start--------------------------- + self.es.indices.refresh(index=index_name) + print(self.es.cat.count(index=index_name, format="json")) + print(" END Of Import to elastic ", index_name, "\n") + + # ----------------------------start--------------------------- # متد iterateJsonFile: - # نوع ورودی: + # نوع ورودی: # - file_path: مسیر فایل (str) # - isZip: تعیین نوع فایل (ZIP یا JSON) (bool) - پیش‌فرض True # - limit_pack: محدودیت تعداد فایل‌ها (int) - پیش‌فرض -1 # نوع خروجی: ژنراتور - # عملیات: + # عملیات: # - اگر isZip=True باشد: فایل ZIP را پردازش می‌کند # - اگر isZip=False باشد: فایل JSON را پردازش می‌کند # - داده‌ها را به صورت ژنراتور برمی‌گرداند # -----------------------------end---------------------------- - def iterateJsonFile(self, file_path, isZip=True, limit_pack = -1): - if not os.path.exists(file_path): - print("file zip:" , file_path , " not exist iterateJsonFile " ) - return + def iterateJsonFile(self, file_path, isZip=True, limit_pack=-1): + if not os.path.exists(file_path): + print("file zip:", file_path, " not exist iterateJsonFile ") + return - if isZip : - fileNo = 0 - with zipfile.ZipFile(file_path, 'r') as zObject: - fileNo +=1 - print("="*10, " zip fileNo: " , fileNo ," iterateJsonFile - | File Numbers:" ,len(zObject.namelist()) , "=" * 10) + if isZip: + fileNo = 0 + with zipfile.ZipFile(file_path, "r") as zObject: + fileNo += 1 + print( + "=" * 10, + " zip fileNo: ", + fileNo, + " iterateJsonFile - | File Numbers:", + len(zObject.namelist()), + "=" * 10, + ) - packNo = 0 - self.counter = 0 - for filename in zObject.namelist(): - packNo += 1 - if limit_pack != -1 : - if packNo > limit_pack : - print('limit_data iterateJsonFile ', limit_pack) - break + packNo = 0 + self.counter = 0 + for filename in zObject.namelist(): + packNo += 1 + if limit_pack != -1: + if packNo > limit_pack: + print("limit_data iterateJsonFile ", limit_pack) + break - print("index iterateJsonFile :", '=>' , filename ) - with zObject.open(filename) as file: - data = json.loads(file.read()) - # Yield each entry - # yield data - yield from ({"source": hit["_source"], "id": hit["_id"]} for hit in data) - else : - with open(filename, 'r', encoding='utf-8') as file: - data = json.loads(file.read()) - # Yield each entry - # yield from (hit for hit in data) - #return data - yield from ({"source": hit["_source"], "id": hit["_id"]} for hit in data) - + print("index iterateJsonFile :", "=>", filename) + with zObject.open(filename) as file: + data = json.loads(file.read()) + # Yield each entry + # yield data + yield from ( + {"source": hit["_source"], "id": hit["_id"]} for hit in data + ) + else: + with open(filename, "r", encoding="utf-8") as file: + data = json.loads(file.read()) + # Yield each entry + # yield from (hit for hit in data) + # return data + yield from ( + {"source": hit["_source"], "id": hit["_id"]} for hit in data + ) - # ----------------------------start--------------------------- + # ----------------------------start--------------------------- # متد es_iterate_all_documents: - # نوع ورودی: + # نوع ورودی: # - index: نام اندیس (str) # - body: بدنه جستجو (dict) - پیش‌فرض خالی # - pagesize: اندازه صفحه (int) - پیش‌فرض 250 # - scroll_timeout: زمان اسکرول (str) - پیش‌فرض "25m" # - **kwargs: پارامترهای اضافی # نوع خروجی: ژنراتور - # عملیات: + # عملیات: # - تمام اسناد اندیس را با استفاده از scroll API دریافت می‌کند # - پیشرفت عملیات را نمایش می‌دهد # - داده‌ها را به صورت ژنراتور برمی‌گرداند # -----------------------------end---------------------------- - def es_iterate_all_documents(self, index, body="", pagesize=250, scroll_timeout="25m", **kwargs): + def es_iterate_all_documents( + self, index, body="", pagesize=250, scroll_timeout="25m", **kwargs + ): """ Helper to iterate ALL values from a single index Yields all the documents. @@ -791,7 +849,7 @@ class ElasticHelper(): # result = self.es.search(index=index, scroll="2m", **kwargs, body={ # "size": pagesize # }) - if body : + if body: result = self.es.search( index=index, scroll=scroll_timeout, @@ -799,12 +857,9 @@ class ElasticHelper(): size=pagesize, body=body ) - else : + else: result = self.es.search( - index=index, - scroll=scroll_timeout, - **kwargs, - size=pagesize + index=index, scroll=scroll_timeout, **kwargs, size=pagesize ) self.total = result["hits"]["total"]["value"] @@ -817,11 +872,11 @@ class ElasticHelper(): # "scroll": scroll_timeout # }) result = self.es.scroll(scroll_id=scroll_id, scroll=scroll_timeout) - + scroll_id = result["_scroll_id"] hits = result["hits"]["hits"] self.counter += len(hits) - if self.total > 0 : + if self.total > 0: print("progress -> %.2f %%" % ((self.counter / self.total) * 100)) # Stop after no more docs if not hits: @@ -829,8 +884,9 @@ class ElasticHelper(): # Yield each entry yield from ({"source": hit["_source"], "id": hit["_id"]} for hit in hits) - - def removeCustomFileds(self, index_name_i, fields=[], renameFileds={}, body={}, bulk_update_size=200): + def removeCustomFileds( + self, index_name_i, fields=[], renameFileds={}, body={}, bulk_update_size=200 + ): try: _list = [] try: @@ -843,72 +899,77 @@ class ElasticHelper(): total_count = 0 for mentry in _list: count += 1 - + entry = mentry["source"] id = mentry["id"] # print(id) eid = id - # if (count % 100) == 0 : + # if (count % 100) == 0 : # print("%s -> %.2f " % (id , (count / self.total) if self.total > 0 else 0)) data_filled = False data = entry for col in fields: - if col in data : + if col in data: del data[col] - - elif '.' in col : - cols = col.split('.') - subsource = entry - for sub in cols : + + elif "." in col: + cols = col.split(".") + subsource = entry + for sub in cols: dCol = subsource.get(sub, None) - if dCol : - subsource = dCol - else : + if dCol: + subsource = dCol + else: break - + for col in renameFileds.items(): - if col in data : + if col in data: dCol = data[col] - data[renameFileds[col]] = dCol + data[renameFileds[col]] = dCol del data[col] - - bulk_data.append({ - '_id': eid, - '_source' : data - }) - - # انتقال دسته جمعی کدها به الاستیک + + bulk_data.append({"_id": eid, "_source": data}) + + # انتقال دسته جمعی کدها به الاستیک if len(bulk_data) >= bulk_update_size: total_count += len(bulk_data) - print('=' * 5, ' update bulk --> ' , 'total='+ str(total_count) , str(count)) - self.importBulkList(bulk_data, index_name_i) + print( + "=" * 5, + " update bulk --> ", + "total=" + str(total_count), + str(count), + ) + self.importBulkList(bulk_data, index_name_i) bulk_data = [] - - + if len(bulk_data) >= 0: total_count += len(bulk_data) - print('=' * 5, ' update bulk --> ' , 'total='+ str(total_count) , str(count)) - self.importBulkList(bulk_data, index_name_i) + print( + "=" * 5, + " update bulk --> ", + "total=" + str(total_count), + str(count), + ) + self.importBulkList(bulk_data, index_name_i) bulk_data = [] - + except Exception as e: # print("1111") print(e) # save_error(id, e) - - - # ----------------------------start--------------------------- + + # ----------------------------start--------------------------- # متد moveCustomFileds: - # نوع ورودی: + # نوع ورودی: # - index_name_i: نام اندیس منبع (str) # - index_name_o: نام اندیس مقصد (str) # - fields: لیست فیلدهای مورد انتقال (list) - پیش‌فرض خالی # - renameFileds: دیکشنری تغییر نام فیلدها (dict) - پیش‌فرض خالی # نوع خروجی: بدون خروجی مستقیم - # عملیات: + # عملیات: # - تمام اسناد اندیس منبع را دریافت می‌کند # - فیلدهای مشخص شده را استخراج و به اندیس مقصد انتقال می‌دهد # - اگر renameFileds وجود داشته باشد، نام فیلدها را تغییر می‌دهد @@ -925,42 +986,45 @@ class ElasticHelper(): count = 0 for mentry in list: count += 1 - + entry = mentry["source"] id = mentry["id"] # print(id) eid = id - if (count % 100) == 0 : - print("%s -> %.2f " % (id , (count / self.total) if self.total > 0 else 0)) + if (count % 100) == 0: + print( + "%s -> %.2f " + % (id, (count / self.total) if self.total > 0 else 0) + ) data_filled = False data = {} for col in fields: - if '.' in col : - cols = col.split('.') - subsource = entry - for sub in cols : + if "." in col: + cols = col.split(".") + subsource = entry + for sub in cols: dCol = subsource.get(sub, None) - if dCol : - subsource = dCol - else : + if dCol: + subsource = dCol + else: break - else : + else: dCol = entry.get(col, None) if dCol is None: continue - if col in renameFileds : - data[renameFileds[col]] = dCol + if col in renameFileds: + data[renameFileds[col]] = dCol else: - data[col] = dCol + data[col] = dCol data_filled = True - if not data_filled : + if not data_filled: continue try: @@ -975,29 +1039,29 @@ class ElasticHelper(): # save_error(id, e) - # ----------------------------start--------------------------- + # ----------------------------start--------------------------- # متد mappingIndex: - # نوع ورودی: + # نوع ورودی: # - index_name_i: نام اندیس (str) # نوع خروجی: بدون خروجی مستقیم - # عملیات: + # عملیات: # - توضیح می‌دهد که تغییر مپینگ از طریق پایتون امکان‌پذیر نیست # - باید اندیس جدیدی با مپینگ مطلوب ایجاد و رایندکس شود # -----------------------------end---------------------------- def mappingIndex(self, index_name_i): - # فقط از طریق کیبانا میشه تغییر مپ داد - - # با پایتون نمیشه + # فقط از طریق کیبانا میشه تغییر مپ داد + + # با پایتون نمیشه # باید ایندکس جدیدی با مپ مطلوب ایجاد کرد و رایندکس کرد pass - # ----------------------------start--------------------------- + # ----------------------------start--------------------------- # متد updateByQueryIndex: - # نوع ورودی: + # نوع ورودی: # - index_name_i: نام اندیس (str) # - body: بدنه آپدیت (dict) # نوع خروجی: بدون خروجی مستقیم - # عملیات: + # عملیات: # - اسناد را با استفاده از update_by_query API آپدیت می‌کند # - در صورت خطا، پیام خطا نمایش داده می‌شود # -----------------------------end---------------------------- @@ -1016,19 +1080,18 @@ class ElasticHelper(): # } try: self.es.update_by_query(body=body, index=index_name_i) - + except Exception as e: print(e) - # save_error(id, e) + # save_error(id, e) - - # ----------------------------start--------------------------- + # ----------------------------start--------------------------- # متد deleteByQueryIndex: - # نوع ورودی: + # نوع ورودی: # - index_name_i: نام اندیس (str) # - body: بدنه حذف (dict) # نوع خروجی: بدون خروجی مستقیم - # عملیات: + # عملیات: # - اسناد را با استفاده از delete_by_query API حذف می‌کند # - در صورت خطا، پیام خطا نمایش داده می‌شود # -----------------------------end---------------------------- @@ -1042,30 +1105,30 @@ class ElasticHelper(): # } # } try: - self.es.delete_by_query(index=index_name_i, body=body ) - + self.es.delete_by_query(index=index_name_i, body=body) + except Exception as e: print(e) - # save_error(id, e) + # save_error(id, e) - # ----------------------------start--------------------------- + # ----------------------------start--------------------------- # متد delete_by_ids: - # نوع ورودی: + # نوع ورودی: # - index_name_i: نام اندیس (str) # - ids: لیست شناسه‌ها (list) # نوع خروجی: بدون خروجی مستقیم - # عملیات: + # عملیات: # - اسناد با شناسه‌های مشخص شده را حذف می‌کند # - در صورت خطا، پیام خطا نمایش داده می‌شود # -----------------------------end---------------------------- def delete_by_ids(self, index_name_i, ids): try: - # ids = ['test1', 'test2', 'test3'] + # ids = ['test1', 'test2', 'test3'] query = {"query": {"terms": {"_id": ids}}} res = self.es.delete_by_query(index=index_name_i, body=query) - print(res) - + print(res) + except Exception as e: print(e) - # save_error(id, e) + # save_error(id, e) diff --git a/app/for_ai/ai_json_move_to_index.py b/app/for_ai/ai_json_move_to_index.py index 834ea64..515a908 100644 --- a/app/for_ai/ai_json_move_to_index.py +++ b/app/for_ai/ai_json_move_to_index.py @@ -160,7 +160,7 @@ def copyToAiCodesHistoryCodes(elastic, index_name_o, data, version_key = "D51_v1 history_codes = [] try: - item = elastic.get_doctument(index_name_o, eid) + item = elastic.get_document(index_name_o, eid) history_codes = item.get("_source", {}).get("history_codes", []) except Exception as e: continue diff --git a/app/for_ai/codes_import_from_excel.py b/app/for_ai/codes_import_from_excel.py index 830dec3..dd9b7f2 100644 --- a/app/for_ai/codes_import_from_excel.py +++ b/app/for_ai/codes_import_from_excel.py @@ -488,7 +488,7 @@ def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, file_lo # ذخیره کد در الاستیک برای شناسه های یافت شده if section_id and section_id != 0: try : - item = elastic.get_doctument(index_name_o,section_id) + item = elastic.get_document(index_name_o,section_id) except Exception as e: print('-------------Exception as e section_id not found --- rownumber , section_id ' + str(row_number) + str(section_id) + '\n') file.write('----section_id not found --- rownumber , section_id ' + str(row_number) + str(section_id) + '\n') diff --git a/app/for_ai/codes_llm_update_to_elastic.py b/app/for_ai/codes_llm_update_to_elastic.py index 6c370cf..aaeb343 100644 --- a/app/for_ai/codes_llm_update_to_elastic.py +++ b/app/for_ai/codes_llm_update_to_elastic.py @@ -71,7 +71,7 @@ def parse_and_update_code(file_path, elastic, index_name_o = "mj_qa_section", up res = None try : if elastic : - res = elastic.get_doctument(index_name_o, section_id) + res = elastic.get_document(index_name_o, section_id) except: list_section_id_notfound.append(section_id) continue @@ -210,7 +210,7 @@ def parse_and_update_multi_code(file_path, elastic, all_codes, index_name_o, upd res = None try : if elastic : - res = elastic.get_doctument(index_name_o, section_id) + res = elastic.get_document(index_name_o, section_id) except: list_section_id_notfound.append(section_id) continue @@ -740,7 +740,7 @@ def repair_diff_codes_llm(elastic, paths, index_name, file_result="diff_section_ res = None try : - res = elastic.get_doctument(index_name, section_id) + res = elastic.get_document(index_name, section_id) except: list_section_id_notfound.append(section_id) continue diff --git a/app/for_ai/llm_excel_codes_import_to_es.py b/app/for_ai/llm_excel_codes_import_to_es.py index 9907ba7..9f2b5b2 100644 --- a/app/for_ai/llm_excel_codes_import_to_es.py +++ b/app/for_ai/llm_excel_codes_import_to_es.py @@ -72,7 +72,7 @@ def update_history_code(elastic, data, index_name_o, sub_key, label_name, versio # if id in ["qs1002289", "qs1002290"] : # continue eid = id - res = elastic.get_doctument(index_name_o, eid) + res = elastic.get_document(index_name_o, eid) history_codes = res["_source"]["history_codes"] new_data = { @@ -185,7 +185,7 @@ def run_all_json_codes(elastic, path_base, index_name_o, version_key): if not "rel" in item : continue - res = elastic.get_doctument(index_name_o, eid) + res = elastic.get_document(index_name_o, eid) history_codes = res["_source"]["history_codes"] sub_key = "positive" diff --git a/app/import_from_sql/s12_LawSection_repair_ref_state.py b/app/import_from_sql/s12_LawSection_repair_ref_state.py index 4157217..1cbfadd 100644 --- a/app/import_from_sql/s12_LawSection_repair_ref_state.py +++ b/app/import_from_sql/s12_LawSection_repair_ref_state.py @@ -111,7 +111,7 @@ def import_law_section_repair_ref_state(cursor, elastic, index_name_o, file_log) prev_ref_state = [] item = {} try: - item = elastic.get_doctument(index_name_o, eid) + item = elastic.get_document(index_name_o, eid) if 'ref_state' in item['_source'] : if len(item['_source']['ref_state']) > 0: prev_ref_state = item['_source']['ref_state'] diff --git a/app/monir/elastic_helper.py b/app/monir/elastic_helper.py deleted file mode 100644 index 2e53a89..0000000 --- a/app/monir/elastic_helper.py +++ /dev/null @@ -1,854 +0,0 @@ -import zipfile -import sys -import os -import json -from time import sleep -from elasticsearch import Elasticsearch, helpers - - -class ElasticHelper: - - counter = 0 - total = 0 - id = "" - path_mappings = os.getcwd() + "/repo/_other/" - - def __init__( - self, - es_url="http://127.0.0.1:6900", - es_pass="", - es_user="elastic", - path_mappings="", - ): - - if path_mappings: - self.path_mappings = path_mappings - - if es_pass == "": - self.es = Elasticsearch(es_url) - else: - self.es = Elasticsearch( - es_url, - http_auth=(es_user, es_pass), - ) - - print(es_url) - print(self.es) - - 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 = "" - - def get_document(self, index_name, id): - res = self.es.get(index=index_name, id=id) - return res - - def exist_document(self, index_name, id): - res = self.es.exists(index=index_name, id=id) - return res - - def update_index_doc(self, is_update_state, index_name_o, eid, data): - if is_update_state: - resp = self.es.update(index=index_name_o, id=eid, doc=data) - # resp = self.es.update(index=index_name_o, id=eid, body={'doc':data}) - else: - resp = self.es.index(index=index_name_o, id=eid, document=data) - return resp - - def exportToJsonForAI( - self, - path_back, - index_name, - out_name="", - body={}, - fields=[], - mode="normal", - collapse_field="", - ): - print("*" * 50, " start backup -->", index_name) - self.counter = 0 - sid = None - - out = out_name - if out_name == "": - out = index_name - - s_res = self.es.search(index=index_name, scroll="5m", size=1000, body=body) - self.total = s_res["hits"]["total"]["value"] - - print("start index = %s" % index_name) - print("total = %d" % self.total) - - sid = s_res["_scroll_id"] - scroll_size = len(s_res["hits"]["hits"]) - pack_count = 1 - out_json = [] - if mode == "dict" or collapse_field: - out_json = {} - - prev_collapse_value = "" - pack_collapse = [] - while scroll_size > 0: - "Scrolling..." - self.counter += scroll_size - print("progress -> %.2f %%" % ((self.counter / self.total) * 100)) - - #### for test - # if pack_count > 2 : - # break - pack_count += 1 - ############################# - for item in s_res["hits"]["hits"]: - id = item["_id"] - item2 = None - if mode == "id": # فقط شناسه ها نیاز هست - item2 = id - elif fields: - item2 = {} - item2["id"] = id - for kf in fields: - # print(kf) - if kf in item["_source"]: - # print(item['_source'][kf]) - item2[kf] = item["_source"][kf] - elif "." in kf: - cols = kf.split(".") - subsource = item["_source"] - for sub in cols: - if sub in subsource: - subsource = subsource[sub] - continue - else: - break - key = kf.replace(".", "__") - item2[key] = subsource - - # exit() - else: - item2 = {} - item2 = item - - if collapse_field and collapse_field in item["_source"]: - collapse_value = item["_source"][collapse_field] - if not prev_collapse_value: - prev_collapse_value = collapse_value - - if not collapse_value == prev_collapse_value: - out_json[prev_collapse_value] = pack_collapse - pack_collapse = [] - prev_collapse_value = collapse_value - - pack_collapse.append(item2) - - elif mode == "dict": - out_json[id] = item2 - else: - out_json.append(item2) - - s_res = self.es.scroll(scroll_id=sid, scroll="2m", request_timeout=100000) - sid = s_res["_scroll_id"] - scroll_size = len(s_res["hits"]["hits"]) - - sid = None - - if collapse_field and prev_collapse_value and pack_collapse: - out_json[prev_collapse_value] = pack_collapse - - with open(path_back + "/" + out, "w", encoding="utf-8") as fout: - json.dump(out_json, fout, ensure_ascii=False, indent=4) - - ############################## - - def backupIndexToZipfile( - self, - path_back, - index_name, - file_name="", - body={}, - byzip=True, - fields=[], - noFields=[], - ): - print("*" * 50, " start backup -->", index_name) - self.counter = 0 - sid = None - - out = index_name - - if file_name == "": - file_name = index_name - - if body == {}: - s_res = self.es.search(index=index_name, scroll="5m", size=1000) - else: - s_res = self.es.search(index=index_name, scroll="5m", size=1000, body=body) - - self.total = s_res["hits"]["total"]["value"] - if self.total == 0: - print("total index_name by query = %d" % self.total) - return False - - if byzip: - fout = zipfile.ZipFile(path_back + "/" + file_name + ".zip", "w") - else: - fout = open(path_back + "/" + file_name + ".json", "a+", encoding="utf-8") - - print("start index = %s" % index_name) - print("total = %d" % self.total) - - sid = s_res["_scroll_id"] - scroll_size = len(s_res["hits"]["hits"]) - file_count = 1 - while scroll_size > 0: - "Scrolling..." - self.counter += scroll_size - print("progress -> %.2f %%" % ((self.counter / self.total) * 100)) - ############################# - out_json = [] - for item in s_res["hits"]["hits"]: - if fields: - item2 = {} - item2["id"] = item["_id"] - item2["_source"] = {} - for kf in fields: - if kf in item["_source"]: - item2["_source"][kf] = item["_source"][kf] - else: - item2 = item - - if noFields: - for kf in noFields: - if kf in item2["_source"]: - del item2["_source"][kf] - - out_json.append(item2) - - text = json.dumps(out_json, ensure_ascii=False) - out_json = [] - if byzip: - filename = out + str(file_count) + ".json" - file_count += 1 - fout.writestr(filename, text.encode("utf-8"), zipfile.ZIP_DEFLATED) - else: - fout.write(text) - - ############################## - s_res = self.es.scroll(scroll_id=sid, scroll="2m", request_timeout=100000) - sid = s_res["_scroll_id"] - scroll_size = len(s_res["hits"]["hits"]) - sid = None - fout.close() - - def restorFileToElastic( - self, path_back, index_name, app_key="", queryDelete=True, map_name="" - ): - if not os.path.exists(path_back): - print(" **** error *** path not exist: ", path_back) - return False - - file_path = path_back + "/" + index_name + ".zip" - if not os.path.exists(file_path): - return False - - if queryDelete: - # اگر وجود داشته باشد، از کاربر برای حذفش سوال میکند - if self.deleteIndex(index_name): - self.createIndex(index_name, app_key, map_name) - self.zipFileToElastic(file_path, index_name) - else: # اگر وجود داشته باشد پرش می کند و کاری نمیکند - self.createIndex(index_name, app_key, map_name) - self.zipFileToElastic(file_path, index_name) - - def restorFileToElastic2( - self, path_file, index_name, app_key="", queryDelete=True, map_name="" - ): - if not os.path.exists(path_file): - print(" **** error *** path not exist: ", path_file) - return False - - file_path = path_file - if not os.path.exists(file_path): - return False - - if queryDelete: - # اگر وجود داشته باشد، از کاربر برای حذفش سوال میکند - if self.deleteIndex(index_name): - self.createIndex(index_name, app_key, map_name) - self.zipFileToElastic(file_path, index_name) - else: # اگر وجود داشته باشد پرش می کند و کاری نمیکند - self.createIndex(index_name, app_key, map_name) - self.zipFileToElastic(file_path, index_name) - - def renameElasticIndex(self, index_name_i, index_name_o, app_key="", map_name=""): - - if self.createIndex(index_name_o, app_key, map_name): - res = self.es.reindex( - body={ - "source": {"index": index_name_i}, - "dest": {"index": index_name_o}, - }, - wait_for_completion=False, - ) - - print(type(res)) - print(res) - - taskid = res["task"] if res["task"] else "" - # tasks = client.TasksClient(self.es) - tasks = self.es.tasks - while True: - res = tasks.get(task_id=taskid) - if res["completed"]: - break - - # print( res["task"]) - print( - "----", - index_name_o, - " imported : ", - res["task"]["status"]["total"], - " / ", - res["task"]["status"]["created"], - ) - sleep(1) - print("----", index_name_o, " complated") - - def deleteIndex(self, index_name): - if not self.es.indices.exists(index=index_name): - print(" " * 10, " for delete NOT exist index :", index_name) - return True - - question = "Is DELETE elastic index (" + index_name + ") ? " - if self.query_yes_no(question): - self.es.indices.delete(index=index_name) - print("%" * 10, " Finish DELETE index :", index_name) - return True - else: - return False - - def query_yes_no(self, question, default="no"): - valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} - if default is None: - prompt = " [y/n] " - elif default == "yes": - prompt = " [Y/n] " - elif default == "no": - prompt = " [y/N] " - else: - raise ValueError("invalid default answer: '%s'" % default) - - while True: - print("%" * 10, " quistion ", "%" * 10, "\n") - sys.stdout.write(question + prompt) - choice = input().lower() - if default is not None and choice == "": - return valid[default] - elif choice in valid: - return valid[choice] - else: - sys.stdout.write( - "لطفا یکی از موارد روبرو را وارد کنید : 'yes' or 'no' " - "(or 'y' or 'n').\n" - ) - - def createIndexIfNotExist(self, index_name_o, mapping_o=""): - try: - if not self.es.indices.exists(index=index_name_o): - response = self.es.indices.create(index=index_name_o, body=mapping_o) - # print out the response: - print("create index response:", response) - except: - print("....... index exist ! ... not created") - - def createIndex(self, index_name, app_key="", map_name=""): - - path_base = self.path_mappings - path_mapping1 = path_base + "general/" - if app_key == "": - app_key = "tavasi" - path_mapping2 = path_base + app_key + "/" - - if map_name == "": - map_name = index_name - - if self.es.indices.exists(index=index_name): - print("============== exist index :", index_name) - return True - - if map_name == "mj_rg_section" or map_name == "semantic_search": - map_name = "mj_qa_section" - elif map_name[-3] == "_ai": - map_name = [0 - len(map_name) - 3] - print(map_name) - - mapping_file_path = path_mapping1 + map_name + ".json" - print("mapping_file_path : ", mapping_file_path) - if not os.path.isfile(mapping_file_path): - if not os.path.isfile(mapping_file_path): - mapping_file_path = path_mapping2 + map_name + ".json" - - print("mapping_file_path : ", mapping_file_path) - - # Create Index With Mapping - if os.path.isfile(mapping_file_path): - mapping_file = open(mapping_file_path, "r", encoding="utf-8") - mapping_file_read = mapping_file.read() - mapping_data = json.loads(mapping_file_read) - mapping_file.close() - if self.es.indices.exists(index=index_name): - print("============== exist index :", index_name) - else: - self.es.indices.create(index=index_name, body=mapping_data) - return True - else: - print("*** error not find maping file elastic : *******", mapping_file_path) - return False - - def updateBulkList(self, listData, index_name): - chunk_size = 1000 - raise_on_error = False - raise_on_exception = False - stats_only = True - yield_ok = False - - actions = [] - for item in listData: - actions.append( - { - "_op_type": "update", - "_index": index_name, - "_id": item["_id"], - "doc": item["_source"], - } - ) - helpers.bulk( - self.es, - actions, - chunk_size, - raise_on_error, - raise_on_exception, - stats_only, - yield_ok, - ) - - def importBulkList(self, listData, index_name): - chunk_size = 100000 - raise_on_error = False - raise_on_exception = False - stats_only = True - yield_ok = False - - for item in listData: - actions = [ - { - "_op_type": "index", - "_index": index_name, - "_id": item["_id"], - "_source": item["_source"], - } - ] - helpers.bulk( - self.es, - actions, - chunk_size, - raise_on_error, - raise_on_exception, - stats_only, - yield_ok, - ) - - def importJsonDataToElastic(self, jsonData, index_name, fields=[]): - chunk_size = 1000 - raise_on_error = False - raise_on_exception = False - stats_only = True - yield_ok = False - - actions = [] - - for item in jsonData: - id = item["_id"] if item["_id"] else item["id"] - source = item["_source"] - if fields: - source = {} - for col in fields: - if col in item["_source"]: - source[col] = item["_source"] - - actions.append( - { - "_op_type": "index", - "_index": index_name, - "_id": id, - "_source": source, - } - ) - helpers.bulk( - self.es, - actions, - chunk_size, - raise_on_error, - raise_on_exception, - stats_only, - yield_ok, - ) - - def fileToElastic(self, file_path, index_name, limit_pack=-1, fields=[]): - if not os.path.exists(file_path): - print("file zip:", file_path, " not exist") - return - print("index:", index_name, "=>", file_path) - self.counter = 0 - with open(file_path) as file: - data = json.loads(file.read()) - self.importJsonDataToElastic(data, index_name, fields) - - self.es.indices.refresh(index=index_name) - print(self.es.cat.count(index=index_name, format="json")) - - def zipFileToElastic(self, file_path, index_name, limit_pack=-1, fields=[]): - if not os.path.exists(file_path): - print( - "file zip:", file_path, " not exist for imort to elastic : ", index_name - ) - return - - fileNo = 0 - with zipfile.ZipFile(file_path, "r") as zObject: - fileNo += 1 - print( - "=" * 10, - " zip fileNo: ", - fileNo, - " - ( ", - index_name, - " ) | File Numbers:", - len(zObject.namelist()), - "=" * 10, - ) - - packNo = 0 - self.counter = 0 - for filename in zObject.namelist(): - packNo += 1 - if limit_pack != -1: - if packNo > limit_pack: - print("limit_data ", index_name, " ", limit_pack) - break - - print("index:", index_name, "=>", filename) - with zObject.open(filename) as file: - data = json.loads(file.read()) - self.importJsonDataToElastic(data, index_name, fields) - - self.es.indices.refresh(index=index_name) - print(self.es.cat.count(index=index_name, format="json")) - print(" END Of Import to elastic ", index_name, "\n") - - def iterateJsonFile(self, file_path, isZip=True, limit_pack=-1): - if not os.path.exists(file_path): - print("file zip:", file_path, " not exist iterateJsonFile ") - return - - if isZip: - fileNo = 0 - with zipfile.ZipFile(file_path, "r") as zObject: - fileNo += 1 - print( - "=" * 10, - " zip fileNo: ", - fileNo, - " iterateJsonFile - | File Numbers:", - len(zObject.namelist()), - "=" * 10, - ) - - packNo = 0 - self.counter = 0 - for filename in zObject.namelist(): - packNo += 1 - if limit_pack != -1: - if packNo > limit_pack: - print("limit_data iterateJsonFile ", limit_pack) - break - - print("index iterateJsonFile :", "=>", filename) - with zObject.open(filename) as file: - data = json.loads(file.read()) - # Yield each entry - # yield data - yield from ( - {"source": hit["_source"], "id": hit["_id"]} for hit in data - ) - else: - with open(filename, "r", encoding="utf-8") as file: - data = json.loads(file.read()) - # Yield each entry - # yield from (hit for hit in data) - # return data - yield from ( - {"source": hit["_source"], "id": hit["_id"]} for hit in data - ) - - def es_iterate_all_documents( - self, index, body="", pagesize=250, scroll_timeout="25m", **kwargs - ): - """ - Helper to iterate ALL values from a single index - Yields all the documents. - """ - is_first = True - while True: - # Scroll next - if is_first: # Initialize scroll - # result = self.es.search(index=index, scroll="2m", **kwargs, body={ - # "size": pagesize - # }) - if body: - result = self.es.search( - index=index, - scroll=scroll_timeout, - **kwargs, - size=pagesize, - body=body - ) - else: - result = self.es.search( - index=index, scroll=scroll_timeout, **kwargs, size=pagesize - ) - - self.total = result["hits"]["total"]["value"] - if self.total > 0: - print("total = %d" % self.total) - is_first = False - else: - # result = es.scroll(body={ - # "scroll_id": scroll_id, - # "scroll": scroll_timeout - # }) - result = self.es.scroll(scroll_id=scroll_id, scroll=scroll_timeout) - - scroll_id = result["_scroll_id"] - hits = result["hits"]["hits"] - self.counter += len(hits) - if self.total > 0: - print("progress -> %.2f %%" % ((self.counter / self.total) * 100)) - # Stop after no more docs - if not hits: - break - # Yield each entry - yield from ({"source": hit["_source"], "id": hit["_id"]} for hit in hits) - - def removeCustomFileds( - self, index_name_i, fields=[], renameFileds={}, body={}, bulk_update_size=200 - ): - try: - _list = [] - try: - _list = self.es_iterate_all_documents(index_name_i, body) - except Exception as e: - print(e) - - bulk_data = [] - count = 0 - total_count = 0 - for mentry in _list: - count += 1 - - entry = mentry["source"] - id = mentry["id"] - # print(id) - eid = id - - # if (count % 100) == 0 : - # print("%s -> %.2f " % (id , (count / self.total) if self.total > 0 else 0)) - - data_filled = False - data = entry - for col in fields: - if col in data: - del data[col] - - elif "." in col: - cols = col.split(".") - subsource = entry - for sub in cols: - dCol = subsource.get(sub, None) - if dCol: - subsource = dCol - else: - break - - for col in renameFileds.items(): - if col in data: - dCol = data[col] - data[renameFileds[col]] = dCol - del data[col] - - bulk_data.append({"_id": eid, "_source": data}) - - # انتقال دسته جمعی کدها به الاستیک - if len(bulk_data) >= bulk_update_size: - total_count += len(bulk_data) - print( - "=" * 5, - " update bulk --> ", - "total=" + str(total_count), - str(count), - ) - self.importBulkList(bulk_data, index_name_i) - bulk_data = [] - - if len(bulk_data) >= 0: - total_count += len(bulk_data) - print( - "=" * 5, - " update bulk --> ", - "total=" + str(total_count), - str(count), - ) - self.importBulkList(bulk_data, index_name_i) - bulk_data = [] - - except Exception as e: - # print("1111") - print(e) - - # save_error(id, e) - - def moveCustomFileds(self, index_name_i, index_name_o, fields=[], renameFileds={}): - try: - body = {} - list = [] - try: - list = self.es_iterate_all_documents(index_name_i) - except Exception as e: - print(e) - - count = 0 - for mentry in list: - count += 1 - - entry = mentry["source"] - id = mentry["id"] - # print(id) - eid = id - - if (count % 100) == 0: - print( - "%s -> %.2f " - % (id, (count / self.total) if self.total > 0 else 0) - ) - - data_filled = False - data = {} - for col in fields: - - if "." in col: - cols = col.split(".") - subsource = entry - for sub in cols: - dCol = subsource.get(sub, None) - if dCol: - subsource = dCol - else: - break - else: - dCol = entry.get(col, None) - - if dCol is None: - continue - - if col in renameFileds: - data[renameFileds[col]] = dCol - else: - data[col] = dCol - - data_filled = True - - if not data_filled: - continue - - try: - resp = self.update_index_doc(True, index_name_o, eid, data) - except Exception as e: - print(e) - # save_error(id, e) - - except Exception as e: - # print("1111") - print(e) - - # save_error(id, e) - - def mappingIndex(self, index_name_i): - # فقط از طریق کیبانا میشه تغییر مپ داد - - # با پایتون نمیشه - # باید ایندکس جدیدی با مپ مطلوب ایجاد کرد و رایندکس کرد - pass - - def updateByQueryIndex(self, index_name_i, body): - ## sample - # body = { - # "script": { - # "inline": "ctx._source.Device='Test'", - # "lang": "painless" - # }, - # "query": { - # "match": { - # "Device": "Boiler" - # } - # } - # } - try: - self.es.update_by_query(body=body, index=index_name_i) - - except Exception as e: - print(e) - # save_error(id, e) - - def deleteByQueryIndex(self, index_name_i, body): - ## sample - # body = { - # "query": { - # "match": { - # "Device": "Boiler" - # } - # } - # } - try: - self.es.delete_by_query(index=index_name_i, body=body) - - except Exception as e: - print(e) - # save_error(id, e) - - def delete_by_ids(self, index_name_i, ids): - try: - # ids = ['test1', 'test2', 'test3'] - - query = {"query": {"terms": {"_id": ids}}} - res = self.es.delete_by_query(index=index_name_i, body=query) - print(res) - - except Exception as e: - print(e) - # save_error(id, e) diff --git a/app/monir/new_schema/mn_term.py b/app/monir/new_schema/mn_term.py new file mode 100644 index 0000000..a4b33d4 --- /dev/null +++ b/app/monir/new_schema/mn_term.py @@ -0,0 +1,46 @@ +from pydantic import BaseModel + +class MnTerm(BaseModel): + id: str + main_type : str + "sub_type": str + "title": str + "content": str + "author": str + { + "type": "text", + "fields": { + "keyword": { + "type": "keyword", + "ignore_above": 256 + } + } + }, + "begin_date": { + "type": "date" + }, + "end_date": { + "type": "date" + }, + "begin_year": { + "type": "integer" + }, + "tags": { + "type": "text", + "fields": { + "keyword": { + "type": "keyword", + "ignore_above": 256 + } + } + }, + "keywords": { + "type": "text", + "fields": { + "keyword": { + "type": "keyword", + "ignore_above": 256 + } + } + } +} \ No newline at end of file diff --git a/app/monir/new_schema/monir.json b/app/monir/new_schema/monir.json index 81ab398..23404a6 100644 --- a/app/monir/new_schema/monir.json +++ b/app/monir/new_schema/monir.json @@ -1,325 +1,363 @@ { - "id": { - "type": "keyword" - }, - "person_code": { - "type": "keyword" - }, - "research_code": { - "type": "keyword" - }, - "meet_code": { - "type": "keyword" - }, - "old_meet_id": { - "type": "integer" - }, - "Allwords": { - "type": "text", - "fields": { + "id": { + "type": "keyword" + }, + "person_code": { + "type": "keyword" + }, + "research_code": { + "type": "keyword" + }, + "meet_code": { + "type": "keyword" + }, + "old_meet_id": { + "type": "integer" + }, + "Allwords": { + "type": "text", + "fields": { "keyword": { - "type": "keyword", - "ignore_above": 256 + "type": "keyword", + "ignore_above": 256 } - } - }, - "author": { - "type": "text", - "fields": { + } + }, + "author": { + "type": "text", + "fields": { "keyword": { - "type": "keyword", - "ignore_above": 256 + "type": "keyword", + "ignore_above": 256 } - } - }, + } + }, --"branch": { - "type": "text", - "fields": { + "type": "text", + "fields": { "keyword": { - "type": "keyword", - "ignore_above": 256 + "type": "keyword", + "ignore_above": 256 } - } - }, - "title": { - "type": "text", - "fields": { + } + }, + "title": { + "type": "text", + "fields": { "keyword": { - "type": "keyword", - "ignore_above": 256 + "type": "keyword", + "ignore_above": 256 } - } - }, - "meet_no": { - "type": "integer" - }, - "subject": { - "properties": { + } + }, + "meet_no": { + "type": "integer" + }, + "subject": { + "properties": { "id": { - "type": "integer" + "type": "integer" }, "title": { - "type": "text", - "fielddata": true, - "fields": { - "keyword": { - "type": "keyword", - "ignore_above": 256 + "type": "text", + "fielddata": true, + "fields": { + "keyword": { + "type": "keyword", + "ignore_above": 256 + } } - } } - } - }, - "subtitle": { - "type": "text", - "fields": { + } + }, + "subtitle": { + "type": "text", + "fields": { "keyword": { - "type": "keyword", - "ignore_above": 256 + "type": "keyword", + "ignore_above": 256 } - } - }, - "tags": { - "type": "text", - "fields": { + } + }, + "tags": { + "type": "text", + "fields": { "keyword": { - "type": "keyword", - "ignore_above": 256 + "type": "keyword", + "ignore_above": 256 } - } - }, - "keywords": { - "type": "text", - "fields": { + } + }, + "keywords": { + "type": "text", + "fields": { "keyword": { - "type": "keyword", - "ignore_above": 256 + "type": "keyword", + "ignore_above": 256 } - } - }, - "verb": { - "type": "text", - "fields": { + } + }, + "verb": { + "type": "text", + "fields": { "keyword": { - "type": "keyword", - "ignore_above": 256 + "type": "keyword", + "ignore_above": 256 } - } - }, - "format": { - "type": "text", - "fielddata": true, - "fields": { + } + }, + "format": { + "type": "text", + "fielddata": true, + "fields": { "keyword": { - "type": "keyword", - "ignore_above": 256 + "type": "keyword", + "ignore_above": 256 } - } - }, - "begin_year": { - "type": "integer", - "fields": { + } + }, + "begin_year": { + "type": "integer", + "fields": { "keyword": { - "type": "keyword", - "ignore_above": 20 + "type": "keyword", + "ignore_above": 20 } - } - }, - "begin_date": { - "type": "date" - }, - "end_date": { - "type": "date" - }, - "amplify": { - "type": "text" - }, - "ralation": { - "type": "keyword" - }, - "city": { - "type": "keyword" - }, - "place": { - "type": "keyword" - }, - "address": { - "type": "text" - }, - "films": { - "type": "integer" - }, - "sounds": { - "type": "integer" - }, - "photos": { - "type": "integer" - }, - "in_tadvin": { - "type": "boolean" - }, - "video_links": { - "properties": { - "title": {"type": "keyword"}, - "link": {"type": "text"} - } - }, - "sound_links": { - "properties": { - "title": {"type": "keyword"}, - "link": {"type": "text"} - } - }, - "photo_links": { - "properties": { - "title": {"type": "keyword"}, - "link": {"type": "text"} - } - }, - "file_links": { - "properties": { - "title": {"type": "keyword"}, - "link": {"type": "text"}, - "text": {"type": "text"}, - "date": {"type": "date"}, - "in_search": {"type": "boolean"} - } - }, - "audience": { - "type": "text", - "fielddata": true - }, - "attendees": { - "type": "text" - }, - "report_tmp": { - "properties": { - "address": {"type": "integer"}, - "mindex": {"type": "integer"}, - "mintro": {"type": "integer"}, - "sanad_data1": {"type": "integer"}, - "sanad_data2": {"type": "integer"} + } + }, + "begin_date": { + "type": "date" + }, + "end_date": { + "type": "date" + }, + "amplify": { + "type": "text" + }, + "ralation": { + "type": "keyword" + }, + "city": { + "type": "keyword" + }, + "place": { + "type": "keyword" + }, + "address": { + "type": "text" + }, + "films": { + "type": "integer" + }, + "sounds": { + "type": "integer" + }, + "photos": { + "type": "integer" + }, + "in_tadvin": { + "type": "boolean" + }, + "video_links": { + "properties": { + "title": { + "type": "keyword" + }, + "link": { + "type": "text" } - }, - "mindex": { - "type": "text", - "fields": { + } + }, + "sound_links": { + "properties": { + "title": { + "type": "keyword" + }, + "link": { + "type": "text" + } + } + }, + "photo_links": { + "properties": { + "title": { + "type": "keyword" + }, + "link": { + "type": "text" + } + } + }, + "file_links": { + "properties": { + "title": { + "type": "keyword" + }, + "link": { + "type": "text" + }, + "text": { + "type": "text" + }, + "date": { + "type": "date" + }, + "in_search": { + "type": "boolean" + } + } + }, + "audience": { + "type": "text", + "fielddata": true + }, + "attendees": { + "type": "text" + }, + "report_tmp": { + "properties": { + "address": { + "type": "integer" + }, + "mindex": { + "type": "integer" + }, + "mintro": { + "type": "integer" + }, + "sanad_data1": { + "type": "integer" + }, + "sanad_data2": { + "type": "integer" + } + } + }, + "mindex": { + "type": "text", + "fields": { "fa": { - "type": "text", - "analyzer": "normal_analyzer_persian", - "search_analyzer": "normal_analyzer_persian", - "search_quote_analyzer": "phrase_analyzer_persian" - }, - "ar": { - "type": "text", - "analyzer": "normal_analyzer_arabic", - "search_analyzer": "normal_analyzer_arabic", - "search_quote_analyzer": "phrase_analyzer_arabic" - }, - "ph": { - "type": "text", - "analyzer": "phrase_analyzer_persian", - "search_analyzer": "phrase_analyzer_persian", - "search_quote_analyzer": "phrase_analyzer_persian" - } - } - }, - "mintro": { - "type": "text", - "fields": { - "fa": { - "type": "text", - "analyzer": "normal_analyzer_persian", - "search_analyzer": "normal_analyzer_persian", - "search_quote_analyzer": "phrase_analyzer_persian" - }, - "ar": { - "type": "text", - "analyzer": "normal_analyzer_arabic", - "search_analyzer": "normal_analyzer_arabic", - "search_quote_analyzer": "phrase_analyzer_arabic" - }, - "ph": { - "type": "text", - "analyzer": "phrase_analyzer_persian", - "search_analyzer": "phrase_analyzer_persian", - "search_quote_analyzer": "phrase_analyzer_persian" - } - } - }, - "content": { - "type": "text", - "fields": { - "fa": { - "type": "text", - "analyzer": "normal_analyzer_persian", - "search_analyzer": "normal_analyzer_persian", - "search_quote_analyzer": "phrase_analyzer_persian" - }, - "ar": { - "type": "text", - "analyzer": "normal_analyzer_arabic", - "search_analyzer": "normal_analyzer_arabic", - "search_quote_analyzer": "phrase_analyzer_arabic" - }, - "ph": { - "type": "text", - "analyzer": "phrase_analyzer_persian", - "search_analyzer": "phrase_analyzer_persian", - "search_quote_analyzer": "phrase_analyzer_persian" - } - } - }, - "version_info": { - "properties": { - "number" : {"type": "integer"}, - "title": {"type": "keyword"}, - "timestamp": {"type": "long"} - } - }, - "next_page": { - "type": "integer" - }, - "completion" : { - "type" : "completion", - "analyzer" : "simple", - "preserve_separators" : true, - "preserve_position_increments" : true, - "max_input_length" : 50 - }, - "sort_date_timestamp": { - "type": "long" - }, - "permit_tags":{ - "type": "keyword" - }, - "resource_info": { - "type": "text", - "fields": { - "fa": { "type": "text", "analyzer": "normal_analyzer_persian", "search_analyzer": "normal_analyzer_persian", "search_quote_analyzer": "phrase_analyzer_persian" - }, - "ar": { + }, + "ar": { "type": "text", "analyzer": "normal_analyzer_arabic", "search_analyzer": "normal_analyzer_arabic", "search_quote_analyzer": "phrase_analyzer_arabic" - }, - "ph": { + }, + "ph": { "type": "text", "analyzer": "phrase_analyzer_persian", "search_analyzer": "phrase_analyzer_persian", "search_quote_analyzer": "phrase_analyzer_persian" - } } - }, - "user_owner":{ - "type": "integer" - }, - "draft_step":{ - "type": "keyword" - } - } \ No newline at end of file + } + }, + "mintro": { + "type": "text", + "fields": { + "fa": { + "type": "text", + "analyzer": "normal_analyzer_persian", + "search_analyzer": "normal_analyzer_persian", + "search_quote_analyzer": "phrase_analyzer_persian" + }, + "ar": { + "type": "text", + "analyzer": "normal_analyzer_arabic", + "search_analyzer": "normal_analyzer_arabic", + "search_quote_analyzer": "phrase_analyzer_arabic" + }, + "ph": { + "type": "text", + "analyzer": "phrase_analyzer_persian", + "search_analyzer": "phrase_analyzer_persian", + "search_quote_analyzer": "phrase_analyzer_persian" + } + } + }, + "content": { + "type": "text", + "fields": { + "fa": { + "type": "text", + "analyzer": "normal_analyzer_persian", + "search_analyzer": "normal_analyzer_persian", + "search_quote_analyzer": "phrase_analyzer_persian" + }, + "ar": { + "type": "text", + "analyzer": "normal_analyzer_arabic", + "search_analyzer": "normal_analyzer_arabic", + "search_quote_analyzer": "phrase_analyzer_arabic" + }, + "ph": { + "type": "text", + "analyzer": "phrase_analyzer_persian", + "search_analyzer": "phrase_analyzer_persian", + "search_quote_analyzer": "phrase_analyzer_persian" + } + } + }, + "version_info": { + "properties": { + "number": { + "type": "integer" + }, + "title": { + "type": "keyword" + }, + "timestamp": { + "type": "long" + } + } + }, + "next_page": { + "type": "integer" + }, + "completion": { + "type": "completion", + "analyzer": "simple", + "preserve_separators": true, + "preserve_position_increments": true, + "max_input_length": 50 + }, + "sort_date_timestamp": { + "type": "long" + }, + "permit_tags": { + "type": "keyword" + }, + "resource_info": { + "type": "text", + "fields": { + "fa": { + "type": "text", + "analyzer": "normal_analyzer_persian", + "search_analyzer": "normal_analyzer_persian", + "search_quote_analyzer": "phrase_analyzer_persian" + }, + "ar": { + "type": "text", + "analyzer": "normal_analyzer_arabic", + "search_analyzer": "normal_analyzer_arabic", + "search_quote_analyzer": "phrase_analyzer_arabic" + }, + "ph": { + "type": "text", + "analyzer": "phrase_analyzer_persian", + "search_analyzer": "phrase_analyzer_persian", + "search_quote_analyzer": "phrase_analyzer_persian" + } + } + }, + "user_owner": { + "type": "integer" + }, + "draft_step": { + "type": "keyword" + } +} \ No newline at end of file diff --git a/app/monir/sanad_stuff.py b/app/monir/sanad_stuff.py index 6cee4b2..3c1a257 100644 --- a/app/monir/sanad_stuff.py +++ b/app/monir/sanad_stuff.py @@ -1,9 +1,38 @@ -from elastic_helper import ElasticHelper +# --------------------------- modularity +from app.common.elastic_helper import ElasticHelper +from pydantic import BaseModel +# --------------------------- global-params +base_index_name = 'monir_test_term' +id_data = None +_data = None + + +# --------------------------- function +def generate_pydantic_model_from_mapping(model_name: str, mapping_es: dict) -> type[BaseModel]: + fields = {} + for field_name, field_def in mapping["properties"].items(): + es_type = field_def["type"] + py_type = ES_TO_PYDANTIC.get(es_type, str) + + # اضافه کردن optional بودن؟ یا default؟ بسته به نیاز + fields[field_name] = (py_type, ...) + + return type(name, (BaseModel,), {"__annotations__": fields}) + + +# --------------------------- flow es_helper = ElasticHelper( es_url="http://127.0.0.1:6900", es_user="elastic", # es_pass="", # path_mappings = "" ) - \ No newline at end of file + + +es_helper.update_index_doc( + is_update_state=False, + index_name_o=base_index_name, + eid=id_data, + data=_data +) \ No newline at end of file diff --git a/app/repair_data/r1_LawSection_repair1.py b/app/repair_data/r1_LawSection_repair1.py index c749450..ca64701 100644 --- a/app/repair_data/r1_LawSection_repair1.py +++ b/app/repair_data/r1_LawSection_repair1.py @@ -139,7 +139,7 @@ def repair_law_section_text(cursor, elastic, index_name, dict_changed, file_log) item = {} try: - item = elastic.get_doctument(index_name, eid) + item = elastic.get_document(index_name, eid) # در اینصورت محتوای ماده توسط مجلس تغییر یافته است text_m = text_normal.normalize_qanon(item['_source']['content'], True).strip().replace(' ', '') text_m2 = text_normal.normalize_qanon(text, True).strip().replace(' ', '') @@ -198,7 +198,7 @@ def repair_error_new_section_ts_date( elastic, index_name, dict_changed, file_lo ts_year = '' item = {} try: - item = elastic.get_doctument(index_name, eid_prev) + item = elastic.get_document(index_name, eid_prev) ts_date = item['_source']['ts_date'] ts_year = item['_source']['ts_year'] sort_date_timestamp = item['_source']['sort_date_timestamp'] @@ -570,7 +570,7 @@ dict_effected_sections, dict_effected_new_sections = extract_all_effecteds(elast # print(dict_effected_sections) # try: -# item = elastic.get_doctument("mj_qa_section", "3223423") +# item = elastic.get_document("mj_qa_section", "3223423") # except Exception as e: # print(e) # print(type(e).__name__) diff --git a/app/repair_data/r7_doc_state_update.py b/app/repair_data/r7_doc_state_update.py index 6e02156..71ad830 100644 --- a/app/repair_data/r7_doc_state_update.py +++ b/app/repair_data/r7_doc_state_update.py @@ -159,7 +159,7 @@ elastic = ElasticHelper(host, password, "elastic", path_base_map) # print(dict_effected_sections) # try: -# item = elastic.get_doctument("mj_qa_section", "3223423") +# item = elastic.get_document("mj_qa_section", "3223423") # except Exception as e: # print(e) # print(type(e).__name__)