elasticsearch_db.py 5.6 KB

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