opensearch.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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_community.embeddings.openai import OpenAIEmbeddings
  13. from langchain_community.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 where:
  84. for key, value in where.items():
  85. query["query"]["bool"]["must"].append({"term": {f"metadata.{key}.keyword": value}})
  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(self, documents: list[str], metadatas: list[object], ids: list[str], **kwargs: Optional[dict[str, any]]):
  98. """Adds documents to the opensearch index"""
  99. embeddings = self.embedder.embedding_fn(documents)
  100. for batch_start in tqdm(range(0, len(documents), self.BATCH_SIZE), desc="Inserting batches in opensearch"):
  101. batch_end = batch_start + self.BATCH_SIZE
  102. batch_documents = documents[batch_start:batch_end]
  103. batch_embeddings = embeddings[batch_start:batch_end]
  104. # Create document entries for bulk upload
  105. batch_entries = [
  106. {
  107. "_index": self._get_index(),
  108. "_id": doc_id,
  109. "_source": {"text": text, "metadata": metadata, "embeddings": embedding},
  110. }
  111. for doc_id, text, metadata, embedding in zip(
  112. ids[batch_start:batch_end], batch_documents, metadatas[batch_start:batch_end], batch_embeddings
  113. )
  114. ]
  115. # Perform bulk operation
  116. bulk(self.client, batch_entries, **kwargs)
  117. self.client.indices.refresh(index=self._get_index())
  118. # Sleep to avoid rate limiting
  119. time.sleep(0.1)
  120. def query(
  121. self,
  122. input_query: list[str],
  123. n_results: int,
  124. where: dict[str, any],
  125. citations: bool = False,
  126. **kwargs: Optional[dict[str, Any]],
  127. ) -> Union[list[tuple[str, dict]], list[str]]:
  128. """
  129. query contents from vector database based on vector similarity
  130. :param input_query: list of query string
  131. :type input_query: list[str]
  132. :param n_results: no of similar documents to fetch from database
  133. :type n_results: int
  134. :param where: Optional. to filter data
  135. :type where: dict[str, any]
  136. :param citations: we use citations boolean param to return context along with the answer.
  137. :type citations: bool, default is False.
  138. :return: The content of the document that matched your query,
  139. along with url of the source and doc_id (if citations flag is true)
  140. :rtype: list[str], if citations=False, otherwise list[tuple[str, str, str]]
  141. """
  142. embeddings = OpenAIEmbeddings()
  143. docsearch = OpenSearchVectorSearch(
  144. index_name=self._get_index(),
  145. embedding_function=embeddings,
  146. opensearch_url=f"{self.config.opensearch_url}",
  147. http_auth=self.config.http_auth,
  148. use_ssl=hasattr(self.config, "use_ssl") and self.config.use_ssl,
  149. verify_certs=hasattr(self.config, "verify_certs") and self.config.verify_certs,
  150. )
  151. pre_filter = {"match_all": {}} # default
  152. if len(where) > 0:
  153. pre_filter = {"bool": {"must": []}}
  154. for key, value in where.items():
  155. pre_filter["bool"]["must"].append({"term": {f"metadata.{key}.keyword": value}})
  156. docs = docsearch.similarity_search_with_score(
  157. input_query,
  158. search_type="script_scoring",
  159. space_type="cosinesimil",
  160. vector_field="embeddings",
  161. text_field="text",
  162. metadata_field="metadata",
  163. pre_filter=pre_filter,
  164. k=n_results,
  165. **kwargs,
  166. )
  167. contexts = []
  168. for doc, score in docs:
  169. context = doc.page_content
  170. if citations:
  171. metadata = doc.metadata
  172. metadata["score"] = score
  173. contexts.append(tuple((context, metadata)))
  174. else:
  175. contexts.append(context)
  176. return contexts
  177. def set_collection_name(self, name: str):
  178. """
  179. Set the name of the collection. A collection is an isolated space for vectors.
  180. :param name: Name of the collection.
  181. :type name: str
  182. """
  183. if not isinstance(name, str):
  184. raise TypeError("Collection name must be a string")
  185. self.config.collection_name = name
  186. def count(self) -> int:
  187. """
  188. Count number of documents/chunks embedded in the database.
  189. :return: number of documents
  190. :rtype: int
  191. """
  192. query = {"query": {"match_all": {}}}
  193. response = self.client.count(index=self._get_index(), body=query)
  194. doc_count = response["count"]
  195. return doc_count
  196. def reset(self):
  197. """
  198. Resets the database. Deletes all embeddings irreversibly.
  199. """
  200. # Delete all data from the database
  201. if self.client.indices.exists(index=self._get_index()):
  202. # delete index in ES
  203. self.client.indices.delete(index=self._get_index())
  204. def delete(self, where):
  205. """Deletes a document from the OpenSearch index"""
  206. query = {"query": {"bool": {"must": []}}}
  207. for key, value in where.items():
  208. query["query"]["bool"]["must"].append({"term": {f"metadata.{key}.keyword": value}})
  209. self.client.delete_by_query(index=self._get_index(), body=query)
  210. def _get_index(self) -> str:
  211. """Get the OpenSearch index for a collection
  212. :return: OpenSearch index
  213. :rtype: str
  214. """
  215. return self.config.collection_name