opensearch.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. import logging
  2. import time
  3. from typing import Any, Optional, Union
  4. from tqdm import tqdm
  5. try:
  6. from opensearchpy import OpenSearch
  7. from opensearchpy.helpers import bulk
  8. except ImportError:
  9. raise ImportError(
  10. "OpenSearch requires extra dependencies. Install with `pip install --upgrade embedchain[opensearch]`"
  11. ) from None
  12. from langchain.embeddings.openai import OpenAIEmbeddings
  13. from langchain.vectorstores import OpenSearchVectorSearch
  14. from embedchain.config import OpenSearchDBConfig
  15. from embedchain.helpers.json_serializable import register_deserializable
  16. from embedchain.vectordb.base import BaseVectorDB
  17. @register_deserializable
  18. class OpenSearchDB(BaseVectorDB):
  19. """
  20. OpenSearch as vector database
  21. """
  22. BATCH_SIZE = 100
  23. def __init__(self, config: OpenSearchDBConfig):
  24. """OpenSearch as vector database.
  25. :param config: OpenSearch domain config
  26. :type config: OpenSearchDBConfig
  27. """
  28. if config is None:
  29. raise ValueError("OpenSearchDBConfig is required")
  30. self.config = config
  31. self.client = OpenSearch(
  32. hosts=[self.config.opensearch_url],
  33. http_auth=self.config.http_auth,
  34. **self.config.extra_params,
  35. )
  36. info = self.client.info()
  37. logging.info(f"Connected to {info['version']['distribution']}. Version: {info['version']['number']}")
  38. # Remove auth credentials from config after successful connection
  39. super().__init__(config=self.config)
  40. def _initialize(self):
  41. logging.info(self.client.info())
  42. index_name = self._get_index()
  43. if self.client.indices.exists(index=index_name):
  44. print(f"Index '{index_name}' already exists.")
  45. return
  46. index_body = {
  47. "settings": {"knn": True},
  48. "mappings": {
  49. "properties": {
  50. "text": {"type": "text"},
  51. "embeddings": {
  52. "type": "knn_vector",
  53. "index": False,
  54. "dimension": self.config.vector_dimension,
  55. },
  56. }
  57. },
  58. }
  59. self.client.indices.create(index_name, body=index_body)
  60. print(self.client.indices.get(index_name))
  61. def _get_or_create_db(self):
  62. """Called during initialization"""
  63. return self.client
  64. def _get_or_create_collection(self, name):
  65. """Note: nothing to return here. Discuss later"""
  66. def get(
  67. self, ids: Optional[list[str]] = None, where: Optional[dict[str, any]] = None, limit: Optional[int] = None
  68. ) -> set[str]:
  69. """
  70. Get existing doc ids present in vector database
  71. :param ids: _list of doc ids to check for existence
  72. :type ids: list[str]
  73. :param where: to filter data
  74. :type where: dict[str, any]
  75. :return: ids
  76. :type: set[str]
  77. """
  78. query = {}
  79. if ids:
  80. query["query"] = {"bool": {"must": [{"ids": {"values": ids}}]}}
  81. else:
  82. query["query"] = {"bool": {"must": []}}
  83. if "app_id" in where:
  84. app_id = where["app_id"]
  85. query["query"]["bool"]["must"].append({"term": {"metadata.app_id.keyword": app_id}})
  86. # OpenSearch syntax is different from Elasticsearch
  87. response = self.client.search(index=self._get_index(), body=query, _source=True, size=limit)
  88. docs = response["hits"]["hits"]
  89. ids = [doc["_id"] for doc in docs]
  90. doc_ids = [doc["_source"]["metadata"]["doc_id"] for doc in docs]
  91. # Result is modified for compatibility with other vector databases
  92. # TODO: Add method in vector database to return result in a standard format
  93. result = {"ids": ids, "metadatas": []}
  94. for doc_id in doc_ids:
  95. result["metadatas"].append({"doc_id": doc_id})
  96. return result
  97. def add(
  98. self,
  99. embeddings: list[list[str]],
  100. documents: list[str],
  101. metadatas: list[object],
  102. ids: list[str],
  103. **kwargs: Optional[dict[str, any]],
  104. ):
  105. """Add data in vector database.
  106. Args:
  107. embeddings (list[list[str]]): list of embeddings to add.
  108. documents (list[str]): list of texts to add.
  109. metadatas (list[object]): list of metadata associated with docs.
  110. ids (list[str]): IDs of docs.
  111. """
  112. for batch_start in tqdm(range(0, len(documents), self.BATCH_SIZE), desc="Inserting batches in opensearch"):
  113. batch_end = batch_start + self.BATCH_SIZE
  114. batch_documents = documents[batch_start:batch_end]
  115. batch_embeddings = embeddings[batch_start:batch_end]
  116. # Create document entries for bulk upload
  117. batch_entries = [
  118. {
  119. "_index": self._get_index(),
  120. "_id": doc_id,
  121. "_source": {"text": text, "metadata": metadata, "embeddings": embedding},
  122. }
  123. for doc_id, text, metadata, embedding in zip(
  124. ids[batch_start:batch_end], batch_documents, metadatas[batch_start:batch_end], batch_embeddings
  125. )
  126. ]
  127. # Perform bulk operation
  128. bulk(self.client, batch_entries, **kwargs)
  129. self.client.indices.refresh(index=self._get_index())
  130. # Sleep to avoid rate limiting
  131. time.sleep(0.1)
  132. def query(
  133. self,
  134. input_query: list[str],
  135. n_results: int,
  136. where: dict[str, any],
  137. citations: bool = False,
  138. **kwargs: Optional[dict[str, Any]],
  139. ) -> Union[list[tuple[str, dict]], list[str]]:
  140. """
  141. query contents from vector database based on vector similarity
  142. :param input_query: list of query string
  143. :type input_query: list[str]
  144. :param n_results: no of similar documents to fetch from database
  145. :type n_results: int
  146. :param where: Optional. to filter data
  147. :type where: dict[str, any]
  148. :param citations: we use citations boolean param to return context along with the answer.
  149. :type citations: bool, default is False.
  150. :return: The content of the document that matched your query,
  151. along with url of the source and doc_id (if citations flag is true)
  152. :rtype: list[str], if citations=False, otherwise list[tuple[str, str, str]]
  153. """
  154. embeddings = OpenAIEmbeddings()
  155. docsearch = OpenSearchVectorSearch(
  156. index_name=self._get_index(),
  157. embedding_function=embeddings,
  158. opensearch_url=f"{self.config.opensearch_url}",
  159. http_auth=self.config.http_auth,
  160. use_ssl=hasattr(self.config, "use_ssl") and self.config.use_ssl,
  161. verify_certs=hasattr(self.config, "verify_certs") and self.config.verify_certs,
  162. )
  163. pre_filter = {"match_all": {}} # default
  164. if "app_id" in where:
  165. app_id = where["app_id"]
  166. pre_filter = {"bool": {"must": [{"term": {"metadata.app_id.keyword": app_id}}]}}
  167. docs = docsearch.similarity_search_with_score(
  168. input_query,
  169. search_type="script_scoring",
  170. space_type="cosinesimil",
  171. vector_field="embeddings",
  172. text_field="text",
  173. metadata_field="metadata",
  174. pre_filter=pre_filter,
  175. k=n_results,
  176. **kwargs,
  177. )
  178. contexts = []
  179. for doc, score in docs:
  180. context = doc.page_content
  181. if citations:
  182. metadata = doc.metadata
  183. metadata["score"] = score
  184. contexts.append(tuple((context, metadata)))
  185. else:
  186. contexts.append(context)
  187. return contexts
  188. def set_collection_name(self, name: str):
  189. """
  190. Set the name of the collection. A collection is an isolated space for vectors.
  191. :param name: Name of the collection.
  192. :type name: str
  193. """
  194. if not isinstance(name, str):
  195. raise TypeError("Collection name must be a string")
  196. self.config.collection_name = name
  197. def count(self) -> int:
  198. """
  199. Count number of documents/chunks embedded in the database.
  200. :return: number of documents
  201. :rtype: int
  202. """
  203. query = {"query": {"match_all": {}}}
  204. response = self.client.count(index=self._get_index(), body=query)
  205. doc_count = response["count"]
  206. return doc_count
  207. def reset(self):
  208. """
  209. Resets the database. Deletes all embeddings irreversibly.
  210. """
  211. # Delete all data from the database
  212. if self.client.indices.exists(index=self._get_index()):
  213. # delete index in ES
  214. self.client.indices.delete(index=self._get_index())
  215. def delete(self, where):
  216. """Deletes a document from the OpenSearch index"""
  217. if "doc_id" not in where:
  218. raise ValueError("doc_id is required to delete a document")
  219. query = {"query": {"bool": {"must": [{"term": {"metadata.doc_id": where["doc_id"]}}]}}}
  220. self.client.delete_by_query(index=self._get_index(), body=query)
  221. def _get_index(self) -> str:
  222. """Get the OpenSearch index for a collection
  223. :return: OpenSearch index
  224. :rtype: str
  225. """
  226. return self.config.collection_name