opensearch.py 9.3 KB

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