elasticsearch.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. from elasticsearch import Elasticsearch, BadRequestError
  2. from typing import Optional
  3. import ssl
  4. from elasticsearch.helpers import bulk,scan
  5. from open_webui.retrieval.vector.main import VectorItem, SearchResult, GetResult
  6. from open_webui.config import (
  7. ELASTICSEARCH_URL,
  8. ELASTICSEARCH_CA_CERTS,
  9. ELASTICSEARCH_API_KEY,
  10. ELASTICSEARCH_USERNAME,
  11. ELASTICSEARCH_PASSWORD,
  12. ELASTICSEARCH_CLOUD_ID,
  13. SSL_ASSERT_FINGERPRINT
  14. )
  15. class ElasticsearchClient:
  16. """
  17. Important:
  18. in order to reduce the number of indexes and since the embedding vector length is fixed, we avoid creating
  19. an index for each file but store it as a text field, while seperating to different index
  20. baesd on the embedding length.
  21. """
  22. def __init__(self):
  23. self.index_prefix = "open_webui_collections"
  24. self.client = Elasticsearch(
  25. hosts=[ELASTICSEARCH_URL],
  26. ca_certs=ELASTICSEARCH_CA_CERTS,
  27. api_key=ELASTICSEARCH_API_KEY,
  28. cloud_id=ELASTICSEARCH_CLOUD_ID,
  29. basic_auth=(ELASTICSEARCH_USERNAME,ELASTICSEARCH_PASSWORD) if ELASTICSEARCH_USERNAME and ELASTICSEARCH_PASSWORD else None,
  30. ssl_assert_fingerprint=SSL_ASSERT_FINGERPRINT
  31. )
  32. #Status: works
  33. def _get_index_name(self,dimension:int)->str:
  34. return f"{self.index_prefix}_d{str(dimension)}"
  35. #Status: works
  36. def _scan_result_to_get_result(self, result) -> GetResult:
  37. if not result:
  38. return None
  39. ids = []
  40. documents = []
  41. metadatas = []
  42. for hit in result:
  43. ids.append(hit["_id"])
  44. documents.append(hit["_source"].get("text"))
  45. metadatas.append(hit["_source"].get("metadata"))
  46. return GetResult(ids=[ids], documents=[documents], metadatas=[metadatas])
  47. #Status: works
  48. def _result_to_get_result(self, result) -> GetResult:
  49. if not result["hits"]["hits"]:
  50. return None
  51. ids = []
  52. documents = []
  53. metadatas = []
  54. for hit in result["hits"]["hits"]:
  55. ids.append(hit["_id"])
  56. documents.append(hit["_source"].get("text"))
  57. metadatas.append(hit["_source"].get("metadata"))
  58. return GetResult(ids=[ids], documents=[documents], metadatas=[metadatas])
  59. #Status: works
  60. def _result_to_search_result(self, result) -> SearchResult:
  61. ids = []
  62. distances = []
  63. documents = []
  64. metadatas = []
  65. for hit in result["hits"]["hits"]:
  66. ids.append(hit["_id"])
  67. distances.append(hit["_score"])
  68. documents.append(hit["_source"].get("text"))
  69. metadatas.append(hit["_source"].get("metadata"))
  70. return SearchResult(
  71. ids=[ids], distances=[distances], documents=[documents], metadatas=[metadatas]
  72. )
  73. #Status: works
  74. def _create_index(self, dimension: int):
  75. body = {
  76. "mappings": {
  77. "properties": {
  78. "collection": {"type": "keyword"},
  79. "id": {"type": "keyword"},
  80. "vector": {
  81. "type": "dense_vector",
  82. "dims": dimension, # Adjust based on your vector dimensions
  83. "index": True,
  84. "similarity": "cosine",
  85. },
  86. "text": {"type": "text"},
  87. "metadata": {"type": "object"},
  88. }
  89. }
  90. }
  91. self.client.indices.create(index=self._get_index_name(dimension), body=body)
  92. #Status: works
  93. def _create_batches(self, items: list[VectorItem], batch_size=100):
  94. for i in range(0, len(items), batch_size):
  95. yield items[i : min(i + batch_size,len(items))]
  96. #Status: works
  97. def has_collection(self,collection_name) -> bool:
  98. query_body = {"query": {"bool": {"filter": []}}}
  99. query_body["query"]["bool"]["filter"].append({"term": {"collection": collection_name}})
  100. try:
  101. result = self.client.count(
  102. index=f"{self.index_prefix}*",
  103. body=query_body
  104. )
  105. return result.body["count"]>0
  106. except Exception as e:
  107. return None
  108. #@TODO: Make this delete a collection and not an index
  109. def delete_colleciton(self, collection_name: str):
  110. # TODO: fix this to include the dimension or a * prefix
  111. # delete_collection here means delete a bunch of documents for an index.
  112. # We are simply adapting to the norms of the other DBs.
  113. self.client.indices.delete(index=self._get_collection_name(collection_name))
  114. #Status: works
  115. def search(
  116. self, collection_name: str, vectors: list[list[float]], limit: int
  117. ) -> Optional[SearchResult]:
  118. query = {
  119. "size": limit,
  120. "_source": [
  121. "text",
  122. "metadata"
  123. ],
  124. "query": {
  125. "script_score": {
  126. "query": {
  127. "bool": {
  128. "filter": [
  129. {
  130. "term": {
  131. "collection": collection_name
  132. }
  133. }
  134. ]
  135. }
  136. },
  137. "script": {
  138. "source": "cosineSimilarity(params.vector, 'vector') + 1.0",
  139. "params": {
  140. "vector": vectors[0]
  141. }, # Assuming single query vector
  142. },
  143. }
  144. },
  145. }
  146. result = self.client.search(
  147. index=self._get_index_name(len(vectors[0])), body=query
  148. )
  149. return self._result_to_search_result(result)
  150. #Status: only tested halfwat
  151. def query(
  152. self, collection_name: str, filter: dict, limit: Optional[int] = None
  153. ) -> Optional[GetResult]:
  154. if not self.has_collection(collection_name):
  155. return None
  156. query_body = {
  157. "query": {"bool": {"filter": []}},
  158. "_source": ["text", "metadata"],
  159. }
  160. for field, value in filter.items():
  161. query_body["query"]["bool"]["filter"].append({"term": {field: value}})
  162. query_body["query"]["bool"]["filter"].append({"term": {"collection": collection_name}})
  163. size = limit if limit else 10
  164. try:
  165. result = self.client.search(
  166. index=f"{self.index_prefix}*",
  167. body=query_body,
  168. size=size,
  169. )
  170. return self._result_to_get_result(result)
  171. except Exception as e:
  172. return None
  173. #Status: works
  174. def _has_index(self,dimension:int):
  175. return self.client.indices.exists(index=self._get_index_name(dimension=dimension))
  176. def get_or_create_index(self, dimension: int):
  177. if not self._has_index(dimension=dimension):
  178. self._create_index(dimension=dimension)
  179. #Status: works
  180. def get(self, collection_name: str) -> Optional[GetResult]:
  181. # Get all the items in the collection.
  182. query = {
  183. "query": {
  184. "bool": {
  185. "filter": [
  186. {
  187. "term": {
  188. "collection": collection_name
  189. }
  190. }
  191. ]
  192. }
  193. }, "_source": ["text", "metadata"]}
  194. results = list(scan(self.client, index=f"{self.index_prefix}*", query=query))
  195. return self._scan_result_to_get_result(results)
  196. #Status: works
  197. def insert(self, collection_name: str, items: list[VectorItem]):
  198. if not self._has_index(dimension=len(items[0]["vector"])):
  199. self._create_index(dimension=len(items[0]["vector"]))
  200. for batch in self._create_batches(items):
  201. actions = [
  202. {
  203. "_index":self._get_index_name(dimension=len(items[0]["vector"])),
  204. "_id": item["id"],
  205. "_source": {
  206. "collection": collection_name,
  207. "vector": item["vector"],
  208. "text": item["text"],
  209. "metadata": item["metadata"],
  210. },
  211. }
  212. for item in batch
  213. ]
  214. bulk(self.client,actions)
  215. # Status: should work
  216. def upsert(self, collection_name: str, items: list[VectorItem]):
  217. if not self._has_index(dimension=len(items[0]["vector"])):
  218. self._create_index(collection_name, dimension=len(items[0]["vector"]))
  219. for batch in self._create_batches(items):
  220. actions = [
  221. {
  222. "_index": self._get_index_name(dimension=len(items[0]["vector"])),
  223. "_id": item["id"],
  224. "_source": {
  225. "vector": item["vector"],
  226. "text": item["text"],
  227. "metadata": item["metadata"],
  228. },
  229. }
  230. for item in batch
  231. ]
  232. self.client.bulk(actions)
  233. #TODO: This currently deletes by * which is not always supported in ElasticSearch.
  234. # Need to read a bit before changing. Also, need to delete from a specific collection
  235. def delete(self, collection_name: str, ids: list[str]):
  236. #Assuming ID is unique across collections and indexes
  237. actions = [
  238. {"delete": {"_index": f"{self.index_prefix}*", "_id": id}}
  239. for id in ids
  240. ]
  241. self.client.bulk(body=actions)
  242. def reset(self):
  243. indices = self.client.indices.get(index=f"{self.index_prefix}*")
  244. for index in indices:
  245. self.client.indices.delete(index=index)