elasticsearch.py 9.1 KB

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