elasticsearch.py 10 KB

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