elasticsearch.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. from typing import Dict, List, Optional, Set
  2. try:
  3. from elasticsearch import Elasticsearch
  4. from elasticsearch.helpers import bulk
  5. except ImportError:
  6. raise ImportError(
  7. "Elasticsearch requires extra dependencies. Install with `pip install --upgrade embedchain[elasticsearch]`"
  8. ) from None
  9. from embedchain.config import ElasticsearchDBConfig
  10. from embedchain.helper.json_serializable import register_deserializable
  11. from embedchain.vectordb.base import BaseVectorDB
  12. @register_deserializable
  13. class ElasticsearchDB(BaseVectorDB):
  14. """
  15. Elasticsearch as vector database
  16. """
  17. def __init__(
  18. self,
  19. config: Optional[ElasticsearchDBConfig] = None,
  20. es_config: Optional[ElasticsearchDBConfig] = None, # Backwards compatibility
  21. ):
  22. """Elasticsearch as vector database.
  23. :param config: Elasticsearch database config, defaults to None
  24. :type config: ElasticsearchDBConfig, optional
  25. :param es_config: `es_config` is supported as an alias for `config` (for backwards compatibility),
  26. defaults to None
  27. :type es_config: ElasticsearchDBConfig, optional
  28. :raises ValueError: No config provided
  29. """
  30. if config is None and es_config is None:
  31. raise ValueError("ElasticsearchDBConfig is required")
  32. self.config = config or es_config
  33. self.client = Elasticsearch(es_config.ES_URL, **es_config.ES_EXTRA_PARAMS)
  34. # Call parent init here because embedder is needed
  35. super().__init__(config=self.config)
  36. def _initialize(self):
  37. """
  38. This method is needed because `embedder` attribute needs to be set externally before it can be initialized.
  39. """
  40. index_settings = {
  41. "mappings": {
  42. "properties": {
  43. "text": {"type": "text"},
  44. "embeddings": {"type": "dense_vector", "index": False, "dims": self.embedder.vector_dimension},
  45. }
  46. }
  47. }
  48. es_index = self._get_index()
  49. if not self.client.indices.exists(index=es_index):
  50. # create index if not exist
  51. print("Creating index", es_index, index_settings)
  52. self.client.indices.create(index=es_index, body=index_settings)
  53. def _get_or_create_db(self):
  54. """Called during initialization"""
  55. return self.client
  56. def _get_or_create_collection(self, name):
  57. """Note: nothing to return here. Discuss later"""
  58. def get(self, ids: List[str], where: Dict[str, any]) -> Set[str]:
  59. """
  60. Get existing doc ids present in vector database
  61. :param ids: _list of doc ids to check for existance
  62. :type ids: List[str]
  63. :param where: to filter data
  64. :type where: Dict[str, any]
  65. :return: ids
  66. :rtype: Set[str]
  67. """
  68. query = {"bool": {"must": [{"ids": {"values": ids}}]}}
  69. if "app_id" in where:
  70. app_id = where["app_id"]
  71. query["bool"]["must"].append({"term": {"metadata.app_id": app_id}})
  72. response = self.client.search(index=self.es_index, query=query, _source=False)
  73. docs = response["hits"]["hits"]
  74. ids = [doc["_id"] for doc in docs]
  75. return set(ids)
  76. def add(self, documents: List[str], metadatas: List[object], ids: List[str]):
  77. """add data in vector database
  78. :param documents: list of texts to add
  79. :type documents: List[str]
  80. :param metadatas: list of metadata associated with docs
  81. :type metadatas: List[object]
  82. :param ids: ids of docs
  83. :type ids: List[str]
  84. """
  85. docs = []
  86. embeddings = self.embedder.embedding_fn(documents)
  87. for id, text, metadata, embeddings in zip(ids, documents, metadatas, embeddings):
  88. docs.append(
  89. {
  90. "_index": self._get_index(),
  91. "_id": id,
  92. "_source": {"text": text, "metadata": metadata, "embeddings": embeddings},
  93. }
  94. )
  95. bulk(self.client, docs)
  96. self.client.indices.refresh(index=self._get_index())
  97. def query(self, input_query: List[str], n_results: int, where: Dict[str, any]) -> List[str]:
  98. """
  99. query contents from vector data base based on vector similarity
  100. :param input_query: list of query string
  101. :type input_query: List[str]
  102. :param n_results: no of similar documents to fetch from database
  103. :type n_results: int
  104. :param where: Optional. to filter data
  105. :type where: Dict[str, any]
  106. :return: Database contents that are the result of the query
  107. :rtype: List[str]
  108. """
  109. input_query_vector = self.embedder.embedding_fn(input_query)
  110. query_vector = input_query_vector[0]
  111. query = {
  112. "script_score": {
  113. "query": {"bool": {"must": [{"exists": {"field": "text"}}]}},
  114. "script": {
  115. "source": "cosineSimilarity(params.input_query_vector, 'embeddings') + 1.0",
  116. "params": {"input_query_vector": query_vector},
  117. },
  118. }
  119. }
  120. if "app_id" in where:
  121. app_id = where["app_id"]
  122. query["script_score"]["query"]["bool"]["must"] = [{"term": {"metadata.app_id": app_id}}]
  123. _source = ["text"]
  124. response = self.client.search(index=self._get_index(), query=query, _source=_source, size=n_results)
  125. docs = response["hits"]["hits"]
  126. contents = [doc["_source"]["text"] for doc in docs]
  127. return contents
  128. def set_collection_name(self, name: str):
  129. """
  130. Set the name of the collection. A collection is an isolated space for vectors.
  131. :param name: Name of the collection.
  132. :type name: str
  133. """
  134. self.config.collection_name = name
  135. def count(self) -> int:
  136. """
  137. Count number of documents/chunks embedded in the database.
  138. :return: number of documents
  139. :rtype: int
  140. """
  141. query = {"match_all": {}}
  142. response = self.client.count(index=self._get_index(), query=query)
  143. doc_count = response["count"]
  144. return doc_count
  145. def reset(self):
  146. """
  147. Resets the database. Deletes all embeddings irreversibly.
  148. """
  149. # Delete all data from the database
  150. if self.client.indices.exists(index=self._get_index()):
  151. # delete index in Es
  152. self.client.indices.delete(index=self._get_index())
  153. def _get_index(self) -> str:
  154. """Get the Elasticsearch index for a collection
  155. :return: Elasticsearch index
  156. :rtype: str
  157. """
  158. # NOTE: The method is preferred to an attribute, because if collection name changes,
  159. # it's always up-to-date.
  160. return f"{self.config.collection_name}_{self.embedder.vector_dimension}"