elasticsearch_db.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. from typing import Any, Dict, List
  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 embedchain[elasticsearch]`"
  8. ) from None
  9. from embedchain.config import ElasticsearchDBConfig
  10. from embedchain.helper_classes.json_serializable import register_deserializable
  11. from embedchain.vectordb.base_vector_db import BaseVectorDB
  12. @register_deserializable
  13. class ElasticsearchDB(BaseVectorDB):
  14. def __init__(
  15. self,
  16. config: ElasticsearchDBConfig = None,
  17. es_config: ElasticsearchDBConfig = None, # Backwards compatibility
  18. ):
  19. """
  20. Elasticsearch as vector database
  21. :param es_config. elasticsearch database config to be used for connection
  22. :param embedding_fn: Function to generate embedding vectors.
  23. :param vector_dim: Vector dimension generated by embedding fn
  24. """
  25. if config is None and es_config is None:
  26. raise ValueError("ElasticsearchDBConfig is required")
  27. self.config = config or es_config
  28. self.client = Elasticsearch(es_config.ES_URL, **es_config.ES_EXTRA_PARAMS)
  29. # Call parent init here because embedder is needed
  30. super().__init__(config=self.config)
  31. def _initialize(self):
  32. """
  33. This method is needed because `embedder` attribute needs to be set externally before it can be initialized.
  34. """
  35. index_settings = {
  36. "mappings": {
  37. "properties": {
  38. "text": {"type": "text"},
  39. "embeddings": {"type": "dense_vector", "index": False, "dims": self.embedder.vector_dimension},
  40. }
  41. }
  42. }
  43. es_index = self._get_index()
  44. if not self.client.indices.exists(index=es_index):
  45. # create index if not exist
  46. print("Creating index", es_index, index_settings)
  47. self.client.indices.create(index=es_index, body=index_settings)
  48. def _get_or_create_db(self):
  49. return self.client
  50. def _get_or_create_collection(self, name):
  51. """Note: nothing to return here. Discuss later"""
  52. def get(self, ids: List[str], where: Dict[str, any]) -> List[str]:
  53. """
  54. Get existing doc ids present in vector database
  55. :param ids: list of doc ids to check for existance
  56. :param where: Optional. to filter data
  57. """
  58. query = {"bool": {"must": [{"ids": {"values": ids}}]}}
  59. if "app_id" in where:
  60. app_id = where["app_id"]
  61. query["bool"]["must"].append({"term": {"metadata.app_id": app_id}})
  62. response = self.client.search(index=self.es_index, query=query, _source=False)
  63. docs = response["hits"]["hits"]
  64. ids = [doc["_id"] for doc in docs]
  65. return set(ids)
  66. def add(self, documents: List[str], metadatas: List[object], ids: List[str]) -> Any:
  67. """
  68. add data in vector database
  69. :param documents: list of texts to add
  70. :param metadatas: list of metadata associated with docs
  71. :param ids: ids of docs
  72. """
  73. docs = []
  74. embeddings = self.config.embedding_fn(documents)
  75. for id, text, metadata, embeddings in zip(ids, documents, metadatas, embeddings):
  76. docs.append(
  77. {
  78. "_index": self._get_index(),
  79. "_id": id,
  80. "_source": {"text": text, "metadata": metadata, "embeddings": embeddings},
  81. }
  82. )
  83. bulk(self.client, docs)
  84. self.client.indices.refresh(index=self._get_index())
  85. return
  86. def query(self, input_query: List[str], n_results: int, where: Dict[str, any]) -> List[str]:
  87. """
  88. query contents from vector data base based on vector similarity
  89. :param input_query: list of query string
  90. :param n_results: no of similar documents to fetch from database
  91. :param where: Optional. to filter data
  92. """
  93. input_query_vector = self.config.embedding_fn(input_query)
  94. query_vector = input_query_vector[0]
  95. query = {
  96. "script_score": {
  97. "query": {"bool": {"must": [{"exists": {"field": "text"}}]}},
  98. "script": {
  99. "source": "cosineSimilarity(params.input_query_vector, 'embeddings') + 1.0",
  100. "params": {"input_query_vector": query_vector},
  101. },
  102. }
  103. }
  104. if "app_id" in where:
  105. app_id = where["app_id"]
  106. query["script_score"]["query"]["bool"]["must"] = [{"term": {"metadata.app_id": app_id}}]
  107. _source = ["text"]
  108. response = self.client.search(index=self._get_index(), query=query, _source=_source, size=n_results)
  109. docs = response["hits"]["hits"]
  110. contents = [doc["_source"]["text"] for doc in docs]
  111. return contents
  112. def set_collection_name(self, name: str):
  113. self.config.collection_name = name
  114. def count(self) -> int:
  115. query = {"match_all": {}}
  116. response = self.client.count(index=self.es_index, query=query)
  117. doc_count = response["count"]
  118. return doc_count
  119. def reset(self):
  120. # Delete all data from the database
  121. if self.client.indices.exists(index=self.es_index):
  122. # delete index in Es
  123. self.client.indices.delete(index=self.es_index)
  124. def _get_index(self):
  125. # NOTE: The method is preferred to an attribute, because if collection name changes,
  126. # it's always up-to-date.
  127. return f"{self.config.collection_name}_{self.config.vector_dim}"