elasticsearch.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. import logging
  2. from typing import Any, Optional, Union
  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.helpers.json_serializable import register_deserializable
  12. from embedchain.utils.misc import chunks
  13. from embedchain.vectordb.base import BaseVectorDB
  14. logger = logging.getLogger(__name__)
  15. @register_deserializable
  16. class ElasticsearchDB(BaseVectorDB):
  17. """
  18. Elasticsearch as vector database
  19. """
  20. def __init__(
  21. self,
  22. config: Optional[ElasticsearchDBConfig] = None,
  23. es_config: Optional[ElasticsearchDBConfig] = None, # Backwards compatibility
  24. ):
  25. """Elasticsearch as vector database.
  26. :param config: Elasticsearch database config, defaults to None
  27. :type config: ElasticsearchDBConfig, optional
  28. :param es_config: `es_config` is supported as an alias for `config` (for backwards compatibility),
  29. defaults to None
  30. :type es_config: ElasticsearchDBConfig, optional
  31. :raises ValueError: No config provided
  32. """
  33. if config is None and es_config is None:
  34. self.config = ElasticsearchDBConfig()
  35. else:
  36. if not isinstance(config, ElasticsearchDBConfig):
  37. raise TypeError(
  38. "config is not a `ElasticsearchDBConfig` instance. "
  39. "Please make sure the type is right and that you are passing an instance."
  40. )
  41. self.config = config or es_config
  42. if self.config.ES_URL:
  43. self.client = Elasticsearch(self.config.ES_URL, **self.config.ES_EXTRA_PARAMS)
  44. elif self.config.CLOUD_ID:
  45. self.client = Elasticsearch(cloud_id=self.config.CLOUD_ID, **self.config.ES_EXTRA_PARAMS)
  46. else:
  47. raise ValueError(
  48. "Something is wrong with your config. Please check again - `https://docs.embedchain.ai/components/vector-databases#elasticsearch`" # noqa: E501
  49. )
  50. self.batch_size = self.config.batch_size
  51. # Call parent init here because embedder is needed
  52. super().__init__(config=self.config)
  53. def _initialize(self):
  54. """
  55. This method is needed because `embedder` attribute needs to be set externally before it can be initialized.
  56. """
  57. logger.info(self.client.info())
  58. index_settings = {
  59. "mappings": {
  60. "properties": {
  61. "text": {"type": "text"},
  62. "embeddings": {"type": "dense_vector", "index": False, "dims": self.embedder.vector_dimension},
  63. }
  64. }
  65. }
  66. es_index = self._get_index()
  67. if not self.client.indices.exists(index=es_index):
  68. # create index if not exist
  69. print("Creating index", es_index, index_settings)
  70. self.client.indices.create(index=es_index, body=index_settings)
  71. def _get_or_create_db(self):
  72. """Called during initialization"""
  73. return self.client
  74. def _get_or_create_collection(self, name):
  75. """Note: nothing to return here. Discuss later"""
  76. def get(self, ids: Optional[list[str]] = None, where: Optional[dict[str, any]] = None, limit: Optional[int] = None):
  77. """
  78. Get existing doc ids present in vector database
  79. :param ids: _list of doc ids to check for existence
  80. :type ids: list[str]
  81. :param where: to filter data
  82. :type where: dict[str, any]
  83. :return: ids
  84. :rtype: Set[str]
  85. """
  86. if ids:
  87. query = {"bool": {"must": [{"ids": {"values": ids}}]}}
  88. else:
  89. query = {"bool": {"must": []}}
  90. if where:
  91. for key, value in where.items():
  92. query["bool"]["must"].append({"term": {f"metadata.{key}.keyword": value}})
  93. response = self.client.search(index=self._get_index(), query=query, _source=True, size=limit)
  94. docs = response["hits"]["hits"]
  95. ids = [doc["_id"] for doc in docs]
  96. doc_ids = [doc["_source"]["metadata"]["doc_id"] for doc in docs]
  97. # Result is modified for compatibility with other vector databases
  98. # TODO: Add method in vector database to return result in a standard format
  99. result = {"ids": ids, "metadatas": []}
  100. for doc_id in doc_ids:
  101. result["metadatas"].append({"doc_id": doc_id})
  102. return result
  103. def add(
  104. self,
  105. documents: list[str],
  106. metadatas: list[object],
  107. ids: list[str],
  108. **kwargs: Optional[dict[str, any]],
  109. ) -> Any:
  110. """
  111. add data in vector database
  112. :param documents: list of texts to add
  113. :type documents: list[str]
  114. :param metadatas: list of metadata associated with docs
  115. :type metadatas: list[object]
  116. :param ids: ids of docs
  117. :type ids: list[str]
  118. """
  119. embeddings = self.embedder.embedding_fn(documents)
  120. for chunk in chunks(
  121. list(zip(ids, documents, metadatas, embeddings)),
  122. self.batch_size,
  123. desc="Inserting batches in elasticsearch",
  124. ): # noqa: E501
  125. ids, docs, metadatas, embeddings = [], [], [], []
  126. for id, text, metadata, embedding in chunk:
  127. ids.append(id)
  128. docs.append(text)
  129. metadatas.append(metadata)
  130. embeddings.append(embedding)
  131. batch_docs = []
  132. for id, text, metadata, embedding in zip(ids, docs, metadatas, embeddings):
  133. batch_docs.append(
  134. {
  135. "_index": self._get_index(),
  136. "_id": id,
  137. "_source": {"text": text, "metadata": metadata, "embeddings": embedding},
  138. }
  139. )
  140. bulk(self.client, batch_docs, **kwargs)
  141. self.client.indices.refresh(index=self._get_index())
  142. def query(
  143. self,
  144. input_query: str,
  145. n_results: int,
  146. where: dict[str, any],
  147. citations: bool = False,
  148. **kwargs: Optional[dict[str, Any]],
  149. ) -> Union[list[tuple[str, dict]], list[str]]:
  150. """
  151. query contents from vector database based on vector similarity
  152. :param input_query: query string
  153. :type input_query: str
  154. :param n_results: no of similar documents to fetch from database
  155. :type n_results: int
  156. :param where: Optional. to filter data
  157. :type where: dict[str, any]
  158. :return: The context of the document that matched your query, url of the source, doc_id
  159. :param citations: we use citations boolean param to return context along with the answer.
  160. :type citations: bool, default is False.
  161. :return: The content of the document that matched your query,
  162. along with url of the source and doc_id (if citations flag is true)
  163. :rtype: list[str], if citations=False, otherwise list[tuple[str, str, str]]
  164. """
  165. input_query_vector = self.embedder.embedding_fn([input_query])
  166. query_vector = input_query_vector[0]
  167. # `https://www.elastic.co/guide/en/elasticsearch/reference/7.17/query-dsl-script-score-query.html`
  168. query = {
  169. "script_score": {
  170. "query": {"bool": {"must": [{"exists": {"field": "text"}}]}},
  171. "script": {
  172. "source": "cosineSimilarity(params.input_query_vector, 'embeddings') + 1.0",
  173. "params": {"input_query_vector": query_vector},
  174. },
  175. }
  176. }
  177. if where:
  178. for key, value in where.items():
  179. query["script_score"]["query"]["bool"]["must"].append({"term": {f"metadata.{key}.keyword": value}})
  180. _source = ["text", "metadata"]
  181. response = self.client.search(index=self._get_index(), query=query, _source=_source, size=n_results)
  182. docs = response["hits"]["hits"]
  183. contexts = []
  184. for doc in docs:
  185. context = doc["_source"]["text"]
  186. if citations:
  187. metadata = doc["_source"]["metadata"]
  188. metadata["score"] = doc["_score"]
  189. contexts.append(tuple((context, metadata)))
  190. else:
  191. contexts.append(context)
  192. return contexts
  193. def set_collection_name(self, name: str):
  194. """
  195. Set the name of the collection. A collection is an isolated space for vectors.
  196. :param name: Name of the collection.
  197. :type name: str
  198. """
  199. if not isinstance(name, str):
  200. raise TypeError("Collection name must be a string")
  201. self.config.collection_name = name
  202. def count(self) -> int:
  203. """
  204. Count number of documents/chunks embedded in the database.
  205. :return: number of documents
  206. :rtype: int
  207. """
  208. query = {"match_all": {}}
  209. response = self.client.count(index=self._get_index(), query=query)
  210. doc_count = response["count"]
  211. return doc_count
  212. def reset(self):
  213. """
  214. Resets the database. Deletes all embeddings irreversibly.
  215. """
  216. # Delete all data from the database
  217. if self.client.indices.exists(index=self._get_index()):
  218. # delete index in Es
  219. self.client.indices.delete(index=self._get_index())
  220. def _get_index(self) -> str:
  221. """Get the Elasticsearch index for a collection
  222. :return: Elasticsearch index
  223. :rtype: str
  224. """
  225. # NOTE: The method is preferred to an attribute, because if collection name changes,
  226. # it's always up-to-date.
  227. return f"{self.config.collection_name}_{self.embedder.vector_dimension}".lower()
  228. def delete(self, where):
  229. """Delete documents from the database."""
  230. query = {"query": {"bool": {"must": []}}}
  231. for key, value in where.items():
  232. query["query"]["bool"]["must"].append({"term": {f"metadata.{key}.keyword": value}})
  233. self.client.delete_by_query(index=self._get_index(), body=query)
  234. self.client.indices.refresh(index=self._get_index())