Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

infinity_conn.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. import logging
  2. import os
  3. import re
  4. import json
  5. import time
  6. import infinity
  7. from infinity.common import ConflictType, InfinityException, SortType
  8. from infinity.index import IndexInfo, IndexType
  9. from infinity.connection_pool import ConnectionPool
  10. from infinity.errors import ErrorCode
  11. from rag import settings
  12. from rag.utils import singleton
  13. import polars as pl
  14. from polars.series.series import Series
  15. from api.utils.file_utils import get_project_base_directory
  16. from rag.utils.doc_store_conn import (
  17. DocStoreConnection,
  18. MatchExpr,
  19. MatchTextExpr,
  20. MatchDenseExpr,
  21. FusionExpr,
  22. OrderByExpr,
  23. )
  24. def equivalent_condition_to_str(condition: dict) -> str:
  25. assert "_id" not in condition
  26. cond = list()
  27. for k, v in condition.items():
  28. if not isinstance(k, str) or not v:
  29. continue
  30. if isinstance(v, list):
  31. inCond = list()
  32. for item in v:
  33. if isinstance(item, str):
  34. inCond.append(f"'{item}'")
  35. else:
  36. inCond.append(str(item))
  37. if inCond:
  38. strInCond = ", ".join(inCond)
  39. strInCond = f"{k} IN ({strInCond})"
  40. cond.append(strInCond)
  41. elif isinstance(v, str):
  42. cond.append(f"{k}='{v}'")
  43. else:
  44. cond.append(f"{k}={str(v)}")
  45. return " AND ".join(cond)
  46. def concat_dataframes(df_list: list[pl.DataFrame], selectFields: list[str]) -> pl.DataFrame:
  47. """
  48. Concatenate multiple dataframes into one.
  49. """
  50. if df_list:
  51. return pl.concat(df_list)
  52. schema = dict()
  53. for fieldnm in selectFields:
  54. schema[fieldnm] = str
  55. return pl.DataFrame(schema=schema)
  56. @singleton
  57. class InfinityConnection(DocStoreConnection):
  58. def __init__(self):
  59. self.dbName = settings.INFINITY.get("db_name", "default_db")
  60. infinity_uri = settings.INFINITY["uri"]
  61. if ":" in infinity_uri:
  62. host, port = infinity_uri.split(":")
  63. infinity_uri = infinity.common.NetworkAddress(host, int(port))
  64. self.connPool = None
  65. logging.info(f"Use Infinity {infinity_uri} as the doc engine.")
  66. for _ in range(24):
  67. try:
  68. connPool = ConnectionPool(infinity_uri)
  69. inf_conn = connPool.get_conn()
  70. res = inf_conn.show_current_node()
  71. connPool.release_conn(inf_conn)
  72. self.connPool = connPool
  73. if res.error_code == ErrorCode.OK and res.server_status=="started":
  74. break
  75. logging.warn(f"Infinity status: {res.server_status}. Waiting Infinity {infinity_uri} to be healthy.")
  76. time.sleep(5)
  77. except Exception as e:
  78. logging.warning(f"{str(e)}. Waiting Infinity {infinity_uri} to be healthy.")
  79. time.sleep(5)
  80. if self.connPool is None:
  81. msg = f"Infinity {infinity_uri} didn't become healthy in 120s."
  82. logging.error(msg)
  83. raise Exception(msg)
  84. logging.info(f"Infinity {infinity_uri} is healthy.")
  85. """
  86. Database operations
  87. """
  88. def dbType(self) -> str:
  89. return "infinity"
  90. def health(self) -> dict:
  91. """
  92. Return the health status of the database.
  93. TODO: Infinity-sdk provides health() to wrap `show global variables` and `show tables`
  94. """
  95. inf_conn = self.connPool.get_conn()
  96. res = inf_conn.show_current_node()
  97. self.connPool.release_conn(inf_conn)
  98. res2 = {
  99. "type": "infinity",
  100. "status": "green" if res.error_code == 0 and res.server_status == "started" else "red",
  101. "error": res.error_msg,
  102. }
  103. return res2
  104. """
  105. Table operations
  106. """
  107. def createIdx(self, indexName: str, knowledgebaseId: str, vectorSize: int):
  108. table_name = f"{indexName}_{knowledgebaseId}"
  109. inf_conn = self.connPool.get_conn()
  110. inf_db = inf_conn.create_database(self.dbName, ConflictType.Ignore)
  111. fp_mapping = os.path.join(
  112. get_project_base_directory(), "conf", "infinity_mapping.json"
  113. )
  114. if not os.path.exists(fp_mapping):
  115. raise Exception(f"Mapping file not found at {fp_mapping}")
  116. schema = json.load(open(fp_mapping))
  117. vector_name = f"q_{vectorSize}_vec"
  118. schema[vector_name] = {"type": f"vector,{vectorSize},float"}
  119. inf_table = inf_db.create_table(
  120. table_name,
  121. schema,
  122. ConflictType.Ignore,
  123. )
  124. inf_table.create_index(
  125. "q_vec_idx",
  126. IndexInfo(
  127. vector_name,
  128. IndexType.Hnsw,
  129. {
  130. "M": "16",
  131. "ef_construction": "50",
  132. "metric": "cosine",
  133. "encode": "lvq",
  134. },
  135. ),
  136. ConflictType.Ignore,
  137. )
  138. text_suffix = ["_tks", "_ltks", "_kwd"]
  139. for field_name, field_info in schema.items():
  140. if field_info["type"] != "varchar":
  141. continue
  142. for suffix in text_suffix:
  143. if field_name.endswith(suffix):
  144. inf_table.create_index(
  145. f"text_idx_{field_name}",
  146. IndexInfo(
  147. field_name, IndexType.FullText, {"ANALYZER": "standard"}
  148. ),
  149. ConflictType.Ignore,
  150. )
  151. break
  152. self.connPool.release_conn(inf_conn)
  153. logging.info(
  154. f"INFINITY created table {table_name}, vector size {vectorSize}"
  155. )
  156. def deleteIdx(self, indexName: str, knowledgebaseId: str):
  157. table_name = f"{indexName}_{knowledgebaseId}"
  158. inf_conn = self.connPool.get_conn()
  159. db_instance = inf_conn.get_database(self.dbName)
  160. db_instance.drop_table(table_name, ConflictType.Ignore)
  161. self.connPool.release_conn(inf_conn)
  162. logging.info(f"INFINITY dropped table {table_name}")
  163. def indexExist(self, indexName: str, knowledgebaseId: str) -> bool:
  164. table_name = f"{indexName}_{knowledgebaseId}"
  165. try:
  166. inf_conn = self.connPool.get_conn()
  167. db_instance = inf_conn.get_database(self.dbName)
  168. _ = db_instance.get_table(table_name)
  169. self.connPool.release_conn(inf_conn)
  170. return True
  171. except Exception as e:
  172. logging.warning(f"INFINITY indexExist {str(e)}")
  173. return False
  174. """
  175. CRUD operations
  176. """
  177. def search(
  178. self,
  179. selectFields: list[str],
  180. highlightFields: list[str],
  181. condition: dict,
  182. matchExprs: list[MatchExpr],
  183. orderBy: OrderByExpr,
  184. offset: int,
  185. limit: int,
  186. indexNames: str | list[str],
  187. knowledgebaseIds: list[str],
  188. ) -> list[dict] | pl.DataFrame:
  189. """
  190. TODO: Infinity doesn't provide highlight
  191. """
  192. if isinstance(indexNames, str):
  193. indexNames = indexNames.split(",")
  194. assert isinstance(indexNames, list) and len(indexNames) > 0
  195. inf_conn = self.connPool.get_conn()
  196. db_instance = inf_conn.get_database(self.dbName)
  197. df_list = list()
  198. table_list = list()
  199. if "id" not in selectFields:
  200. selectFields.append("id")
  201. # Prepare expressions common to all tables
  202. filter_cond = ""
  203. filter_fulltext = ""
  204. if condition:
  205. filter_cond = equivalent_condition_to_str(condition)
  206. for matchExpr in matchExprs:
  207. if isinstance(matchExpr, MatchTextExpr):
  208. if len(filter_cond) != 0 and "filter" not in matchExpr.extra_options:
  209. matchExpr.extra_options.update({"filter": filter_cond})
  210. fields = ",".join(matchExpr.fields)
  211. filter_fulltext = (
  212. f"filter_fulltext('{fields}', '{matchExpr.matching_text}')"
  213. )
  214. if len(filter_cond) != 0:
  215. filter_fulltext = f"({filter_cond}) AND {filter_fulltext}"
  216. logging.debug(f"filter_fulltext: {filter_fulltext}")
  217. minimum_should_match = matchExpr.extra_options.get("minimum_should_match", 0.0)
  218. if isinstance(minimum_should_match, float):
  219. str_minimum_should_match = str(int(minimum_should_match * 100)) + "%"
  220. matchExpr.extra_options["minimum_should_match"] = str_minimum_should_match
  221. for k, v in matchExpr.extra_options.items():
  222. if not isinstance(v, str):
  223. matchExpr.extra_options[k] = str(v)
  224. elif isinstance(matchExpr, MatchDenseExpr):
  225. if len(filter_cond) != 0 and "filter" not in matchExpr.extra_options:
  226. matchExpr.extra_options.update({"filter": filter_fulltext})
  227. for k, v in matchExpr.extra_options.items():
  228. if not isinstance(v, str):
  229. matchExpr.extra_options[k] = str(v)
  230. order_by_expr_list = list()
  231. if orderBy.fields:
  232. for order_field in orderBy.fields:
  233. if order_field[1] == 0:
  234. order_by_expr_list.append((order_field[0], SortType.Asc))
  235. else:
  236. order_by_expr_list.append((order_field[0], SortType.Desc))
  237. # Scatter search tables and gather the results
  238. for indexName in indexNames:
  239. for knowledgebaseId in knowledgebaseIds:
  240. table_name = f"{indexName}_{knowledgebaseId}"
  241. try:
  242. table_instance = db_instance.get_table(table_name)
  243. except Exception:
  244. continue
  245. table_list.append(table_name)
  246. builder = table_instance.output(selectFields)
  247. if len(matchExprs) > 0:
  248. for matchExpr in matchExprs:
  249. if isinstance(matchExpr, MatchTextExpr):
  250. fields = ",".join(matchExpr.fields)
  251. builder = builder.match_text(
  252. fields,
  253. matchExpr.matching_text,
  254. matchExpr.topn,
  255. matchExpr.extra_options,
  256. )
  257. elif isinstance(matchExpr, MatchDenseExpr):
  258. builder = builder.match_dense(
  259. matchExpr.vector_column_name,
  260. matchExpr.embedding_data,
  261. matchExpr.embedding_data_type,
  262. matchExpr.distance_type,
  263. matchExpr.topn,
  264. matchExpr.extra_options,
  265. )
  266. elif isinstance(matchExpr, FusionExpr):
  267. builder = builder.fusion(
  268. matchExpr.method, matchExpr.topn, matchExpr.fusion_params
  269. )
  270. else:
  271. if len(filter_cond) > 0:
  272. builder.filter(filter_cond)
  273. if orderBy.fields:
  274. builder.sort(order_by_expr_list)
  275. builder.offset(offset).limit(limit)
  276. kb_res = builder.to_pl()
  277. df_list.append(kb_res)
  278. self.connPool.release_conn(inf_conn)
  279. res = concat_dataframes(df_list, selectFields)
  280. logging.debug("INFINITY search tables: " + str(table_list))
  281. return res
  282. def get(
  283. self, chunkId: str, indexName: str, knowledgebaseIds: list[str]
  284. ) -> dict | None:
  285. inf_conn = self.connPool.get_conn()
  286. db_instance = inf_conn.get_database(self.dbName)
  287. df_list = list()
  288. assert isinstance(knowledgebaseIds, list)
  289. for knowledgebaseId in knowledgebaseIds:
  290. table_name = f"{indexName}_{knowledgebaseId}"
  291. table_instance = db_instance.get_table(table_name)
  292. kb_res = table_instance.output(["*"]).filter(f"id = '{chunkId}'").to_pl()
  293. if len(kb_res) != 0 and kb_res.shape[0] > 0:
  294. df_list.append(kb_res)
  295. self.connPool.release_conn(inf_conn)
  296. res = concat_dataframes(df_list, ["id"])
  297. res_fields = self.getFields(res, res.columns)
  298. return res_fields.get(chunkId, None)
  299. def insert(
  300. self, documents: list[dict], indexName: str, knowledgebaseId: str
  301. ) -> list[str]:
  302. inf_conn = self.connPool.get_conn()
  303. db_instance = inf_conn.get_database(self.dbName)
  304. table_name = f"{indexName}_{knowledgebaseId}"
  305. try:
  306. table_instance = db_instance.get_table(table_name)
  307. except InfinityException as e:
  308. # src/common/status.cppm, kTableNotExist = 3022
  309. if e.error_code != 3022:
  310. raise
  311. vector_size = 0
  312. patt = re.compile(r"q_(?P<vector_size>\d+)_vec")
  313. for k in documents[0].keys():
  314. m = patt.match(k)
  315. if m:
  316. vector_size = int(m.group("vector_size"))
  317. break
  318. if vector_size == 0:
  319. raise ValueError("Cannot infer vector size from documents")
  320. self.createIdx(indexName, knowledgebaseId, vector_size)
  321. table_instance = db_instance.get_table(table_name)
  322. for d in documents:
  323. assert "_id" not in d
  324. assert "id" in d
  325. for k, v in d.items():
  326. if k.endswith("_kwd") and isinstance(v, list):
  327. d[k] = " ".join(v)
  328. ids = ["'{}'".format(d["id"]) for d in documents]
  329. str_ids = ", ".join(ids)
  330. str_filter = f"id IN ({str_ids})"
  331. table_instance.delete(str_filter)
  332. # for doc in documents:
  333. # logging.info(f"insert position_list: {doc['position_list']}")
  334. # logging.info(f"InfinityConnection.insert {json.dumps(documents)}")
  335. table_instance.insert(documents)
  336. self.connPool.release_conn(inf_conn)
  337. logging.debug(f"inserted into {table_name} {str_ids}.")
  338. return []
  339. def update(
  340. self, condition: dict, newValue: dict, indexName: str, knowledgebaseId: str
  341. ) -> bool:
  342. # if 'position_list' in newValue:
  343. # logging.info(f"upsert position_list: {newValue['position_list']}")
  344. inf_conn = self.connPool.get_conn()
  345. db_instance = inf_conn.get_database(self.dbName)
  346. table_name = f"{indexName}_{knowledgebaseId}"
  347. table_instance = db_instance.get_table(table_name)
  348. filter = equivalent_condition_to_str(condition)
  349. for k, v in newValue.items():
  350. if k.endswith("_kwd") and isinstance(v, list):
  351. newValue[k] = " ".join(v)
  352. table_instance.update(filter, newValue)
  353. self.connPool.release_conn(inf_conn)
  354. return True
  355. def delete(self, condition: dict, indexName: str, knowledgebaseId: str) -> int:
  356. inf_conn = self.connPool.get_conn()
  357. db_instance = inf_conn.get_database(self.dbName)
  358. table_name = f"{indexName}_{knowledgebaseId}"
  359. filter = equivalent_condition_to_str(condition)
  360. try:
  361. table_instance = db_instance.get_table(table_name)
  362. except Exception:
  363. logging.warning(
  364. f"Skipped deleting `{filter}` from table {table_name} since the table doesn't exist."
  365. )
  366. return 0
  367. res = table_instance.delete(filter)
  368. self.connPool.release_conn(inf_conn)
  369. return res.deleted_rows
  370. """
  371. Helper functions for search result
  372. """
  373. def getTotal(self, res):
  374. return len(res)
  375. def getChunkIds(self, res):
  376. return list(res["id"])
  377. def getFields(self, res, fields: list[str]) -> list[str, dict]:
  378. res_fields = {}
  379. if not fields:
  380. return {}
  381. num_rows = len(res)
  382. column_id = res["id"]
  383. for i in range(num_rows):
  384. id = column_id[i]
  385. m = {"id": id}
  386. for fieldnm in fields:
  387. if fieldnm not in res:
  388. m[fieldnm] = None
  389. continue
  390. v = res[fieldnm][i]
  391. if isinstance(v, Series):
  392. v = list(v)
  393. elif fieldnm == "important_kwd":
  394. assert isinstance(v, str)
  395. v = v.split()
  396. else:
  397. if not isinstance(v, str):
  398. v = str(v)
  399. # if fieldnm.endswith("_tks"):
  400. # v = rmSpace(v)
  401. m[fieldnm] = v
  402. res_fields[id] = m
  403. return res_fields
  404. def getHighlight(self, res, keywords: list[str], fieldnm: str):
  405. ans = {}
  406. num_rows = len(res)
  407. column_id = res["id"]
  408. for i in range(num_rows):
  409. id = column_id[i]
  410. txt = res[fieldnm][i]
  411. txt = re.sub(r"[\r\n]", " ", txt, flags=re.IGNORECASE | re.MULTILINE)
  412. txts = []
  413. for t in re.split(r"[.?!;\n]", txt):
  414. for w in keywords:
  415. t = re.sub(
  416. r"(^|[ .?/'\"\(\)!,:;-])(%s)([ .?/'\"\(\)!,:;-])"
  417. % re.escape(w),
  418. r"\1<em>\2</em>\3",
  419. t,
  420. flags=re.IGNORECASE | re.MULTILINE,
  421. )
  422. if not re.search(
  423. r"<em>[^<>]+</em>", t, flags=re.IGNORECASE | re.MULTILINE
  424. ):
  425. continue
  426. txts.append(t)
  427. ans[id] = "...".join(txts)
  428. return ans
  429. def getAggregation(self, res, fieldnm: str):
  430. """
  431. TODO: Infinity doesn't provide aggregation
  432. """
  433. return list()
  434. """
  435. SQL
  436. """
  437. def sql(sql: str, fetch_size: int, format: str):
  438. raise NotImplementedError("Not implemented")