This commit is contained in:
init_mahdi
2025-11-06 16:34:54 +03:30
parent 0d99c9adf4
commit 47ec6c1e27
6 changed files with 926 additions and 837 deletions
+10
View File
@@ -32,3 +32,13 @@ yarn-error.log*
*.rar *.rar
*.zip *.zip
analyzed_domains.json 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
+234 -171
View File
@@ -5,19 +5,26 @@ import json
from time import sleep from time import sleep
from elasticsearch import Elasticsearch, helpers from elasticsearch import Elasticsearch, helpers
class ElasticHelper():
class ElasticHelper:
counter = 0 counter = 0
total = 0 total = 0
id = "" id = ""
path_mappings = os.getcwd() + '/repo/_other/' path_mappings = os.getcwd() + "/repo/_other/"
def __init__(self, es_url="http://127.0.0.1:6900", es_pass="", es_user="elastic", path_mappings = ""): def __init__(
self,
es_url="http://127.0.0.1:6900",
es_pass="",
es_user="elastic",
path_mappings="",
):
if path_mappings: if path_mappings:
self.path_mappings = path_mappings self.path_mappings = path_mappings
if es_pass == '' : if es_pass == "":
self.es = Elasticsearch(es_url) self.es = Elasticsearch(es_url)
else: else:
self.es = Elasticsearch( self.es = Elasticsearch(
@@ -32,7 +39,7 @@ class ElasticHelper():
for a in range(0, 10): for a in range(0, 10):
try: try:
if not self.es.ping(): if not self.es.ping():
print('elastic not ping, sleep 30 s : ', a) print("elastic not ping, sleep 30 s : ", a)
sleep(5) sleep(5)
continue continue
else: else:
@@ -42,20 +49,18 @@ class ElasticHelper():
except Exception as e: except Exception as e:
break break
if not self.success_connect: if not self.success_connect:
print('******','not access to elastic service') print("******", "not access to elastic service")
return return
self.counter = 0 self.counter = 0
self.total = 0 self.total = 0
self.id = "" self.id = ""
def get_document(self, index_name, id):
def get_doctument(self, index_name, id):
res = self.es.get(index=index_name, id=id) res = self.es.get(index=index_name, id=id)
return res 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) res = self.es.exists(index=index_name, id=id)
return res return res
@@ -67,35 +72,38 @@ class ElasticHelper():
resp = self.es.index(index=index_name_o, id=eid, document=data) resp = self.es.index(index=index_name_o, id=eid, document=data)
return resp return resp
def exportToJsonForAI(
def exportToJsonForAI(self, path_back, index_name, out_name= '', body={}, fields=[], mode='normal', collapse_field = '') : self,
print('*' * 50, ' start backup -->', index_name) path_back,
index_name,
out_name="",
body={},
fields=[],
mode="normal",
collapse_field="",
):
print("*" * 50, " start backup -->", index_name)
self.counter = 0 self.counter = 0
sid = None sid = None
out = out_name out = out_name
if out_name == '' : if out_name == "":
out = index_name out = index_name
s_res = self.es.search( s_res = self.es.search(index=index_name, scroll="5m", size=1000, body=body)
index=index_name, self.total = s_res["hits"]["total"]["value"]
scroll='5m',
size=1000,
body=body
)
self.total = s_res["hits"]["total"]['value']
print('start index = %s' % index_name) print("start index = %s" % index_name)
print('total = %d' % self.total) print("total = %d" % self.total)
sid = s_res['_scroll_id'] sid = s_res["_scroll_id"]
scroll_size = len(s_res['hits']['hits']) scroll_size = len(s_res["hits"]["hits"])
pack_count = 1 pack_count = 1
out_json = [] out_json = []
if mode == 'dict' or collapse_field: if mode == "dict" or collapse_field:
out_json = {} out_json = {}
prev_collapse_value = '' prev_collapse_value = ""
pack_collapse = [] pack_collapse = []
while scroll_size > 0: while scroll_size > 0:
"Scrolling..." "Scrolling..."
@@ -107,22 +115,22 @@ class ElasticHelper():
# break # break
pack_count += 1 pack_count += 1
############################# #############################
for item in s_res['hits']['hits']: for item in s_res["hits"]["hits"]:
id = item['_id'] id = item["_id"]
item2 = None item2 = None
if mode =='id' : # فقط شناسه ها نیاز هست if mode == "id": # فقط شناسه ها نیاز هست
item2 = id item2 = id
elif fields: elif fields:
item2 = {} item2 = {}
item2['id']= id item2["id"] = id
for kf in fields: for kf in fields:
# print(kf) # print(kf)
if kf in item['_source'] : if kf in item["_source"]:
# print(item['_source'][kf]) # print(item['_source'][kf])
item2[kf] = item['_source'][kf] item2[kf] = item["_source"][kf]
elif '.' in kf : elif "." in kf:
cols = kf.split('.') cols = kf.split(".")
subsource = item['_source'] subsource = item["_source"]
for sub in cols: for sub in cols:
if sub in subsource: if sub in subsource:
subsource = subsource[sub] subsource = subsource[sub]
@@ -137,8 +145,8 @@ class ElasticHelper():
item2 = {} item2 = {}
item2 = item item2 = item
if collapse_field and collapse_field in item['_source']: if collapse_field and collapse_field in item["_source"]:
collapse_value = item['_source'][collapse_field] collapse_value = item["_source"][collapse_field]
if not prev_collapse_value: if not prev_collapse_value:
prev_collapse_value = collapse_value prev_collapse_value = collapse_value
@@ -149,15 +157,14 @@ class ElasticHelper():
pack_collapse.append(item2) pack_collapse.append(item2)
elif mode == 'dict': elif mode == "dict":
out_json[id] = item2 out_json[id] = item2
else: else:
out_json.append(item2) out_json.append(item2)
s_res = self.es.scroll(scroll_id=sid, scroll="2m", request_timeout=100000)
s_res = self.es.scroll(scroll_id=sid, scroll='2m', request_timeout=100000) sid = s_res["_scroll_id"]
sid = s_res['_scroll_id'] scroll_size = len(s_res["hits"]["hits"])
scroll_size = len(s_res['hits']['hits'])
sid = None sid = None
@@ -169,47 +176,45 @@ class ElasticHelper():
############################## ##############################
def backupIndexToZipfile(self, path_back, index_name, file_name= '', body={}, byzip = True, fields=[], noFields=[]) : def backupIndexToZipfile(
print('*' * 50, ' start backup -->', index_name) self,
path_back,
index_name,
file_name="",
body={},
byzip=True,
fields=[],
noFields=[],
):
print("*" * 50, " start backup -->", index_name)
self.counter = 0 self.counter = 0
sid = None sid = None
out = index_name out = index_name
if file_name == '' : if file_name == "":
file_name = index_name file_name = index_name
if body == {}: if body == {}:
s_res = self.es.search( s_res = self.es.search(index=index_name, scroll="5m", size=1000)
index=index_name,
scroll='5m',
size=1000
)
else: else:
s_res = self.es.search( s_res = self.es.search(index=index_name, scroll="5m", size=1000, body=body)
index=index_name,
scroll='5m',
size=1000,
body=body
)
self.total = s_res["hits"]["total"]['value'] self.total = s_res["hits"]["total"]["value"]
if self.total == 0: if self.total == 0:
print('total index_name by query = %d' % self.total) print("total index_name by query = %d" % self.total)
return False return False
if byzip: if byzip:
fout = zipfile.ZipFile(path_back + "/"+ file_name + '.zip', 'w') fout = zipfile.ZipFile(path_back + "/" + file_name + ".zip", "w")
else: else:
fout = open( path_back + "/"+ file_name + '.json', 'a+' , encoding='utf-8') 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) sid = s_res["_scroll_id"]
print('total = %d' % self.total) scroll_size = len(s_res["hits"]["hits"])
sid = s_res['_scroll_id']
scroll_size = len(s_res['hits']['hits'])
file_count = 1 file_count = 1
while scroll_size > 0: while scroll_size > 0:
"Scrolling..." "Scrolling..."
@@ -217,49 +222,48 @@ class ElasticHelper():
print("progress -> %.2f %%" % ((self.counter / self.total) * 100)) print("progress -> %.2f %%" % ((self.counter / self.total) * 100))
############################# #############################
out_json = [] out_json = []
for item in s_res['hits']['hits']: for item in s_res["hits"]["hits"]:
if fields: if fields:
item2 = {} item2 = {}
item2['id']=item['_id'] item2["id"] = item["_id"]
item2['_source']={} item2["_source"] = {}
for kf in fields: for kf in fields:
if kf in item['_source'] : if kf in item["_source"]:
item2['_source'][kf] = item['_source'][kf] item2["_source"][kf] = item["_source"][kf]
else: else:
item2 = item item2 = item
if noFields: if noFields:
for kf in noFields: for kf in noFields:
if kf in item2['_source']: if kf in item2["_source"]:
del item2['_source'][kf] del item2["_source"][kf]
out_json.append(item2) out_json.append(item2)
text = json.dumps(out_json, ensure_ascii=False) text = json.dumps(out_json, ensure_ascii=False)
out_json = [] out_json = []
if byzip: if byzip:
filename = out + str(file_count) + '.json' filename = out + str(file_count) + ".json"
file_count += 1 file_count += 1
fout.writestr(filename, text.encode('utf-8'), zipfile.ZIP_DEFLATED ) fout.writestr(filename, text.encode("utf-8"), zipfile.ZIP_DEFLATED)
else: else:
fout.write(text) fout.write(text)
############################## ##############################
s_res = self.es.scroll(scroll_id=sid, scroll='2m', request_timeout=100000) s_res = self.es.scroll(scroll_id=sid, scroll="2m", request_timeout=100000)
sid = s_res['_scroll_id'] sid = s_res["_scroll_id"]
scroll_size = len(s_res['hits']['hits']) scroll_size = len(s_res["hits"]["hits"])
sid = None sid = None
fout.close() fout.close()
def restorFileToElastic(
def restorFileToElastic(self, path_back, index_name, app_key = '', queryDelete = True, map_name='') : self, path_back, index_name, app_key="", queryDelete=True, map_name=""
):
if not os.path.exists(path_back): if not os.path.exists(path_back):
print(' **** error *** path not exist: ', path_back) print(" **** error *** path not exist: ", path_back)
return False return False
file_path = path_back + '/' + index_name + '.zip' file_path = path_back + "/" + index_name + ".zip"
if not os.path.exists(file_path): if not os.path.exists(file_path):
return False return False
@@ -272,9 +276,11 @@ class ElasticHelper():
self.createIndex(index_name, app_key, map_name) 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='') : def restorFileToElastic2(
self, path_file, index_name, app_key="", queryDelete=True, map_name=""
):
if not os.path.exists(path_file): if not os.path.exists(path_file):
print(' **** error *** path not exist: ', path_file) print(" **** error *** path not exist: ", path_file)
return False return False
file_path = path_file file_path = path_file
@@ -290,16 +296,16 @@ class ElasticHelper():
self.createIndex(index_name, app_key, map_name) self.createIndex(index_name, app_key, map_name)
self.zipFileToElastic(file_path, index_name) self.zipFileToElastic(file_path, index_name)
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): if self.createIndex(index_name_o, app_key, map_name):
res = self.es.reindex( res = self.es.reindex(
body={ body={
"source": {"index": index_name_i}, "source": {"index": index_name_i},
"dest": {"index": index_name_o} "dest": {"index": index_name_o},
}, },
wait_for_completion=False) wait_for_completion=False,
)
print(type(res)) print(type(res))
print(res) print(res)
@@ -313,20 +319,26 @@ class ElasticHelper():
break break
# print( res["task"]) # print( res["task"])
print( '----', index_name_o, ' imported : ', res["task"]["status"]["total"] , ' / ', res["task"]["status"]["created"]) print(
"----",
index_name_o,
" imported : ",
res["task"]["status"]["total"],
" / ",
res["task"]["status"]["created"],
)
sleep(1) sleep(1)
print( '----', index_name_o, ' complated') print("----", index_name_o, " complated")
def deleteIndex(self, index_name): def deleteIndex(self, index_name):
if not self.es.indices.exists(index=index_name): if not self.es.indices.exists(index=index_name):
print(' ' * 10, " for delete NOT exist index :", index_name ) print(" " * 10, " for delete NOT exist index :", index_name)
return True return True
question = 'Is DELETE elastic index (' + index_name +') ? ' question = "Is DELETE elastic index (" + index_name + ") ? "
if self.query_yes_no(question): if self.query_yes_no(question):
self.es.indices.delete(index=index_name) self.es.indices.delete(index=index_name)
print('%' * 10 , " Finish DELETE index :", index_name ) print("%" * 10, " Finish DELETE index :", index_name)
return True return True
else: else:
return False return False
@@ -343,7 +355,7 @@ class ElasticHelper():
raise ValueError("invalid default answer: '%s'" % default) raise ValueError("invalid default answer: '%s'" % default)
while True: while True:
print('%'*10, ' quistion ', '%'*10 , '\n') print("%" * 10, " quistion ", "%" * 10, "\n")
sys.stdout.write(question + prompt) sys.stdout.write(question + prompt)
choice = input().lower() choice = input().lower()
if default is not None and choice == "": if default is not None and choice == "":
@@ -351,7 +363,10 @@ class ElasticHelper():
elif choice in valid: elif choice in valid:
return valid[choice] return valid[choice]
else: else:
sys.stdout.write("لطفا یکی از موارد روبرو را وارد کنید : 'yes' or 'no' " "(or 'y' or 'n').\n") sys.stdout.write(
"لطفا یکی از موارد روبرو را وارد کنید : 'yes' or 'no' "
"(or 'y' or 'n').\n"
)
def createIndexIfNotExist(self, index_name_o, mapping_o=""): def createIndexIfNotExist(self, index_name_o, mapping_o=""):
try: try:
@@ -362,40 +377,38 @@ class ElasticHelper():
except: except:
print("....... index exist ! ... not created") print("....... index exist ! ... not created")
def createIndex(self, index_name, app_key="", map_name=""):
def createIndex(self, index_name, app_key='', map_name=''):
path_base = self.path_mappings path_base = self.path_mappings
path_mapping1 = path_base + 'general/' path_mapping1 = path_base + "general/"
if app_key == '' : if app_key == "":
app_key = 'tavasi' app_key = "tavasi"
path_mapping2 = path_base + app_key + '/' path_mapping2 = path_base + app_key + "/"
if map_name == "":
if map_name == '':
map_name = index_name map_name = index_name
if self.es.indices.exists(index=index_name): if self.es.indices.exists(index=index_name):
print("============== exist index :", index_name) print("============== exist index :", index_name)
return True return True
if map_name == 'mj_rg_section' or map_name == 'semantic_search' : if map_name == "mj_rg_section" or map_name == "semantic_search":
map_name = 'mj_qa_section' map_name = "mj_qa_section"
elif map_name[-3]=='_ai': elif map_name[-3] == "_ai":
map_name = [0 - len(map_name) - 3] map_name = [0 - len(map_name) - 3]
print(map_name) print(map_name)
mapping_file_path = path_mapping1 + map_name + '.json' mapping_file_path = path_mapping1 + map_name + ".json"
print("mapping_file_path : ", mapping_file_path) print("mapping_file_path : ", mapping_file_path)
if not os.path.isfile(mapping_file_path): if not os.path.isfile(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 # Create Index With Mapping
if os.path.isfile(mapping_file_path): 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_file_read = mapping_file.read()
mapping_data = json.loads(mapping_file_read) mapping_data = json.loads(mapping_file_read)
mapping_file.close() mapping_file.close()
@@ -405,10 +418,9 @@ class ElasticHelper():
self.es.indices.create(index=index_name, body=mapping_data) self.es.indices.create(index=index_name, body=mapping_data)
return True return True
else: else:
print('*** error not find maping file elastic : *******', mapping_file_path) print("*** error not find maping file elastic : *******", mapping_file_path)
return False return False
def updateBulkList(self, listData, index_name): def updateBulkList(self, listData, index_name):
chunk_size = 1000 chunk_size = 1000
raise_on_error = False raise_on_error = False
@@ -418,14 +430,23 @@ class ElasticHelper():
actions = [] actions = []
for item in listData: for item in listData:
actions.append({ actions.append(
{
"_op_type": "update", "_op_type": "update",
"_index": index_name, "_index": index_name,
"_id" : item['_id'], "_id": item["_id"],
"doc": item['_source'] "doc": item["_source"],
} }
) )
helpers.bulk(self.es, actions, chunk_size, raise_on_error, raise_on_exception, stats_only, yield_ok ) helpers.bulk(
self.es,
actions,
chunk_size,
raise_on_error,
raise_on_exception,
stats_only,
yield_ok,
)
def importBulkList(self, listData, index_name): def importBulkList(self, listData, index_name):
chunk_size = 100000 chunk_size = 100000
@@ -435,15 +456,23 @@ class ElasticHelper():
yield_ok = False yield_ok = False
for item in listData: for item in listData:
actions = [{ actions = [
{
"_op_type": "index", "_op_type": "index",
"_index": index_name, "_index": index_name,
"_id" : item['_id'], "_id": item["_id"],
"_source": item['_source'] "_source": item["_source"],
} }
] ]
helpers.bulk(self.es, actions, chunk_size, raise_on_error, raise_on_exception, stats_only, yield_ok ) helpers.bulk(
self.es,
actions,
chunk_size,
raise_on_error,
raise_on_exception,
stats_only,
yield_ok,
)
def importJsonDataToElastic(self, jsonData, index_name, fields=[]): def importJsonDataToElastic(self, jsonData, index_name, fields=[]):
chunk_size = 1000 chunk_size = 1000
@@ -455,29 +484,37 @@ class ElasticHelper():
actions = [] actions = []
for item in jsonData: for item in jsonData:
id = item['_id'] if item['_id'] else item['id'] id = item["_id"] if item["_id"] else item["id"]
source = item['_source'] source = item["_source"]
if fields: if fields:
source = {} source = {}
for col in fields: for col in fields:
if col in item['_source'] : if col in item["_source"]:
source[col] = item['_source'] source[col] = item["_source"]
actions.append(
actions.append({ {
"_op_type": "index", "_op_type": "index",
"_index": index_name, "_index": index_name,
"_id": id, "_id": id,
"_source": source "_source": source,
}) }
helpers.bulk(self.es, actions, chunk_size, raise_on_error, raise_on_exception, stats_only, yield_ok ) )
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=[]): def fileToElastic(self, file_path, index_name, limit_pack=-1, fields=[]):
if not os.path.exists(file_path): if not os.path.exists(file_path):
print("file zip:", file_path, " not exist") print("file zip:", file_path, " not exist")
return return
print("index:" , index_name , '=>' , file_path ) print("index:", index_name, "=>", file_path)
self.counter = 0 self.counter = 0
with open(file_path) as file: with open(file_path) as file:
data = json.loads(file.read()) data = json.loads(file.read())
@@ -488,13 +525,24 @@ class ElasticHelper():
def zipFileToElastic(self, file_path, index_name, limit_pack=-1, fields=[]): def zipFileToElastic(self, file_path, index_name, limit_pack=-1, fields=[]):
if not os.path.exists(file_path): if not os.path.exists(file_path):
print("file zip:" , file_path , " not exist for imort to elastic : ", index_name ) print(
"file zip:", file_path, " not exist for imort to elastic : ", index_name
)
return return
fileNo = 0 fileNo = 0
with zipfile.ZipFile(file_path, 'r') as zObject: with zipfile.ZipFile(file_path, "r") as zObject:
fileNo += 1 fileNo += 1
print("="*10, " zip fileNo: " , fileNo ," - ( ", index_name," ) | File Numbers:" ,len(zObject.namelist()) , "=" * 10) print(
"=" * 10,
" zip fileNo: ",
fileNo,
" - ( ",
index_name,
" ) | File Numbers:",
len(zObject.namelist()),
"=" * 10,
)
packNo = 0 packNo = 0
self.counter = 0 self.counter = 0
@@ -502,10 +550,10 @@ class ElasticHelper():
packNo += 1 packNo += 1
if limit_pack != -1: if limit_pack != -1:
if packNo > limit_pack: if packNo > limit_pack:
print('limit_data ', index_name, ' ', limit_pack) print("limit_data ", index_name, " ", limit_pack)
break break
print("index:" , index_name , '=>' , filename ) print("index:", index_name, "=>", filename)
with zObject.open(filename) as file: with zObject.open(filename) as file:
data = json.loads(file.read()) data = json.loads(file.read())
self.importJsonDataToElastic(data, index_name, fields) self.importJsonDataToElastic(data, index_name, fields)
@@ -514,7 +562,6 @@ class ElasticHelper():
print(self.es.cat.count(index=index_name, format="json")) print(self.es.cat.count(index=index_name, format="json"))
print(" END Of Import to elastic ", index_name, "\n") print(" END Of Import to elastic ", index_name, "\n")
def iterateJsonFile(self, file_path, isZip=True, limit_pack=-1): def iterateJsonFile(self, file_path, isZip=True, limit_pack=-1):
if not os.path.exists(file_path): if not os.path.exists(file_path):
print("file zip:", file_path, " not exist iterateJsonFile ") print("file zip:", file_path, " not exist iterateJsonFile ")
@@ -522,9 +569,16 @@ class ElasticHelper():
if isZip: if isZip:
fileNo = 0 fileNo = 0
with zipfile.ZipFile(file_path, 'r') as zObject: with zipfile.ZipFile(file_path, "r") as zObject:
fileNo += 1 fileNo += 1
print("="*10, " zip fileNo: " , fileNo ," iterateJsonFile - | File Numbers:" ,len(zObject.namelist()) , "=" * 10) print(
"=" * 10,
" zip fileNo: ",
fileNo,
" iterateJsonFile - | File Numbers:",
len(zObject.namelist()),
"=" * 10,
)
packNo = 0 packNo = 0
self.counter = 0 self.counter = 0
@@ -532,25 +586,30 @@ class ElasticHelper():
packNo += 1 packNo += 1
if limit_pack != -1: if limit_pack != -1:
if packNo > limit_pack: if packNo > limit_pack:
print('limit_data iterateJsonFile ', limit_pack) print("limit_data iterateJsonFile ", limit_pack)
break break
print("index iterateJsonFile :", '=>' , filename ) print("index iterateJsonFile :", "=>", filename)
with zObject.open(filename) as file: with zObject.open(filename) as file:
data = json.loads(file.read()) data = json.loads(file.read())
# Yield each entry # Yield each entry
# yield data # yield data
yield from ({"source": hit["_source"], "id": hit["_id"]} for hit in data) yield from (
{"source": hit["_source"], "id": hit["_id"]} for hit in data
)
else: else:
with open(filename, 'r', encoding='utf-8') as file: with open(filename, "r", encoding="utf-8") as file:
data = json.loads(file.read()) data = json.loads(file.read())
# Yield each entry # Yield each entry
# yield from (hit for hit in data) # yield from (hit for hit in data)
# return data # return data
yield from ({"source": hit["_source"], "id": hit["_id"]} for hit in data) yield from (
{"source": hit["_source"], "id": hit["_id"]} for hit in data
)
def es_iterate_all_documents(
def es_iterate_all_documents(self, index, body="", pagesize=250, scroll_timeout="25m", **kwargs): self, index, body="", pagesize=250, scroll_timeout="25m", **kwargs
):
""" """
Helper to iterate ALL values from a single index Helper to iterate ALL values from a single index
Yields all the documents. Yields all the documents.
@@ -572,10 +631,7 @@ class ElasticHelper():
) )
else: else:
result = self.es.search( result = self.es.search(
index=index, index=index, scroll=scroll_timeout, **kwargs, size=pagesize
scroll=scroll_timeout,
**kwargs,
size=pagesize
) )
self.total = result["hits"]["total"]["value"] self.total = result["hits"]["total"]["value"]
@@ -600,8 +656,9 @@ class ElasticHelper():
# Yield each entry # Yield each entry
yield from ({"source": hit["_source"], "id": hit["_id"]} for hit in hits) yield from ({"source": hit["_source"], "id": hit["_id"]} for hit in hits)
def removeCustomFileds(
def removeCustomFileds(self, index_name_i, fields=[], renameFileds={}, body={}, bulk_update_size=200): self, index_name_i, fields=[], renameFileds={}, body={}, bulk_update_size=200
):
try: try:
_list = [] _list = []
try: try:
@@ -629,8 +686,8 @@ class ElasticHelper():
if col in data: if col in data:
del data[col] del data[col]
elif '.' in col : elif "." in col:
cols = col.split('.') cols = col.split(".")
subsource = entry subsource = entry
for sub in cols: for sub in cols:
dCol = subsource.get(sub, None) dCol = subsource.get(sub, None)
@@ -645,22 +702,28 @@ class ElasticHelper():
data[renameFileds[col]] = dCol data[renameFileds[col]] = dCol
del data[col] del data[col]
bulk_data.append({ bulk_data.append({"_id": eid, "_source": data})
'_id': eid,
'_source' : data
})
# انتقال دسته جمعی کدها به الاستیک # انتقال دسته جمعی کدها به الاستیک
if len(bulk_data) >= bulk_update_size: if len(bulk_data) >= bulk_update_size:
total_count += len(bulk_data) total_count += len(bulk_data)
print('=' * 5, ' update bulk --> ' , 'total='+ str(total_count) , str(count)) print(
"=" * 5,
" update bulk --> ",
"total=" + str(total_count),
str(count),
)
self.importBulkList(bulk_data, index_name_i) self.importBulkList(bulk_data, index_name_i)
bulk_data = [] bulk_data = []
if len(bulk_data) >= 0: if len(bulk_data) >= 0:
total_count += len(bulk_data) total_count += len(bulk_data)
print('=' * 5, ' update bulk --> ' , 'total='+ str(total_count) , str(count)) print(
"=" * 5,
" update bulk --> ",
"total=" + str(total_count),
str(count),
)
self.importBulkList(bulk_data, index_name_i) self.importBulkList(bulk_data, index_name_i)
bulk_data = [] bulk_data = []
@@ -670,7 +733,6 @@ class ElasticHelper():
# save_error(id, e) # save_error(id, e)
def moveCustomFileds(self, index_name_i, index_name_o, fields=[], renameFileds={}): def moveCustomFileds(self, index_name_i, index_name_o, fields=[], renameFileds={}):
try: try:
body = {} body = {}
@@ -690,14 +752,17 @@ class ElasticHelper():
eid = id eid = id
if (count % 100) == 0: if (count % 100) == 0:
print("%s -> %.2f " % (id , (count / self.total) if self.total > 0 else 0)) print(
"%s -> %.2f "
% (id, (count / self.total) if self.total > 0 else 0)
)
data_filled = False data_filled = False
data = {} data = {}
for col in fields: for col in fields:
if '.' in col : if "." in col:
cols = col.split('.') cols = col.split(".")
subsource = entry subsource = entry
for sub in cols: for sub in cols:
dCol = subsource.get(sub, None) dCol = subsource.get(sub, None)
@@ -760,7 +825,6 @@ class ElasticHelper():
print(e) print(e)
# save_error(id, e) # save_error(id, e)
def deleteByQueryIndex(self, index_name_i, body): def deleteByQueryIndex(self, index_name_i, body):
## sample ## sample
# body = { # body = {
@@ -788,4 +852,3 @@ class ElasticHelper():
except Exception as e: except Exception as e:
print(e) print(e)
# save_error(id, e) # save_error(id, e)
+25 -20
View File
@@ -5,7 +5,6 @@
"sub_type": { "sub_type": {
"type": "keyword" "type": "keyword"
}, },
"id": { "id": {
"type": "keyword" "type": "keyword"
}, },
@@ -21,7 +20,6 @@
"old_meet_id": { "old_meet_id": {
"type": "integer" "type": "integer"
}, },
"title": { "title": {
"type": "text", "type": "text",
"fields": { "fields": {
@@ -34,13 +32,21 @@
"meet_no": { "meet_no": {
"type": "integer" "type": "integer"
}, },
"author": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"term_info": { "term_info": {
"properties": { "properties": {
"id": { "id": {
"type": "keyword" "type": "keyword"
}, },
"format": { "sub_type": {
"type": "keyword" "type": "keyword"
}, },
"author": { "author": {
@@ -63,7 +69,6 @@
} }
} }
}, },
"subtitle": { "subtitle": {
"type": "text", "type": "text",
"fields": { "fields": {
@@ -73,7 +78,6 @@
} }
} }
}, },
"subjects": { "subjects": {
"properties": { "properties": {
"id": { "id": {
@@ -99,7 +103,6 @@
} }
} }
}, },
"tags": { "tags": {
"type": "text", "type": "text",
"fields": { "fields": {
@@ -127,14 +130,12 @@
} }
} }
}, },
"sanad_year": { "sanad_year": {
"type": "integer" "type": "integer"
}, },
"sanad_date": { "sanad_date": {
"type": "date" "type": "date"
}, },
"amplify": { "amplify": {
"type": "text" "type": "text"
}, },
@@ -150,15 +151,12 @@
"address": { "address": {
"type": "text" "type": "text"
}, },
"audience": { "audience": {
"type": "text" "type": "text"
}, },
"attendees": { "attendees": {
"type": "text" "type": "text"
}, },
"report_info": { "report_info": {
"properties": { "properties": {
"film_count": { "film_count": {
@@ -173,15 +171,23 @@
"file_count": { "file_count": {
"type": "integer" "type": "integer"
}, },
"is_address": {"type": "integer"}, "is_address": {
"is_mindex": {"type": "integer"}, "type": "integer"
"is_mintro": {"type": "integer"}, },
"is_sanad_data1": {"type": "integer"}, "is_mindex": {
"is_sanad_data2": {"type": "integer"} "type": "integer"
},
"is_mintro": {
"type": "integer"
},
"is_sanad_data1": {
"type": "integer"
},
"is_sanad_data2": {
"type": "integer"
}
} }
}, },
"mindex": { "mindex": {
"type": "text", "type": "text",
"fields": { "fields": {
@@ -251,7 +257,6 @@
} }
} }
}, },
"completion": { "completion": {
"type": "completion", "type": "completion",
"analyzer": "simple", "analyzer": "simple",
+14 -9
View File
@@ -5,7 +5,6 @@
"sub_type": { "sub_type": {
"type": "keyword" "type": "keyword"
}, },
"id": { "id": {
"type": "keyword" "type": "keyword"
}, },
@@ -41,7 +40,6 @@
} }
} }
}, },
"permit_tags": { "permit_tags": {
"type": "keyword" "type": "keyword"
}, },
@@ -59,19 +57,26 @@
}, },
"file_links": { "file_links": {
"properties": { "properties": {
"title": {"type": "keyword"}, "title": {
"link": {"type": "text"}, "type": "keyword"
"type": {"type": "text"}, },
"description": {"type": "text"} "link": {
"type": "text"
},
"type": {
"type": "text"
},
"description": {
"type": "text"
}
} }
}, },
"meet_info": { "meet_info": {
"properties": { "properties": {
"id": { "id": {
"type": "keyword" "type": "keyword"
}, },
"format": { "sub_type": {
"type": "keyword" "type": "keyword"
}, },
"author": { "author": {
@@ -99,7 +104,7 @@
"id": { "id": {
"type": "keyword" "type": "keyword"
}, },
"format": { "sub_type": {
"type": "keyword" "type": "keyword"
}, },
"author": { "author": {
+7 -10
View File
@@ -2,6 +2,12 @@
"id": { "id": {
"type": "keyword" "type": "keyword"
}, },
"main_type": {
"type": "keyword"
},
"sub_type": {
"type": "keyword"
},
"title": { "title": {
"type": "text", "type": "text",
"fields": { "fields": {
@@ -43,10 +49,6 @@
} }
} }
}, },
"main_type": {
"type": "keyword"
},
"begin_date": { "begin_date": {
"type": "date" "type": "date"
}, },
@@ -56,7 +58,6 @@
"begin_year": { "begin_year": {
"type": "integer" "type": "integer"
}, },
"tags": { "tags": {
"type": "text", "type": "text",
"fields": { "fields": {
@@ -74,9 +75,5 @@
"ignore_above": 256 "ignore_above": 256
} }
} }
}, }
"format": {
"type": "keyword"
},
} }
+9
View File
@@ -0,0 +1,9 @@
from elastic_helper import ElasticHelper
es_helper = ElasticHelper(
es_url="http://127.0.0.1:6900",
es_user="elastic",
# es_pass="",
# path_mappings = ""
)