elasticsearch.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. import logging
  2. from typing import Any, Dict, List, Optional, Tuple
  3. try:
  4. from elasticsearch import Elasticsearch
  5. from elasticsearch.helpers import bulk
  6. except ImportError:
  7. raise ImportError(
  8. "Elasticsearch requires extra dependencies. Install with `pip install --upgrade embedchain[elasticsearch]`"
  9. ) from None
  10. from embedchain.config import ElasticsearchDBConfig
  11. from embedchain.helper.json_serializable import register_deserializable
  12. from embedchain.vectordb.base import BaseVectorDB
  13. @register_deserializable
  14. class ElasticsearchDB(BaseVectorDB):
  15. """
  16. Elasticsearch as vector database
  17. """
  18. def __init__(
  19. self,
  20. config: Optional[ElasticsearchDBConfig] = None,
  21. es_config: Optional[ElasticsearchDBConfig] = None, # Backwards compatibility
  22. ):
  23. """Elasticsearch as vector database.
  24. :param config: Elasticsearch database config, defaults to None
  25. :type config: ElasticsearchDBConfig, optional
  26. :param es_config: `es_config` is supported as an alias for `config` (for backwards compatibility),
  27. defaults to None
  28. :type es_config: ElasticsearchDBConfig, optional
  29. :raises ValueError: No config provided
  30. """
  31. if config is None and es_config is None:
  32. self.config = ElasticsearchDBConfig()
  33. else:
  34. if not isinstance(config, ElasticsearchDBConfig):
  35. raise TypeError(
  36. "config is not a `ElasticsearchDBConfig` instance. "
  37. "Please make sure the type is right and that you are passing an instance."
  38. )
  39. self.config = config or es_config
  40. self.client = Elasticsearch(self.config.ES_URL, **self.config.ES_EXTRA_PARAMS)
  41. # Call parent init here because embedder is needed
  42. super().__init__(config=self.config)
  43. def _initialize(self):
  44. """
  45. This method is needed because `embedder` attribute needs to be set externally before it can be initialized.
  46. """
  47. logging.info(self.client.info())
  48. index_settings = {
  49. "mappings": {
  50. "properties": {
  51. "text": {"type": "text"},
  52. "embeddings": {"type": "dense_vector", "index": False, "dims": self.embedder.vector_dimension},
  53. }
  54. }
  55. }
  56. es_index = self._get_index()
  57. if not self.client.indices.exists(index=es_index):
  58. # create index if not exist
  59. print("Creating index", es_index, index_settings)
  60. self.client.indices.create(index=es_index, body=index_settings)
  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(self, ids: Optional[List[str]] = None, where: Optional[Dict[str, any]] = None, limit: Optional[int] = None):
  67. """
  68. Get existing doc ids present in vector database
  69. :param ids: _list of doc ids to check for existance
  70. :type ids: List[str]
  71. :param where: to filter data
  72. :type where: Dict[str, any]
  73. :return: ids
  74. :rtype: Set[str]
  75. """
  76. if ids:
  77. query = {"bool": {"must": [{"ids": {"values": ids}}]}}
  78. else:
  79. query = {"bool": {"must": []}}
  80. if "app_id" in where:
  81. app_id = where["app_id"]
  82. query["bool"]["must"].append({"term": {"metadata.app_id": app_id}})
  83. response = self.client.search(index=self._get_index(), query=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,
  89. embeddings: List[List[float]],
  90. documents: List[str],
  91. metadatas: List[object],
  92. ids: List[str],
  93. skip_embedding: bool,
  94. ) -> Any:
  95. """
  96. add data in vector database
  97. :param embeddings: list of embeddings to add
  98. :type embeddings: List[List[str]]
  99. :param documents: list of texts to add
  100. :type documents: List[str]
  101. :param metadatas: list of metadata associated with docs
  102. :type metadatas: List[object]
  103. :param ids: ids of docs
  104. :type ids: List[str]
  105. :param skip_embedding: Optional. If True, then the input_query is assumed to be already embedded.
  106. :type skip_embedding: bool
  107. """
  108. docs = []
  109. if not skip_embedding:
  110. embeddings = self.embedder.embedding_fn(documents)
  111. for id, text, metadata, embeddings in zip(ids, documents, metadatas, embeddings):
  112. docs.append(
  113. {
  114. "_index": self._get_index(),
  115. "_id": id,
  116. "_source": {"text": text, "metadata": metadata, "embeddings": embeddings},
  117. }
  118. )
  119. bulk(self.client, docs)
  120. self.client.indices.refresh(index=self._get_index())
  121. def query(
  122. self, input_query: List[str], n_results: int, where: Dict[str, any], skip_embedding: bool
  123. ) -> List[Tuple[str, str, str]]:
  124. """
  125. query contents from vector data base based on vector similarity
  126. :param input_query: list of query string
  127. :type input_query: List[str]
  128. :param n_results: no of similar documents to fetch from database
  129. :type n_results: int
  130. :param where: Optional. to filter data
  131. :type where: Dict[str, any]
  132. :param skip_embedding: Optional. If True, then the input_query is assumed to be already embedded.
  133. :type skip_embedding: bool
  134. :return: The context of the document that matched your query, url of the source, doc_id
  135. :rtype: List[Tuple[str,str,str]]
  136. """
  137. if skip_embedding:
  138. query_vector = input_query
  139. else:
  140. input_query_vector = self.embedder.embedding_fn(input_query)
  141. query_vector = input_query_vector[0]
  142. # `https://www.elastic.co/guide/en/elasticsearch/reference/7.17/query-dsl-script-score-query.html`
  143. query = {
  144. "script_score": {
  145. "query": {"bool": {"must": [{"exists": {"field": "text"}}]}},
  146. "script": {
  147. "source": "cosineSimilarity(params.input_query_vector, 'embeddings') + 1.0",
  148. "params": {"input_query_vector": query_vector},
  149. },
  150. }
  151. }
  152. if "app_id" in where:
  153. app_id = where["app_id"]
  154. query["script_score"]["query"] = {"match": {"metadata.app_id": app_id}}
  155. _source = ["text", "metadata.url", "metadata.doc_id"]
  156. response = self.client.search(index=self._get_index(), query=query, _source=_source, size=n_results)
  157. docs = response["hits"]["hits"]
  158. contents = []
  159. for doc in docs:
  160. context = doc["_source"]["text"]
  161. metadata = doc["_source"]["metadata"]
  162. source = metadata["url"]
  163. doc_id = metadata["doc_id"]
  164. contents.append(tuple((context, source, doc_id)))
  165. return contents
  166. def set_collection_name(self, name: str):
  167. """
  168. Set the name of the collection. A collection is an isolated space for vectors.
  169. :param name: Name of the collection.
  170. :type name: str
  171. """
  172. if not isinstance(name, str):
  173. raise TypeError("Collection name must be a string")
  174. self.config.collection_name = name
  175. def count(self) -> int:
  176. """
  177. Count number of documents/chunks embedded in the database.
  178. :return: number of documents
  179. :rtype: int
  180. """
  181. query = {"match_all": {}}
  182. response = self.client.count(index=self._get_index(), query=query)
  183. doc_count = response["count"]
  184. return doc_count
  185. def reset(self):
  186. """
  187. Resets the database. Deletes all embeddings irreversibly.
  188. """
  189. # Delete all data from the database
  190. if self.client.indices.exists(index=self._get_index()):
  191. # delete index in Es
  192. self.client.indices.delete(index=self._get_index())
  193. def _get_index(self) -> str:
  194. """Get the Elasticsearch index for a collection
  195. :return: Elasticsearch index
  196. :rtype: str
  197. """
  198. # NOTE: The method is preferred to an attribute, because if collection name changes,
  199. # it's always up-to-date.
  200. return f"{self.config.collection_name}_{self.embedder.vector_dimension}".lower()