Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

infinity_conn.py 17KB

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