opensearch.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. import logging
  2. import time
  3. from typing import Dict, List, Optional, Set, Tuple, 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. skip_embedding: bool,
  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. skip_embedding (bool): If True, then embeddings are assumed to be already generated.
  112. """
  113. for batch_start in tqdm(range(0, len(documents), self.BATCH_SIZE), desc="Inserting batches in opensearch"):
  114. batch_end = batch_start + self.BATCH_SIZE
  115. batch_documents = documents[batch_start:batch_end]
  116. # Generate embeddings for the batch if not skipping embedding
  117. if not skip_embedding:
  118. batch_embeddings = self.embedder.embedding_fn(batch_documents)
  119. else:
  120. batch_embeddings = embeddings[batch_start:batch_end]
  121. # Create document entries for bulk upload
  122. batch_entries = [
  123. {
  124. "_index": self._get_index(),
  125. "_id": doc_id,
  126. "_source": {"text": text, "metadata": metadata, "embeddings": embedding},
  127. }
  128. for doc_id, text, metadata, embedding in zip(
  129. ids[batch_start:batch_end], batch_documents, metadatas[batch_start:batch_end], batch_embeddings
  130. )
  131. ]
  132. # Perform bulk operation
  133. bulk(self.client, batch_entries)
  134. self.client.indices.refresh(index=self._get_index())
  135. # Sleep to avoid rate limiting
  136. time.sleep(0.1)
  137. def query(
  138. self,
  139. input_query: List[str],
  140. n_results: int,
  141. where: Dict[str, any],
  142. skip_embedding: bool,
  143. citations: bool = False,
  144. ) -> Union[List[Tuple[str, str, str]], List[str]]:
  145. """
  146. query contents from vector data base based on vector similarity
  147. :param input_query: list of query string
  148. :type input_query: List[str]
  149. :param n_results: no of similar documents to fetch from database
  150. :type n_results: int
  151. :param where: Optional. to filter data
  152. :type where: Dict[str, any]
  153. :param skip_embedding: Optional. If True, then the input_query is assumed to be already embedded.
  154. :type skip_embedding: bool
  155. :param citations: we use citations boolean param to return context along with the answer.
  156. :type citations: bool, default is False.
  157. :return: The content of the document that matched your query,
  158. along with url of the source and doc_id (if citations flag is true)
  159. :rtype: List[str], if citations=False, otherwise List[Tuple[str, str, str]]
  160. """
  161. # TODO(rupeshbansal, deshraj): Add support for skip embeddings here if already exists
  162. embeddings = OpenAIEmbeddings()
  163. docsearch = OpenSearchVectorSearch(
  164. index_name=self._get_index(),
  165. embedding_function=embeddings,
  166. opensearch_url=f"{self.config.opensearch_url}",
  167. http_auth=self.config.http_auth,
  168. use_ssl=hasattr(self.config, "use_ssl") and self.config.use_ssl,
  169. verify_certs=hasattr(self.config, "verify_certs") and self.config.verify_certs,
  170. )
  171. pre_filter = {"match_all": {}} # default
  172. if "app_id" in where:
  173. app_id = where["app_id"]
  174. pre_filter = {"bool": {"must": [{"term": {"metadata.app_id.keyword": app_id}}]}}
  175. docs = docsearch.similarity_search(
  176. input_query,
  177. search_type="script_scoring",
  178. space_type="cosinesimil",
  179. vector_field="embeddings",
  180. text_field="text",
  181. metadata_field="metadata",
  182. pre_filter=pre_filter,
  183. k=n_results,
  184. )
  185. contexts = []
  186. for doc in docs:
  187. context = doc.page_content
  188. if citations:
  189. source = doc.metadata["url"]
  190. doc_id = doc.metadata["doc_id"]
  191. contexts.append(tuple((context, source, doc_id)))
  192. else:
  193. contexts.append(context)
  194. return contexts
  195. def set_collection_name(self, name: str):
  196. """
  197. Set the name of the collection. A collection is an isolated space for vectors.
  198. :param name: Name of the collection.
  199. :type name: str
  200. """
  201. if not isinstance(name, str):
  202. raise TypeError("Collection name must be a string")
  203. self.config.collection_name = name
  204. def count(self) -> int:
  205. """
  206. Count number of documents/chunks embedded in the database.
  207. :return: number of documents
  208. :rtype: int
  209. """
  210. query = {"query": {"match_all": {}}}
  211. response = self.client.count(index=self._get_index(), body=query)
  212. doc_count = response["count"]
  213. return doc_count
  214. def reset(self):
  215. """
  216. Resets the database. Deletes all embeddings irreversibly.
  217. """
  218. # Delete all data from the database
  219. if self.client.indices.exists(index=self._get_index()):
  220. # delete index in ES
  221. self.client.indices.delete(index=self._get_index())
  222. def delete(self, where):
  223. """Deletes a document from the OpenSearch index"""
  224. if "doc_id" not in where:
  225. raise ValueError("doc_id is required to delete a document")
  226. query = {"query": {"bool": {"must": [{"term": {"metadata.doc_id": where["doc_id"]}}]}}}
  227. self.client.delete_by_query(index=self._get_index(), body=query)
  228. def _get_index(self) -> str:
  229. """Get the OpenSearch index for a collection
  230. :return: OpenSearch index
  231. :rtype: str
  232. """
  233. return self.config.collection_name