opensearch.py 8.5 KB

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