opensearch.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. import logging
  2. from typing import Dict, List, Optional, Set, Tuple
  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.keyword": 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,
  96. embeddings: List[List[str]],
  97. documents: List[str],
  98. metadatas: List[object],
  99. ids: List[str],
  100. skip_embedding: bool,
  101. ):
  102. """add data in vector database
  103. :param embeddings: list of embeddings to add
  104. :type embeddings: List[List[str]]
  105. :param documents: list of texts to add
  106. :type documents: List[str]
  107. :param metadatas: list of metadata associated with docs
  108. :type metadatas: List[object]
  109. :param ids: ids of docs
  110. :type ids: List[str]
  111. :param skip_embedding: Optional. If True, then the embeddings are assumed to be already generated.
  112. :type skip_embedding: bool
  113. """
  114. docs = []
  115. if not skip_embedding:
  116. embeddings = self.embedder.embedding_fn(documents)
  117. for id, text, metadata, embeddings in zip(ids, documents, metadatas, embeddings):
  118. docs.append(
  119. {
  120. "_index": self._get_index(),
  121. "_id": id,
  122. "_source": {"text": text, "metadata": metadata, "embeddings": embeddings},
  123. }
  124. )
  125. bulk(self.client, docs)
  126. self.client.indices.refresh(index=self._get_index())
  127. def query(
  128. self, input_query: List[str], n_results: int, where: Dict[str, any], skip_embedding: bool
  129. ) -> List[Tuple[str, str, str]]:
  130. """
  131. query contents from vector data base based on vector similarity
  132. :param input_query: list of query string
  133. :type input_query: List[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 skip_embedding: Optional. If True, then the input_query is assumed to be already embedded.
  139. :type skip_embedding: bool
  140. :return: The content of the document that matched your query, url of the source, doc_id
  141. :rtype: List[Tuple[str,str,str]]
  142. """
  143. # TODO(rupeshbansal, deshraj): Add support for skip embeddings here if already exists
  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 "app_id" in where:
  155. app_id = where["app_id"]
  156. pre_filter = {"bool": {"must": [{"term": {"metadata.app_id.keyword": app_id}}]}}
  157. docs = docsearch.similarity_search(
  158. input_query,
  159. search_type="script_scoring",
  160. space_type="cosinesimil",
  161. vector_field="embeddings",
  162. text_field="text",
  163. metadata_field="metadata",
  164. pre_filter=pre_filter,
  165. k=n_results,
  166. )
  167. contents = []
  168. for doc in docs:
  169. context = doc.page_content
  170. source = doc.metadata["url"]
  171. doc_id = doc.metadata["doc_id"]
  172. contents.append(tuple((context, source, doc_id)))
  173. return contents
  174. def set_collection_name(self, name: str):
  175. """
  176. Set the name of the collection. A collection is an isolated space for vectors.
  177. :param name: Name of the collection.
  178. :type name: str
  179. """
  180. if not isinstance(name, str):
  181. raise TypeError("Collection name must be a string")
  182. self.config.collection_name = name
  183. def count(self) -> int:
  184. """
  185. Count number of documents/chunks embedded in the database.
  186. :return: number of documents
  187. :rtype: int
  188. """
  189. query = {"query": {"match_all": {}}}
  190. response = self.client.count(index=self._get_index(), body=query)
  191. doc_count = response["count"]
  192. return doc_count
  193. def reset(self):
  194. """
  195. Resets the database. Deletes all embeddings irreversibly.
  196. """
  197. # Delete all data from the database
  198. if self.client.indices.exists(index=self._get_index()):
  199. # delete index in Es
  200. self.client.indices.delete(index=self._get_index())
  201. def delete(self, where):
  202. """Deletes a document from the OpenSearch index"""
  203. if "doc_id" not in where:
  204. raise ValueError("doc_id is required to delete a document")
  205. query = {"query": {"bool": {"must": [{"term": {"metadata.doc_id": where["doc_id"]}}]}}}
  206. self.client.delete_by_query(index=self._get_index(), body=query)
  207. def _get_index(self) -> str:
  208. """Get the OpenSearch index for a collection
  209. :return: OpenSearch index
  210. :rtype: str
  211. """
  212. return self.config.collection_name