elasticsearch.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. import logging
  2. from typing import Dict, List, Optional, Set
  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(
  67. self, ids: Optional[List[str]] = None, where: Optional[Dict[str, any]] = None, limit: Optional[int] = None
  68. ) -> Set[str]:
  69. """
  70. Get existing doc ids present in vector database
  71. :param ids: _list of doc ids to check for existance
  72. :type ids: List[str]
  73. :param where: to filter data
  74. :type where: Dict[str, any]
  75. :return: ids
  76. :rtype: Set[str]
  77. """
  78. if ids:
  79. query = {"bool": {"must": [{"ids": {"values": ids}}]}}
  80. else:
  81. query = {"bool": {"must": []}}
  82. if "app_id" in where:
  83. app_id = where["app_id"]
  84. query["bool"]["must"].append({"term": {"metadata.app_id": app_id}})
  85. response = self.client.search(index=self._get_index(), query=query, _source=False, size=limit)
  86. docs = response["hits"]["hits"]
  87. ids = [doc["_id"] for doc in docs]
  88. return {"ids": set(ids)}
  89. def add(self, documents: List[str], metadatas: List[object], ids: List[str]):
  90. """add data in vector database
  91. :param documents: list of texts to add
  92. :type documents: List[str]
  93. :param metadatas: list of metadata associated with docs
  94. :type metadatas: List[object]
  95. :param ids: ids of docs
  96. :type ids: List[str]
  97. """
  98. docs = []
  99. embeddings = self.embedder.embedding_fn(documents)
  100. for id, text, metadata, embeddings in zip(ids, documents, metadatas, embeddings):
  101. docs.append(
  102. {
  103. "_index": self._get_index(),
  104. "_id": id,
  105. "_source": {"text": text, "metadata": metadata, "embeddings": embeddings},
  106. }
  107. )
  108. bulk(self.client, docs)
  109. self.client.indices.refresh(index=self._get_index())
  110. def query(self, input_query: List[str], n_results: int, where: Dict[str, any]) -> List[str]:
  111. """
  112. query contents from vector data base based on vector similarity
  113. :param input_query: list of query string
  114. :type input_query: List[str]
  115. :param n_results: no of similar documents to fetch from database
  116. :type n_results: int
  117. :param where: Optional. to filter data
  118. :type where: Dict[str, any]
  119. :return: Database contents that are the result of the query
  120. :rtype: List[str]
  121. """
  122. input_query_vector = self.embedder.embedding_fn(input_query)
  123. query_vector = input_query_vector[0]
  124. query = {
  125. "script_score": {
  126. "query": {"bool": {"must": [{"exists": {"field": "text"}}]}},
  127. "script": {
  128. "source": "cosineSimilarity(params.input_query_vector, 'embeddings') + 1.0",
  129. "params": {"input_query_vector": query_vector},
  130. },
  131. }
  132. }
  133. if "app_id" in where:
  134. app_id = where["app_id"]
  135. query["script_score"]["query"]["bool"]["must"] = [{"term": {"metadata.app_id": app_id}}]
  136. _source = ["text"]
  137. response = self.client.search(index=self._get_index(), query=query, _source=_source, size=n_results)
  138. docs = response["hits"]["hits"]
  139. contents = [doc["_source"]["text"] for doc in docs]
  140. return contents
  141. def set_collection_name(self, name: str):
  142. """
  143. Set the name of the collection. A collection is an isolated space for vectors.
  144. :param name: Name of the collection.
  145. :type name: str
  146. """
  147. if not isinstance(name, str):
  148. raise TypeError("Collection name must be a string")
  149. self.config.collection_name = name
  150. def count(self) -> int:
  151. """
  152. Count number of documents/chunks embedded in the database.
  153. :return: number of documents
  154. :rtype: int
  155. """
  156. query = {"match_all": {}}
  157. response = self.client.count(index=self._get_index(), query=query)
  158. doc_count = response["count"]
  159. return doc_count
  160. def reset(self):
  161. """
  162. Resets the database. Deletes all embeddings irreversibly.
  163. """
  164. # Delete all data from the database
  165. if self.client.indices.exists(index=self._get_index()):
  166. # delete index in Es
  167. self.client.indices.delete(index=self._get_index())
  168. def _get_index(self) -> str:
  169. """Get the Elasticsearch index for a collection
  170. :return: Elasticsearch index
  171. :rtype: str
  172. """
  173. # NOTE: The method is preferred to an attribute, because if collection name changes,
  174. # it's always up-to-date.
  175. return f"{self.config.collection_name}_{self.embedder.vector_dimension}".lower()