opensearch.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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(self, documents: List[str], metadatas: List[object], ids: List[str]):
  88. """add data in vector database
  89. :param documents: list of texts to add
  90. :type documents: List[str]
  91. :param metadatas: list of metadata associated with docs
  92. :type metadatas: List[object]
  93. :param ids: ids of docs
  94. :type ids: List[str]
  95. """
  96. docs = []
  97. embeddings = self.embedder.embedding_fn(documents)
  98. for id, text, metadata, embeddings in zip(ids, documents, metadatas, embeddings):
  99. docs.append(
  100. {
  101. "_index": self._get_index(),
  102. "_id": id,
  103. "_source": {"text": text, "metadata": metadata, "embeddings": embeddings},
  104. }
  105. )
  106. bulk(self.client, docs)
  107. self.client.indices.refresh(index=self._get_index())
  108. def query(self, input_query: List[str], n_results: int, where: Dict[str, any]) -> List[str]:
  109. """
  110. query contents from vector data base based on vector similarity
  111. :param input_query: list of query string
  112. :type input_query: List[str]
  113. :param n_results: no of similar documents to fetch from database
  114. :type n_results: int
  115. :param where: Optional. to filter data
  116. :type where: Dict[str, any]
  117. :return: Database contents that are the result of the query
  118. :rtype: List[str]
  119. """
  120. embeddings = OpenAIEmbeddings()
  121. docsearch = OpenSearchVectorSearch(
  122. index_name=self._get_index(),
  123. embedding_function=embeddings,
  124. opensearch_url=f"{self.config.opensearch_url}",
  125. http_auth=self.config.http_auth,
  126. use_ssl=True,
  127. )
  128. docs = docsearch.similarity_search(
  129. input_query,
  130. search_type="script_scoring",
  131. space_type="cosinesimil",
  132. vector_field="embeddings",
  133. text_field="text",
  134. metadata_field="metadata",
  135. )
  136. contents = [doc.page_content for doc in docs]
  137. return contents
  138. def set_collection_name(self, name: str):
  139. """
  140. Set the name of the collection. A collection is an isolated space for vectors.
  141. :param name: Name of the collection.
  142. :type name: str
  143. """
  144. if not isinstance(name, str):
  145. raise TypeError("Collection name must be a string")
  146. self.config.collection_name = name
  147. def count(self) -> int:
  148. """
  149. Count number of documents/chunks embedded in the database.
  150. :return: number of documents
  151. :rtype: int
  152. """
  153. query = {"query": {"match_all": {}}}
  154. response = self.client.count(index=self._get_index(), body=query)
  155. doc_count = response["count"]
  156. return doc_count
  157. def reset(self):
  158. """
  159. Resets the database. Deletes all embeddings irreversibly.
  160. """
  161. # Delete all data from the database
  162. if self.client.indices.exists(index=self._get_index()):
  163. # delete index in Es
  164. self.client.indices.delete(index=self._get_index())
  165. def _get_index(self) -> str:
  166. """Get the OpenSearch index for a collection
  167. :return: OpenSearch index
  168. :rtype: str
  169. """
  170. return self.config.collection_name