Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

es_conn.py 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. #
  2. # Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import logging
  17. import re
  18. import json
  19. import time
  20. import os
  21. import copy
  22. from elasticsearch import Elasticsearch, NotFoundError
  23. from elasticsearch_dsl import UpdateByQuery, Q, Search, Index
  24. from elastic_transport import ConnectionTimeout
  25. from rag import settings
  26. from rag.settings import TAG_FLD, PAGERANK_FLD
  27. from rag.utils import singleton
  28. from api.utils.file_utils import get_project_base_directory
  29. import polars as pl
  30. from rag.utils.doc_store_conn import DocStoreConnection, MatchExpr, OrderByExpr, MatchTextExpr, MatchDenseExpr, \
  31. FusionExpr
  32. from rag.nlp import is_english, rag_tokenizer
  33. ATTEMPT_TIME = 2
  34. logger = logging.getLogger('ragflow.es_conn')
  35. @singleton
  36. class ESConnection(DocStoreConnection):
  37. def __init__(self):
  38. self.info = {}
  39. logger.info(f"Use Elasticsearch {settings.ES['hosts']} as the doc engine.")
  40. for _ in range(ATTEMPT_TIME):
  41. try:
  42. self.es = Elasticsearch(
  43. settings.ES["hosts"].split(","),
  44. basic_auth=(settings.ES["username"], settings.ES[
  45. "password"]) if "username" in settings.ES and "password" in settings.ES else None,
  46. verify_certs=False,
  47. timeout=600
  48. )
  49. if self.es:
  50. self.info = self.es.info()
  51. break
  52. except Exception as e:
  53. logger.warning(f"{str(e)}. Waiting Elasticsearch {settings.ES['hosts']} to be healthy.")
  54. time.sleep(5)
  55. if not self.es.ping():
  56. msg = f"Elasticsearch {settings.ES['hosts']} is unhealthy in 120s."
  57. logger.error(msg)
  58. raise Exception(msg)
  59. v = self.info.get("version", {"number": "8.11.3"})
  60. v = v["number"].split(".")[0]
  61. if int(v) < 8:
  62. msg = f"Elasticsearch version must be greater than or equal to 8, current version: {v}"
  63. logger.error(msg)
  64. raise Exception(msg)
  65. fp_mapping = os.path.join(get_project_base_directory(), "conf", "mapping.json")
  66. if not os.path.exists(fp_mapping):
  67. msg = f"Elasticsearch mapping file not found at {fp_mapping}"
  68. logger.error(msg)
  69. raise Exception(msg)
  70. self.mapping = json.load(open(fp_mapping, "r"))
  71. logger.info(f"Elasticsearch {settings.ES['hosts']} is healthy.")
  72. """
  73. Database operations
  74. """
  75. def dbType(self) -> str:
  76. return "elasticsearch"
  77. def health(self) -> dict:
  78. health_dict = dict(self.es.cluster.health())
  79. health_dict["type"] = "elasticsearch"
  80. return health_dict
  81. """
  82. Table operations
  83. """
  84. def createIdx(self, indexName: str, knowledgebaseId: str, vectorSize: int):
  85. if self.indexExist(indexName, knowledgebaseId):
  86. return True
  87. try:
  88. from elasticsearch.client import IndicesClient
  89. return IndicesClient(self.es).create(index=indexName,
  90. settings=self.mapping["settings"],
  91. mappings=self.mapping["mappings"])
  92. except Exception:
  93. logger.exception("ESConnection.createIndex error %s" % (indexName))
  94. def deleteIdx(self, indexName: str, knowledgebaseId: str):
  95. if len(knowledgebaseId) > 0:
  96. # The index need to be alive after any kb deletion since all kb under this tenant are in one index.
  97. return
  98. try:
  99. self.es.indices.delete(index=indexName, allow_no_indices=True)
  100. except NotFoundError:
  101. pass
  102. except Exception:
  103. logger.exception("ESConnection.deleteIdx error %s" % (indexName))
  104. def indexExist(self, indexName: str, knowledgebaseId: str) -> bool:
  105. s = Index(indexName, self.es)
  106. for i in range(ATTEMPT_TIME):
  107. try:
  108. return s.exists()
  109. except Exception as e:
  110. logger.exception("ESConnection.indexExist got exception")
  111. if str(e).find("Timeout") > 0 or str(e).find("Conflict") > 0:
  112. continue
  113. return False
  114. """
  115. CRUD operations
  116. """
  117. def search(
  118. self, selectFields: list[str],
  119. highlightFields: list[str],
  120. condition: dict,
  121. matchExprs: list[MatchExpr],
  122. orderBy: OrderByExpr,
  123. offset: int,
  124. limit: int,
  125. indexNames: str | list[str],
  126. knowledgebaseIds: list[str],
  127. aggFields: list[str] = [],
  128. rank_feature: dict | None = None
  129. ) -> list[dict] | pl.DataFrame:
  130. """
  131. Refers to https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl.html
  132. """
  133. if isinstance(indexNames, str):
  134. indexNames = indexNames.split(",")
  135. assert isinstance(indexNames, list) and len(indexNames) > 0
  136. assert "_id" not in condition
  137. bqry = Q("bool", must=[])
  138. condition["kb_id"] = knowledgebaseIds
  139. for k, v in condition.items():
  140. if k == "available_int":
  141. if v == 0:
  142. bqry.filter.append(Q("range", available_int={"lt": 1}))
  143. else:
  144. bqry.filter.append(
  145. Q("bool", must_not=Q("range", available_int={"lt": 1})))
  146. continue
  147. if not v:
  148. continue
  149. if isinstance(v, list):
  150. bqry.filter.append(Q("terms", **{k: v}))
  151. elif isinstance(v, str) or isinstance(v, int):
  152. bqry.filter.append(Q("term", **{k: v}))
  153. else:
  154. raise Exception(
  155. f"Condition `{str(k)}={str(v)}` value type is {str(type(v))}, expected to be int, str or list.")
  156. s = Search()
  157. vector_similarity_weight = 0.5
  158. for m in matchExprs:
  159. if isinstance(m, FusionExpr) and m.method == "weighted_sum" and "weights" in m.fusion_params:
  160. assert len(matchExprs) == 3 and isinstance(matchExprs[0], MatchTextExpr) and isinstance(matchExprs[1],
  161. MatchDenseExpr) and isinstance(
  162. matchExprs[2], FusionExpr)
  163. weights = m.fusion_params["weights"]
  164. vector_similarity_weight = float(weights.split(",")[1])
  165. for m in matchExprs:
  166. if isinstance(m, MatchTextExpr):
  167. minimum_should_match = m.extra_options.get("minimum_should_match", 0.0)
  168. if isinstance(minimum_should_match, float):
  169. minimum_should_match = str(int(minimum_should_match * 100)) + "%"
  170. bqry.must.append(Q("query_string", fields=m.fields,
  171. type="best_fields", query=m.matching_text,
  172. minimum_should_match=minimum_should_match,
  173. boost=1))
  174. bqry.boost = 1.0 - vector_similarity_weight
  175. elif isinstance(m, MatchDenseExpr):
  176. assert (bqry is not None)
  177. similarity = 0.0
  178. if "similarity" in m.extra_options:
  179. similarity = m.extra_options["similarity"]
  180. s = s.knn(m.vector_column_name,
  181. m.topn,
  182. m.topn * 2,
  183. query_vector=list(m.embedding_data),
  184. filter=bqry.to_dict(),
  185. similarity=similarity,
  186. )
  187. if bqry and rank_feature:
  188. for fld, sc in rank_feature.items():
  189. if fld != PAGERANK_FLD:
  190. fld = f"{TAG_FLD}.{fld}"
  191. bqry.should.append(Q("rank_feature", field=fld, linear={}, boost=sc))
  192. if bqry:
  193. s = s.query(bqry)
  194. for field in highlightFields:
  195. s = s.highlight(field)
  196. if orderBy:
  197. orders = list()
  198. for field, order in orderBy.fields:
  199. order = "asc" if order == 0 else "desc"
  200. if field in ["page_num_int", "top_int"]:
  201. order_info = {"order": order, "unmapped_type": "float",
  202. "mode": "avg", "numeric_type": "double"}
  203. elif field.endswith("_int") or field.endswith("_flt"):
  204. order_info = {"order": order, "unmapped_type": "float"}
  205. else:
  206. order_info = {"order": order, "unmapped_type": "text"}
  207. orders.append({field: order_info})
  208. s = s.sort(*orders)
  209. for fld in aggFields:
  210. s.aggs.bucket(f'aggs_{fld}', 'terms', field=fld, size=1000000)
  211. if limit > 0:
  212. s = s[offset:offset + limit]
  213. q = s.to_dict()
  214. logger.debug(f"ESConnection.search {str(indexNames)} query: " + json.dumps(q))
  215. for i in range(ATTEMPT_TIME):
  216. try:
  217. res = self.es.search(index=indexNames,
  218. body=q,
  219. timeout="600s",
  220. # search_type="dfs_query_then_fetch",
  221. track_total_hits=True,
  222. _source=True)
  223. if str(res.get("timed_out", "")).lower() == "true":
  224. raise Exception("Es Timeout.")
  225. logger.debug(f"ESConnection.search {str(indexNames)} res: " + str(res))
  226. return res
  227. except Exception as e:
  228. logger.exception(f"ESConnection.search {str(indexNames)} query: " + str(q))
  229. if str(e).find("Timeout") > 0:
  230. continue
  231. raise e
  232. logger.error("ESConnection.search timeout for 3 times!")
  233. raise Exception("ESConnection.search timeout.")
  234. def get(self, chunkId: str, indexName: str, knowledgebaseIds: list[str]) -> dict | None:
  235. for i in range(ATTEMPT_TIME):
  236. try:
  237. res = self.es.get(index=(indexName),
  238. id=chunkId, source=True, )
  239. if str(res.get("timed_out", "")).lower() == "true":
  240. raise Exception("Es Timeout.")
  241. chunk = res["_source"]
  242. chunk["id"] = chunkId
  243. return chunk
  244. except NotFoundError:
  245. return None
  246. except Exception as e:
  247. logger.exception(f"ESConnection.get({chunkId}) got exception")
  248. if str(e).find("Timeout") > 0:
  249. continue
  250. raise e
  251. logger.error("ESConnection.get timeout for 3 times!")
  252. raise Exception("ESConnection.get timeout.")
  253. def insert(self, documents: list[dict], indexName: str, knowledgebaseId: str = None) -> list[str]:
  254. # Refers to https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html
  255. operations = []
  256. for d in documents:
  257. assert "_id" not in d
  258. assert "id" in d
  259. d_copy = copy.deepcopy(d)
  260. meta_id = d_copy.pop("id", "")
  261. operations.append(
  262. {"index": {"_index": indexName, "_id": meta_id}})
  263. operations.append(d_copy)
  264. res = []
  265. for _ in range(ATTEMPT_TIME):
  266. try:
  267. res = []
  268. r = self.es.bulk(index=(indexName), operations=operations,
  269. refresh=False, timeout="60s")
  270. if re.search(r"False", str(r["errors"]), re.IGNORECASE):
  271. return res
  272. for item in r["items"]:
  273. for action in ["create", "delete", "index", "update"]:
  274. if action in item and "error" in item[action]:
  275. res.append(str(item[action]["_id"]) + ":" + str(item[action]["error"]))
  276. return res
  277. except Exception as e:
  278. res.append(str(e))
  279. logger.warning("ESConnection.insert got exception: " + str(e))
  280. res = []
  281. if re.search(r"(Timeout|time out)", str(e), re.IGNORECASE):
  282. res.append(str(e))
  283. time.sleep(3)
  284. continue
  285. return res
  286. def update(self, condition: dict, newValue: dict, indexName: str, knowledgebaseId: str) -> bool:
  287. doc = copy.deepcopy(newValue)
  288. doc.pop("id", None)
  289. if "id" in condition and isinstance(condition["id"], str):
  290. # update specific single document
  291. chunkId = condition["id"]
  292. for i in range(ATTEMPT_TIME):
  293. try:
  294. self.es.update(index=indexName, id=chunkId, doc=doc)
  295. return True
  296. except Exception as e:
  297. logger.exception(
  298. f"ESConnection.update(index={indexName}, id={id}, doc={json.dumps(condition, ensure_ascii=False)}) got exception")
  299. if str(e).find("Timeout") > 0:
  300. continue
  301. return False
  302. # update unspecific maybe-multiple documents
  303. bqry = Q("bool")
  304. for k, v in condition.items():
  305. if not isinstance(k, str) or not v:
  306. continue
  307. if k == "exist":
  308. bqry.filter.append(Q("exists", field=v))
  309. continue
  310. if isinstance(v, list):
  311. bqry.filter.append(Q("terms", **{k: v}))
  312. elif isinstance(v, str) or isinstance(v, int):
  313. bqry.filter.append(Q("term", **{k: v}))
  314. else:
  315. raise Exception(
  316. f"Condition `{str(k)}={str(v)}` value type is {str(type(v))}, expected to be int, str or list.")
  317. scripts = []
  318. params = {}
  319. for k, v in newValue.items():
  320. if k == "remove":
  321. if isinstance(v, str):
  322. scripts.append(f"ctx._source.remove('{v}');")
  323. if isinstance(v, dict):
  324. for kk, vv in v.items():
  325. scripts.append(f"int i=ctx._source.{kk}.indexOf(params.p_{kk});ctx._source.{kk}.remove(i);")
  326. params[f"p_{kk}"] = vv
  327. continue
  328. if k == "add":
  329. if isinstance(v, dict):
  330. for kk, vv in v.items():
  331. scripts.append(f"ctx._source.{kk}.add(params.pp_{kk});")
  332. params[f"pp_{kk}"] = vv.strip()
  333. continue
  334. if (not isinstance(k, str) or not v) and k != "available_int":
  335. continue
  336. if isinstance(v, str):
  337. scripts.append(f"ctx._source.{k} = '{v}'")
  338. elif isinstance(v, int):
  339. scripts.append(f"ctx._source.{k} = {v}")
  340. else:
  341. raise Exception(
  342. f"newValue `{str(k)}={str(v)}` value type is {str(type(v))}, expected to be int, str.")
  343. ubq = UpdateByQuery(
  344. index=indexName).using(
  345. self.es).query(bqry)
  346. ubq = ubq.script(source="".join(scripts), params=params)
  347. ubq = ubq.params(refresh=True)
  348. ubq = ubq.params(slices=5)
  349. ubq = ubq.params(conflicts="proceed")
  350. for _ in range(ATTEMPT_TIME):
  351. try:
  352. _ = ubq.execute()
  353. return True
  354. except Exception as e:
  355. logger.error("ESConnection.update got exception: " + str(e))
  356. if str(e).find("Timeout") > 0 or str(e).find("Conflict") > 0:
  357. continue
  358. return False
  359. def delete(self, condition: dict, indexName: str, knowledgebaseId: str) -> int:
  360. qry = None
  361. assert "_id" not in condition
  362. if "id" in condition:
  363. chunk_ids = condition["id"]
  364. if not isinstance(chunk_ids, list):
  365. chunk_ids = [chunk_ids]
  366. qry = Q("ids", values=chunk_ids)
  367. else:
  368. qry = Q("bool")
  369. for k, v in condition.items():
  370. if isinstance(v, list):
  371. qry.must.append(Q("terms", **{k: v}))
  372. elif isinstance(v, str) or isinstance(v, int):
  373. qry.must.append(Q("term", **{k: v}))
  374. else:
  375. raise Exception("Condition value must be int, str or list.")
  376. logger.debug("ESConnection.delete query: " + json.dumps(qry.to_dict()))
  377. for _ in range(ATTEMPT_TIME):
  378. try:
  379. res = self.es.delete_by_query(
  380. index=indexName,
  381. body=Search().query(qry).to_dict(),
  382. refresh=True)
  383. return res["deleted"]
  384. except Exception as e:
  385. logger.warning("ESConnection.delete got exception: " + str(e))
  386. if re.search(r"(Timeout|time out)", str(e), re.IGNORECASE):
  387. time.sleep(3)
  388. continue
  389. if re.search(r"(not_found)", str(e), re.IGNORECASE):
  390. return 0
  391. return 0
  392. """
  393. Helper functions for search result
  394. """
  395. def getTotal(self, res):
  396. if isinstance(res["hits"]["total"], type({})):
  397. return res["hits"]["total"]["value"]
  398. return res["hits"]["total"]
  399. def getChunkIds(self, res):
  400. return [d["_id"] for d in res["hits"]["hits"]]
  401. def __getSource(self, res):
  402. rr = []
  403. for d in res["hits"]["hits"]:
  404. d["_source"]["id"] = d["_id"]
  405. d["_source"]["_score"] = d["_score"]
  406. rr.append(d["_source"])
  407. return rr
  408. def getFields(self, res, fields: list[str]) -> dict[str, dict]:
  409. res_fields = {}
  410. if not fields:
  411. return {}
  412. for d in self.__getSource(res):
  413. m = {n: d.get(n) for n in fields if d.get(n) is not None}
  414. for n, v in m.items():
  415. if isinstance(v, list):
  416. m[n] = v
  417. continue
  418. if not isinstance(v, str):
  419. m[n] = str(m[n])
  420. # if n.find("tks") > 0:
  421. # m[n] = rmSpace(m[n])
  422. if m:
  423. res_fields[d["id"]] = m
  424. return res_fields
  425. def getHighlight(self, res, keywords: list[str], fieldnm: str):
  426. ans = {}
  427. for d in res["hits"]["hits"]:
  428. hlts = d.get("highlight")
  429. if not hlts:
  430. continue
  431. txt = "...".join([a for a in list(hlts.items())[0][1]])
  432. if not is_english(txt.split()):
  433. ans[d["_id"]] = txt
  434. continue
  435. txt = d["_source"][fieldnm]
  436. txt = re.sub(r"[\r\n]", " ", txt, flags=re.IGNORECASE | re.MULTILINE)
  437. txts = []
  438. for t in re.split(r"[.?!;\n]", txt):
  439. for w in keywords:
  440. t = re.sub(r"(^|[ .?/'\"\(\)!,:;-])(%s)([ .?/'\"\(\)!,:;-])" % re.escape(w), r"\1<em>\2</em>\3", t,
  441. flags=re.IGNORECASE | re.MULTILINE)
  442. if not re.search(r"<em>[^<>]+</em>", t, flags=re.IGNORECASE | re.MULTILINE):
  443. continue
  444. txts.append(t)
  445. ans[d["_id"]] = "...".join(txts) if txts else "...".join([a for a in list(hlts.items())[0][1]])
  446. return ans
  447. def getAggregation(self, res, fieldnm: str):
  448. agg_field = "aggs_" + fieldnm
  449. if "aggregations" not in res or agg_field not in res["aggregations"]:
  450. return list()
  451. bkts = res["aggregations"][agg_field]["buckets"]
  452. return [(b["key"], b["doc_count"]) for b in bkts]
  453. """
  454. SQL
  455. """
  456. def sql(self, sql: str, fetch_size: int, format: str):
  457. logger.debug(f"ESConnection.sql get sql: {sql}")
  458. sql = re.sub(r"[ `]+", " ", sql)
  459. sql = sql.replace("%", "")
  460. replaces = []
  461. for r in re.finditer(r" ([a-z_]+_l?tks)( like | ?= ?)'([^']+)'", sql):
  462. fld, v = r.group(1), r.group(3)
  463. match = " MATCH({}, '{}', 'operator=OR;minimum_should_match=30%') ".format(
  464. fld, rag_tokenizer.fine_grained_tokenize(rag_tokenizer.tokenize(v)))
  465. replaces.append(
  466. ("{}{}'{}'".format(
  467. r.group(1),
  468. r.group(2),
  469. r.group(3)),
  470. match))
  471. for p, r in replaces:
  472. sql = sql.replace(p, r, 1)
  473. logger.debug(f"ESConnection.sql to es: {sql}")
  474. for i in range(ATTEMPT_TIME):
  475. try:
  476. res = self.es.sql.query(body={"query": sql, "fetch_size": fetch_size}, format=format,
  477. request_timeout="2s")
  478. return res
  479. except ConnectionTimeout:
  480. logger.exception("ESConnection.sql timeout")
  481. continue
  482. except Exception:
  483. logger.exception("ESConnection.sql got exception")
  484. return None
  485. logger.error("ESConnection.sql timeout for 3 times!")
  486. return None