first commit
This commit is contained in:
+288
-27
@@ -4,6 +4,8 @@ import os
|
||||
import json
|
||||
from time import sleep
|
||||
from elasticsearch import Elasticsearch, helpers
|
||||
from pathlib import Path
|
||||
import orjson
|
||||
|
||||
|
||||
class ElasticHelper:
|
||||
@@ -91,7 +93,6 @@ class ElasticHelper:
|
||||
res = self.es.exists(index=index_name, id=id)
|
||||
return res
|
||||
|
||||
|
||||
def update_index_doc(self, is_update_state, index_name_o, eid, data):
|
||||
"""
|
||||
نوع ورودی:
|
||||
@@ -103,7 +104,7 @@ class ElasticHelper:
|
||||
عملیات:
|
||||
- اگر 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})
|
||||
@@ -135,6 +136,7 @@ class ElasticHelper:
|
||||
fields=[],
|
||||
mode="normal",
|
||||
collapse_field="",
|
||||
size=1000,
|
||||
):
|
||||
print("*" * 50, " start backup -->", index_name)
|
||||
self.counter = 0
|
||||
@@ -144,7 +146,7 @@ class ElasticHelper:
|
||||
if out_name == "":
|
||||
out = index_name
|
||||
|
||||
s_res = self.es.search(index=index_name, scroll="5m", size=1000, body=body)
|
||||
s_res = self.es.search(index=index_name, scroll="5m", size=size, body=body)
|
||||
self.total = s_res["hits"]["total"]["value"]
|
||||
|
||||
print("start index = %s" % index_name)
|
||||
@@ -270,7 +272,7 @@ class ElasticHelper:
|
||||
if body == {}:
|
||||
s_res = self.es.search(index=index_name, scroll="5m", size=1000)
|
||||
else:
|
||||
if not "size" in body :
|
||||
if not "size" in body:
|
||||
body["size"] = 1000
|
||||
s_res = self.es.search(index=index_name, scroll="5m", body=body)
|
||||
self.total = s_res["hits"]["total"]["value"]
|
||||
@@ -349,7 +351,13 @@ class ElasticHelper:
|
||||
# - دادهها را از فایل ZIP به Elasticsearch بازیابی میکند
|
||||
# -----------------------------end----------------------------
|
||||
def restorFileToElastic(
|
||||
self, path_back, index_name, app_key="", queryDelete=True, map_name="", mapping_file_path = ""
|
||||
self,
|
||||
path_back,
|
||||
index_name,
|
||||
app_key="",
|
||||
queryDelete=True,
|
||||
map_name="",
|
||||
mapping_file_path="",
|
||||
):
|
||||
if not os.path.exists(path_back):
|
||||
print(" **** error *** path not exist: ", path_back)
|
||||
@@ -369,7 +377,13 @@ class ElasticHelper:
|
||||
self.zipFileToElastic(file_path, index_name)
|
||||
|
||||
def restorFileToElastic2(
|
||||
self, path_file, index_name, app_key="", queryDelete=True, map_name="", mapping_file_path = ""
|
||||
self,
|
||||
path_file,
|
||||
index_name,
|
||||
app_key="",
|
||||
queryDelete=True,
|
||||
map_name="",
|
||||
mapping_file_path="",
|
||||
):
|
||||
if not os.path.exists(path_file):
|
||||
print(" **** error *** path not exist: ", path_file)
|
||||
@@ -526,9 +540,9 @@ class ElasticHelper:
|
||||
# - فایل مپینگ را خوانده و اندیس را ایجاد میکند
|
||||
# - در صورت عدم یافت فایل مپینگ، خطا نمایش داده میشود
|
||||
# -----------------------------end----------------------------
|
||||
def createIndex(self, index_name, app_key="", map_name="", mapping_file_path = ""):
|
||||
|
||||
if not mapping_file_path :
|
||||
def createIndex(self, index_name, app_key="", map_name="", mapping_file_path=""):
|
||||
|
||||
if not mapping_file_path:
|
||||
path_base = self.path_mappings
|
||||
path_mapping1 = path_base + "general/"
|
||||
if app_key == "":
|
||||
@@ -598,8 +612,8 @@ class ElasticHelper:
|
||||
"doc": item["_source"],
|
||||
}
|
||||
)
|
||||
|
||||
if streem_state :
|
||||
|
||||
if streem_state:
|
||||
### /// برای مواردی که نیاز هست خطا فهمیده شود
|
||||
for ok, result in helpers.streaming_bulk(
|
||||
self.es,
|
||||
@@ -608,9 +622,9 @@ class ElasticHelper:
|
||||
raise_on_exception=False,
|
||||
):
|
||||
if not ok:
|
||||
print("Error:", result)
|
||||
|
||||
else :
|
||||
print("Error:", result)
|
||||
|
||||
else:
|
||||
helpers.bulk(
|
||||
self.es,
|
||||
actions,
|
||||
@@ -638,7 +652,7 @@ class ElasticHelper:
|
||||
stats_only = True
|
||||
yield_ok = False
|
||||
|
||||
actions=[]
|
||||
actions = []
|
||||
for item in listData:
|
||||
actions.append(
|
||||
{
|
||||
@@ -648,8 +662,8 @@ class ElasticHelper:
|
||||
"_source": item["_source"],
|
||||
}
|
||||
)
|
||||
|
||||
if streem_state :
|
||||
|
||||
if streem_state:
|
||||
### /// برای مواردی که نیاز هست خطا فهمیده شود
|
||||
for ok, result in helpers.streaming_bulk(
|
||||
self.es,
|
||||
@@ -658,9 +672,9 @@ class ElasticHelper:
|
||||
raise_on_exception=False,
|
||||
):
|
||||
if not ok:
|
||||
print("Error:", result)
|
||||
|
||||
else :
|
||||
print("Error:", result)
|
||||
|
||||
else:
|
||||
helpers.bulk(
|
||||
self.es,
|
||||
actions,
|
||||
@@ -681,7 +695,9 @@ class ElasticHelper:
|
||||
# - دادهها را به صورت bulk وارد میکند
|
||||
# - از helpers.bulk Elasticsearch استفاده میکند
|
||||
# -----------------------------end----------------------------
|
||||
def importJsonDataToElastic(self, jsonData, index_name, fields=[], streem_state = False):
|
||||
def importJsonDataToElastic(
|
||||
self, jsonData, index_name, fields=[], streem_state=False
|
||||
):
|
||||
chunk_size = 100000
|
||||
raise_on_error = False
|
||||
raise_on_exception = False
|
||||
@@ -707,7 +723,7 @@ class ElasticHelper:
|
||||
"_source": source,
|
||||
}
|
||||
)
|
||||
if streem_state :
|
||||
if streem_state:
|
||||
### /// برای مواردی که نیاز هست خطا فهمیده شود
|
||||
for ok, result in helpers.streaming_bulk(
|
||||
self.es,
|
||||
@@ -716,9 +732,9 @@ class ElasticHelper:
|
||||
raise_on_exception=False,
|
||||
):
|
||||
if not ok:
|
||||
print("Error:", result)
|
||||
|
||||
else :
|
||||
print("Error:", result)
|
||||
|
||||
else:
|
||||
success, errors = helpers.bulk(
|
||||
self.es,
|
||||
actions,
|
||||
@@ -729,7 +745,6 @@ class ElasticHelper:
|
||||
yield_ok,
|
||||
)
|
||||
return success, errors
|
||||
|
||||
|
||||
# ----------------------------start---------------------------
|
||||
# متد fileToElastic:
|
||||
@@ -899,7 +914,7 @@ class ElasticHelper:
|
||||
scroll=scroll_timeout,
|
||||
**kwargs,
|
||||
size=pagesize,
|
||||
body=body
|
||||
body=body,
|
||||
)
|
||||
else:
|
||||
result = self.es.search(
|
||||
@@ -1176,3 +1191,249 @@ class ElasticHelper:
|
||||
except Exception as e:
|
||||
print(e)
|
||||
# save_error(id, e)
|
||||
|
||||
def save_orjson(self, path, data):
|
||||
"""
|
||||
تابع برای ذخیره لیست و جیسون با سرعت بالا
|
||||
|
||||
:param path: آدرس خروجی با پسوند json
|
||||
:param data: داده خروجی برای ذخیره
|
||||
"""
|
||||
with open(path, "wb") as f:
|
||||
f.write(
|
||||
orjson.dumps(data, option=orjson.OPT_INDENT_2 | orjson.OPT_NON_STR_KEYS)
|
||||
)
|
||||
|
||||
def load_orjson(self, path: str | Path):
|
||||
"""
|
||||
تابع برای بارگزاری جیسون با نهایت سرعت
|
||||
path: آدرس کامل فایل ورودی
|
||||
"""
|
||||
path = Path(path)
|
||||
with path.open("rb") as f: # باید باینری باز بشه برای orjson
|
||||
return orjson.loads(f.read())
|
||||
|
||||
def backup_entire_index(
|
||||
self,
|
||||
index_name: str,
|
||||
output_dir: str | Path,
|
||||
batch_size: int = 1000,
|
||||
):
|
||||
"""Backup کامل Elasticsearch index.
|
||||
شامل:
|
||||
- _index
|
||||
- _id
|
||||
- _score
|
||||
- _routing
|
||||
- _version
|
||||
- _seq_no
|
||||
- _primary_term
|
||||
- کل _source
|
||||
- تمام dense_vector ها
|
||||
- سایر fields
|
||||
نکته:
|
||||
dense_vector هایی که به دلیل
|
||||
index.mapping.exclude_source_vectors
|
||||
از _source حذف شدهاند نیز از طریق fields
|
||||
بازیابی میشوند.
|
||||
Parameters
|
||||
----------
|
||||
es:
|
||||
Elasticsearch client
|
||||
index_name:
|
||||
نام index
|
||||
output_dir:
|
||||
مسیر فایل JSON خروجی
|
||||
batch_size:
|
||||
تعداد document در هر batch
|
||||
"""
|
||||
|
||||
output_dir = Path(output_dir)
|
||||
output_dir.parent.mkdir(
|
||||
parents=True,
|
||||
exist_ok=True,
|
||||
)
|
||||
|
||||
def find_vector_fields(
|
||||
properties,
|
||||
prefix="",
|
||||
):
|
||||
if not properties:
|
||||
return
|
||||
|
||||
for field_name, field_mapping in properties.items():
|
||||
|
||||
full_name = f"{prefix}.{field_name}" if prefix else field_name
|
||||
|
||||
if field_mapping.get("type") == "dense_vector":
|
||||
vector_fields.append(full_name)
|
||||
|
||||
nested_properties = field_mapping.get("properties")
|
||||
|
||||
if nested_properties:
|
||||
find_vector_fields(
|
||||
nested_properties,
|
||||
full_name,
|
||||
)
|
||||
|
||||
print("=" * 70)
|
||||
print(f"BACKUP START")
|
||||
print(f"Index : {index_name}")
|
||||
print(f"Output : {output_dir}")
|
||||
print("=" * 70)
|
||||
|
||||
total = self.es.count(index=index_name)["count"] # تعداد کل documentها
|
||||
print(f"Total documents: {total:,}")
|
||||
|
||||
if total == 0:
|
||||
print("Index is empty.")
|
||||
return
|
||||
|
||||
################### پیدا کردن تمام dense_vector ها از mapping
|
||||
mapping_response = self.es.indices.get_mapping(index=index_name)
|
||||
mapping = mapping_response[index_name]["mappings"]
|
||||
vector_fields = []
|
||||
|
||||
find_vector_fields(mapping.get("properties", {}))
|
||||
print()
|
||||
if vector_fields:
|
||||
print("Dense vector fields:")
|
||||
for field in vector_fields:
|
||||
print(f" - {field}")
|
||||
else:
|
||||
print("Dense vector fields: None")
|
||||
|
||||
search_kwargs = {
|
||||
"index": index_name,
|
||||
"size": 1000,
|
||||
"query": {"match_all": {}},
|
||||
"sort": [{"_shard_doc": "asc"}],
|
||||
}
|
||||
|
||||
if vector_fields:
|
||||
search_kwargs["fields"] = vector_fields
|
||||
|
||||
######################## Backup
|
||||
documents = []
|
||||
counter = 1
|
||||
processed = 0
|
||||
search_after = None
|
||||
|
||||
while True:
|
||||
|
||||
if search_after is not None:
|
||||
search_kwargs["search_after"] = search_after
|
||||
response = self.es.search(**search_kwargs)
|
||||
hits = response["hits"]["hits"]
|
||||
if not hits:
|
||||
break
|
||||
for hit in hits:
|
||||
document = {}
|
||||
|
||||
for key in (
|
||||
"_index",
|
||||
"_id",
|
||||
"_score",
|
||||
"_routing",
|
||||
"_version",
|
||||
"_seq_no",
|
||||
"_primary_term",
|
||||
):
|
||||
if key in hit:
|
||||
document[key] = hit[key]
|
||||
|
||||
source = hit.get(
|
||||
"_source",
|
||||
{},
|
||||
)
|
||||
|
||||
if source is None:
|
||||
source = {}
|
||||
else:
|
||||
source = dict(source)
|
||||
|
||||
fields = hit.get(
|
||||
"fields",
|
||||
{},
|
||||
)
|
||||
|
||||
for vector_field in vector_fields:
|
||||
|
||||
vector = fields.get(vector_field)
|
||||
|
||||
if vector is None:
|
||||
continue
|
||||
if (
|
||||
isinstance(vector, list)
|
||||
and len(vector) == 1
|
||||
and isinstance(vector[0], list)
|
||||
):
|
||||
vector = vector[0]
|
||||
|
||||
parts = vector_field.split(".")
|
||||
target = source
|
||||
for part in parts[:-1]:
|
||||
if not isinstance(
|
||||
target.get(part),
|
||||
dict,
|
||||
):
|
||||
target[part] = {}
|
||||
target = target[part]
|
||||
target[parts[-1]] = vector
|
||||
document["_source"] = source
|
||||
other_fields = {
|
||||
key: value
|
||||
for key, value in fields.items()
|
||||
if key not in vector_fields
|
||||
}
|
||||
if other_fields:
|
||||
document["fields"] = other_fields
|
||||
documents.append(document)
|
||||
processed += 1
|
||||
|
||||
if len(documents) >= batch_size:
|
||||
percent = processed / total * 100
|
||||
print(
|
||||
f"\rProgress: " f"{processed:,}/{total:,} " f"({percent:.2f}%)",
|
||||
end="",
|
||||
flush=True,
|
||||
)
|
||||
self.save_orjson(
|
||||
path=output_dir / f"part_{counter}.json",
|
||||
data=documents,
|
||||
)
|
||||
documents = []
|
||||
counter += 1
|
||||
|
||||
search_after = hits[-1]["sort"]
|
||||
|
||||
print()
|
||||
if len(documents) > 0:
|
||||
self.save_orjson(
|
||||
path=output_dir / f"part_{counter}.json",
|
||||
data=documents,
|
||||
)
|
||||
|
||||
print()
|
||||
print("=" * 70)
|
||||
print("BACKUP FINISHED")
|
||||
print(f"Documents : {processed:,}")
|
||||
print(f"Output : {output_dir}")
|
||||
print("=" * 70)
|
||||
|
||||
if processed != total:
|
||||
print(
|
||||
f"WARNING: "
|
||||
f"expected {total:,} documents, "
|
||||
f"but backed up {processed:,}."
|
||||
)
|
||||
else:
|
||||
print("Document count: OK")
|
||||
|
||||
return {
|
||||
"index": index_name,
|
||||
"total": total,
|
||||
"backed_up": processed,
|
||||
"output": str(output_dir),
|
||||
"vector_fields": vector_fields,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user