from dotenv import load_dotenv import os, sys, re from app.common.elastic_helper import ElasticHelper from app.common.data_helper import DataHelper from pydantic import BaseModel from typing import Literal, List, Dict, Any, Optional from pathlib import Path from elasticsearch import helpers from elasticsearch.helpers import scan load_dotenv(dotenv_path=r"D:\init_mahdi\dataParsers\config.env") host = os.getenv("HOST_99") password = os.getenv("PASSWORD_99") print(f"host {host} password {password}") elastic = ElasticHelper(es_url=host, es_pass=password, es_user="elastic") def creat_index( elastic: ElasticHelper, input_path=Path( r"D:\init_mahdi\dataParsers\data\mj_qa_group_25315.json" ), index_name="majles_mj_qa_context", batch_size=1000, ): """ Update existing Elasticsearch documents with embeddings. Each JSON file must contain: { "id": "...", "emb": [...] } The document with the corresponding _id must already exist in Elasticsearch. """ actions = [] total = 0 success = 0 failed = 0 print("=" * 80) print("START BULK EMBEDDING UPDATE") print(f"Index : {index_name}") print(f"Input path : {input_path}") print(f"Batch size : {batch_size}") print("=" * 80) in_data = DataHelper.load_orjson(input_path) # in_data = list(input_path.rglob("*.json")) print(f"in_data {len(in_data)}") ############################################################ query = { "_source": ["id"], "query": { "bool": { "filter": [{"term": {"version_key": "base_v3"}}], "must": [{"exists": {"field": "owl"}}], } }, } process_ids = set( hit["_id"] for hit in scan( elastic.es, # اگر نام کلاینت داخل ElasticHelper چیز دیگری است، آن را جایگزین کنید # index="majles_mj_qa_rule", index="majles_mj_qa_context", query=query, size=1000, ) ) print(f"process_ids {len(process_ids)} => ") # print(f"process_ids {len(process_ids)} => {list(process_ids)[1]}") ############################################################ for data in in_data: try: # data = DataHelper.load_orjson(j_path) doc_id = data["_id"] # embedding = data["embed"] owl = data["_source"]["owl"] if doc_id in process_ids: # print(f"doc_id {doc_id}") continue # doc_id = re.sub(r"(_v3)(\d+)$", r"\1-\2", data["id"]) # print(f"doc_id {doc_id}") # return action = { "_op_type": "update", "_index": index_name, "_id": doc_id, "doc": {"owl": owl}, } actions.append(action) total += 1 # Send batch if len(actions) >= batch_size: for ok, result in helpers.streaming_bulk( elastic.es, actions, chunk_size=batch_size, raise_on_error=False, raise_on_exception=False, ): if ok: success += 1 else: failed += 1 print("ERROR:", result) print( f"processed={total:,} | " f"success={success:,} | " f"failed={failed:,}" ) actions.clear() except Exception as e: failed += 1 print(f" {type(e).__name__}: {e}") # Remaining documents if actions: for ok, result in helpers.streaming_bulk( elastic.es, actions, chunk_size=batch_size, raise_on_error=False, raise_on_exception=False, ): if ok: success += 1 else: failed += 1 print("ERROR:", result) print() print("=" * 80) print("BULK UPDATE FINISHED") print(f"Total : {total:,}") print(f"Success: {success:,}") print(f"Failed : {failed:,}") print("=" * 80) creat_index(elastic=elastic) # cd D:\init_mahdi\dataParsers\ # python -m app.put_owl_data