opensearch.py 7.2 KB

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