opensearch.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. from opensearchpy import OpenSearch
  2. from opensearchpy.helpers import bulk
  3. from typing import Optional
  4. from open_webui.retrieval.vector.main import VectorItem, SearchResult, GetResult
  5. from open_webui.config import (
  6. OPENSEARCH_URI,
  7. OPENSEARCH_SSL,
  8. OPENSEARCH_CERT_VERIFY,
  9. OPENSEARCH_USERNAME,
  10. OPENSEARCH_PASSWORD,
  11. )
  12. class OpenSearchClient:
  13. def __init__(self):
  14. self.index_prefix = "open_webui"
  15. self.client = OpenSearch(
  16. hosts=[OPENSEARCH_URI],
  17. use_ssl=OPENSEARCH_SSL,
  18. verify_certs=OPENSEARCH_CERT_VERIFY,
  19. http_auth=(OPENSEARCH_USERNAME, OPENSEARCH_PASSWORD),
  20. )
  21. def _get_index_name(self, collection_name: str) -> str:
  22. return f"{self.index_prefix}_{collection_name}"
  23. def _result_to_get_result(self, result) -> GetResult:
  24. if not result["hits"]["hits"]:
  25. return None
  26. ids = []
  27. documents = []
  28. metadatas = []
  29. for hit in result["hits"]["hits"]:
  30. ids.append(hit["_id"])
  31. documents.append(hit["_source"].get("text"))
  32. metadatas.append(hit["_source"].get("metadata"))
  33. return GetResult(ids=[ids], documents=[documents], metadatas=[metadatas])
  34. def _result_to_search_result(self, result) -> SearchResult:
  35. if not result["hits"]["hits"]:
  36. return None
  37. ids = []
  38. distances = []
  39. documents = []
  40. metadatas = []
  41. for hit in result["hits"]["hits"]:
  42. ids.append(hit["_id"])
  43. distances.append(hit["_score"])
  44. documents.append(hit["_source"].get("text"))
  45. metadatas.append(hit["_source"].get("metadata"))
  46. return SearchResult(
  47. ids=[ids],
  48. distances=[distances],
  49. documents=[documents],
  50. metadatas=[metadatas],
  51. )
  52. def _create_index(self, collection_name: str, dimension: int):
  53. body = {
  54. "settings": {"index": {"knn": True}},
  55. "mappings": {
  56. "properties": {
  57. "id": {"type": "keyword"},
  58. "vector": {
  59. "type": "knn_vector",
  60. "dimension": dimension, # Adjust based on your vector dimensions
  61. "index": True,
  62. "similarity": "faiss",
  63. "method": {
  64. "name": "hnsw",
  65. "space_type": "innerproduct", # Use inner product to approximate cosine similarity
  66. "engine": "faiss",
  67. "parameters": {
  68. "ef_construction": 128,
  69. "m": 16,
  70. },
  71. },
  72. },
  73. "text": {"type": "text"},
  74. "metadata": {"type": "object"},
  75. }
  76. },
  77. }
  78. self.client.indices.create(
  79. index=self._get_index_name(collection_name), body=body
  80. )
  81. def _create_batches(self, items: list[VectorItem], batch_size=100):
  82. for i in range(0, len(items), batch_size):
  83. yield items[i : i + batch_size]
  84. def has_collection(self, collection_name: str) -> bool:
  85. # has_collection here means has index.
  86. # We are simply adapting to the norms of the other DBs.
  87. return self.client.indices.exists(index=self._get_index_name(collection_name))
  88. def delete_collection(self, collection_name: str):
  89. # delete_collection here means delete index.
  90. # We are simply adapting to the norms of the other DBs.
  91. self.client.indices.delete(index=self._get_index_name(collection_name))
  92. def search(
  93. self, collection_name: str, vectors: list[list[float | int]], limit: int
  94. ) -> Optional[SearchResult]:
  95. try:
  96. if not self.has_collection(collection_name):
  97. return None
  98. query = {
  99. "size": limit,
  100. "_source": ["text", "metadata"],
  101. "query": {
  102. "script_score": {
  103. "query": {"match_all": {}},
  104. "script": {
  105. "source": "(cosineSimilarity(params.query_value, doc[params.field]) + 1.0) / 2.0",
  106. "params": {
  107. "field": "vector",
  108. "query_value": vectors[0],
  109. }, # Assuming single query vector
  110. },
  111. }
  112. },
  113. }
  114. result = self.client.search(
  115. index=self._get_index_name(collection_name), body=query
  116. )
  117. return self._result_to_search_result(result)
  118. except Exception as e:
  119. return None
  120. def query(
  121. self, collection_name: str, filter: dict, limit: Optional[int] = None
  122. ) -> Optional[GetResult]:
  123. if not self.has_collection(collection_name):
  124. return None
  125. query_body = {
  126. "query": {"bool": {"filter": []}},
  127. "_source": ["text", "metadata"],
  128. }
  129. for field, value in filter.items():
  130. query_body["query"]["bool"]["filter"].append(
  131. {"match": {"metadata." + str(field): value}}
  132. )
  133. size = limit if limit else 10
  134. try:
  135. result = self.client.search(
  136. index=self._get_index_name(collection_name),
  137. body=query_body,
  138. size=size,
  139. )
  140. return self._result_to_get_result(result)
  141. except Exception as e:
  142. return None
  143. def _create_index_if_not_exists(self, collection_name: str, dimension: int):
  144. if not self.has_collection(collection_name):
  145. self._create_index(collection_name, dimension)
  146. def get(self, collection_name: str) -> Optional[GetResult]:
  147. query = {"query": {"match_all": {}}, "_source": ["text", "metadata"]}
  148. result = self.client.search(
  149. index=self._get_index_name(collection_name), body=query
  150. )
  151. return self._result_to_get_result(result)
  152. def insert(self, collection_name: str, items: list[VectorItem]):
  153. self._create_index_if_not_exists(
  154. collection_name=collection_name, dimension=len(items[0]["vector"])
  155. )
  156. for batch in self._create_batches(items):
  157. actions = [
  158. {
  159. "_op_type": "index",
  160. "_index": self._get_index_name(collection_name),
  161. "_id": item["id"],
  162. "_source": {
  163. "vector": item["vector"],
  164. "text": item["text"],
  165. "metadata": item["metadata"],
  166. },
  167. }
  168. for item in batch
  169. ]
  170. bulk(self.client, actions)
  171. def upsert(self, collection_name: str, items: list[VectorItem]):
  172. self._create_index_if_not_exists(
  173. collection_name=collection_name, dimension=len(items[0]["vector"])
  174. )
  175. for batch in self._create_batches(items):
  176. actions = [
  177. {
  178. "_op_type": "update",
  179. "_index": self._get_index_name(collection_name),
  180. "_id": item["id"],
  181. "doc": {
  182. "vector": item["vector"],
  183. "text": item["text"],
  184. "metadata": item["metadata"],
  185. },
  186. "doc_as_upsert": True,
  187. }
  188. for item in batch
  189. ]
  190. bulk(self.client, actions)
  191. def delete(
  192. self,
  193. collection_name: str,
  194. ids: Optional[list[str]] = None,
  195. filter: Optional[dict] = None,
  196. ):
  197. if ids:
  198. actions = [
  199. {
  200. "_op_type": "delete",
  201. "_index": self._get_index_name(collection_name),
  202. "_id": id,
  203. }
  204. for id in ids
  205. ]
  206. bulk(self.client, actions)
  207. elif filter:
  208. query_body = {
  209. "query": {"bool": {"filter": []}},
  210. }
  211. for field, value in filter.items():
  212. query_body["query"]["bool"]["filter"].append(
  213. {"match": {"metadata." + str(field): value}}
  214. )
  215. self.client.delete_by_query(
  216. index=self._get_index_name(collection_name), body=query_body
  217. )
  218. def reset(self):
  219. indices = self.client.indices.get(index=f"{self.index_prefix}_*")
  220. for index in indices:
  221. self.client.indices.delete(index=index)