elasticsearch.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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.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. **kwargs: Optional[Dict[str, any]],
  95. ) -> Any:
  96. """
  97. add data in vector database
  98. :param embeddings: list of embeddings to add
  99. :type embeddings: List[List[str]]
  100. :param documents: list of texts to add
  101. :type documents: List[str]
  102. :param metadatas: list of metadata associated with docs
  103. :type metadatas: List[object]
  104. :param ids: ids of docs
  105. :type ids: List[str]
  106. :param skip_embedding: Optional. If True, then the input_query is assumed to be already embedded.
  107. :type skip_embedding: bool
  108. """
  109. docs = []
  110. if not skip_embedding:
  111. embeddings = self.embedder.embedding_fn(documents)
  112. for id, text, metadata, embeddings in zip(ids, documents, metadatas, embeddings):
  113. docs.append(
  114. {
  115. "_index": self._get_index(),
  116. "_id": id,
  117. "_source": {"text": text, "metadata": metadata, "embeddings": embeddings},
  118. }
  119. )
  120. bulk(self.client, docs)
  121. self.client.indices.refresh(index=self._get_index())
  122. def query(
  123. self,
  124. input_query: List[str],
  125. n_results: int,
  126. where: Dict[str, any],
  127. skip_embedding: bool,
  128. citations: bool = False,
  129. **kwargs: Optional[Dict[str, Any]],
  130. ) -> Union[List[Tuple[str, str, str]], List[str]]:
  131. """
  132. query contents from vector data base based on vector similarity
  133. :param input_query: list of query string
  134. :type input_query: List[str]
  135. :param n_results: no of similar documents to fetch from database
  136. :type n_results: int
  137. :param where: Optional. to filter data
  138. :type where: Dict[str, any]
  139. :param skip_embedding: Optional. If True, then the input_query is assumed to be already embedded.
  140. :type skip_embedding: bool
  141. :return: The context of the document that matched your query, url of the source, doc_id
  142. :param citations: we use citations boolean param to return context along with the answer.
  143. :type citations: bool, default is False.
  144. :return: The content of the document that matched your query,
  145. along with url of the source and doc_id (if citations flag is true)
  146. :rtype: List[str], if citations=False, otherwise List[Tuple[str, str, str]]
  147. """
  148. if skip_embedding:
  149. query_vector = input_query
  150. else:
  151. input_query_vector = self.embedder.embedding_fn(input_query)
  152. query_vector = input_query_vector[0]
  153. # `https://www.elastic.co/guide/en/elasticsearch/reference/7.17/query-dsl-script-score-query.html`
  154. query = {
  155. "script_score": {
  156. "query": {"bool": {"must": [{"exists": {"field": "text"}}]}},
  157. "script": {
  158. "source": "cosineSimilarity(params.input_query_vector, 'embeddings') + 1.0",
  159. "params": {"input_query_vector": query_vector},
  160. },
  161. }
  162. }
  163. if "app_id" in where:
  164. app_id = where["app_id"]
  165. query["script_score"]["query"] = {"match": {"metadata.app_id": app_id}}
  166. _source = ["text", "metadata.url", "metadata.doc_id"]
  167. response = self.client.search(index=self._get_index(), query=query, _source=_source, size=n_results)
  168. docs = response["hits"]["hits"]
  169. contexts = []
  170. for doc in docs:
  171. context = doc["_source"]["text"]
  172. if citations:
  173. metadata = doc["_source"]["metadata"]
  174. source = metadata["url"]
  175. doc_id = metadata["doc_id"]
  176. contexts.append(tuple((context, source, doc_id)))
  177. else:
  178. contexts.append(context)
  179. return contexts
  180. def set_collection_name(self, name: str):
  181. """
  182. Set the name of the collection. A collection is an isolated space for vectors.
  183. :param name: Name of the collection.
  184. :type name: str
  185. """
  186. if not isinstance(name, str):
  187. raise TypeError("Collection name must be a string")
  188. self.config.collection_name = name
  189. def count(self) -> int:
  190. """
  191. Count number of documents/chunks embedded in the database.
  192. :return: number of documents
  193. :rtype: int
  194. """
  195. query = {"match_all": {}}
  196. response = self.client.count(index=self._get_index(), query=query)
  197. doc_count = response["count"]
  198. return doc_count
  199. def reset(self):
  200. """
  201. Resets the database. Deletes all embeddings irreversibly.
  202. """
  203. # Delete all data from the database
  204. if self.client.indices.exists(index=self._get_index()):
  205. # delete index in Es
  206. self.client.indices.delete(index=self._get_index())
  207. def _get_index(self) -> str:
  208. """Get the Elasticsearch index for a collection
  209. :return: Elasticsearch index
  210. :rtype: str
  211. """
  212. # NOTE: The method is preferred to an attribute, because if collection name changes,
  213. # it's always up-to-date.
  214. return f"{self.config.collection_name}_{self.embedder.vector_dimension}".lower()