opensearch.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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. if ids:
  76. query = {"query": {"bool": {"must": [{"ids": {"values": ids}}]}}}
  77. else:
  78. query = {"query": {"bool": {"must": []}}}
  79. if "app_id" in where:
  80. app_id = where["app_id"]
  81. query["query"]["bool"]["must"].append({"term": {"metadata.app_id": app_id}})
  82. # OpenSearch syntax is different from Elasticsearch
  83. response = self.client.search(index=self._get_index(), body=query, _source=False, size=limit)
  84. docs = response["hits"]["hits"]
  85. ids = [doc["_id"] for doc in docs]
  86. return {"ids": set(ids)}
  87. def add(
  88. self, embeddings: List[str], documents: List[str], metadatas: List[object], ids: List[str], skip_embedding: bool
  89. ):
  90. """add data in vector database
  91. :param embeddings: list of embeddings to add
  92. :type embeddings: List[str]
  93. :param documents: list of texts to add
  94. :type documents: List[str]
  95. :param metadatas: list of metadata associated with docs
  96. :type metadatas: List[object]
  97. :param ids: ids of docs
  98. :type ids: List[str]
  99. :param skip_embedding: Optional. If True, then the embeddings are assumed to be already generated.
  100. :type skip_embedding: bool
  101. """
  102. docs = []
  103. # TODO(rupeshbansal, deshraj): Add support for skip embeddings here if already exists
  104. embeddings = self.embedder.embedding_fn(documents)
  105. for id, text, metadata, embeddings in zip(ids, documents, metadatas, embeddings):
  106. docs.append(
  107. {
  108. "_index": self._get_index(),
  109. "_id": id,
  110. "_source": {"text": text, "metadata": metadata, "embeddings": embeddings},
  111. }
  112. )
  113. bulk(self.client, docs)
  114. self.client.indices.refresh(index=self._get_index())
  115. def query(self, input_query: List[str], n_results: int, where: Dict[str, any], skip_embedding: bool) -> List[str]:
  116. """
  117. query contents from vector data base based on vector similarity
  118. :param input_query: list of query string
  119. :type input_query: List[str]
  120. :param n_results: no of similar documents to fetch from database
  121. :type n_results: int
  122. :param where: Optional. to filter data
  123. :type where: Dict[str, any]
  124. :param skip_embedding: Optional. If True, then the input_query is assumed to be already embedded.
  125. :type skip_embedding: bool
  126. :return: Database contents that are the result of the query
  127. :rtype: List[str]
  128. """
  129. # TODO(rupeshbansal, deshraj): Add support for skip embeddings here if already exists
  130. embeddings = OpenAIEmbeddings()
  131. docsearch = OpenSearchVectorSearch(
  132. index_name=self._get_index(),
  133. embedding_function=embeddings,
  134. opensearch_url=f"{self.config.opensearch_url}",
  135. http_auth=self.config.http_auth,
  136. use_ssl=True,
  137. )
  138. pre_filter = {"match_all": {}} # default
  139. if "app_id" in where:
  140. app_id = where["app_id"]
  141. pre_filter = {"bool": {"must": [{"term": {"metadata.app_id": app_id}}]}}
  142. docs = docsearch.similarity_search(
  143. input_query,
  144. search_type="script_scoring",
  145. space_type="cosinesimil",
  146. vector_field="embeddings",
  147. text_field="text",
  148. metadata_field="metadata",
  149. pre_filter=pre_filter,
  150. k=n_results,
  151. )
  152. contents = [doc.page_content for doc in docs]
  153. return contents
  154. def set_collection_name(self, name: str):
  155. """
  156. Set the name of the collection. A collection is an isolated space for vectors.
  157. :param name: Name of the collection.
  158. :type name: str
  159. """
  160. if not isinstance(name, str):
  161. raise TypeError("Collection name must be a string")
  162. self.config.collection_name = name
  163. def count(self) -> int:
  164. """
  165. Count number of documents/chunks embedded in the database.
  166. :return: number of documents
  167. :rtype: int
  168. """
  169. query = {"query": {"match_all": {}}}
  170. response = self.client.count(index=self._get_index(), body=query)
  171. doc_count = response["count"]
  172. return doc_count
  173. def reset(self):
  174. """
  175. Resets the database. Deletes all embeddings irreversibly.
  176. """
  177. # Delete all data from the database
  178. if self.client.indices.exists(index=self._get_index()):
  179. # delete index in Es
  180. self.client.indices.delete(index=self._get_index())
  181. def _get_index(self) -> str:
  182. """Get the OpenSearch index for a collection
  183. :return: OpenSearch index
  184. :rtype: str
  185. """
  186. return self.config.collection_name