zilliz.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. import logging
  2. from typing import Any, Optional, Union
  3. from embedchain.config import ZillizDBConfig
  4. from embedchain.helpers.json_serializable import register_deserializable
  5. from embedchain.vectordb.base import BaseVectorDB
  6. try:
  7. from pymilvus import (Collection, CollectionSchema, DataType, FieldSchema,
  8. MilvusClient, connections, utility)
  9. except ImportError:
  10. raise ImportError(
  11. "Zilliz requires extra dependencies. Install with `pip install --upgrade embedchain[milvus]`"
  12. ) from None
  13. @register_deserializable
  14. class ZillizVectorDB(BaseVectorDB):
  15. """Base class for vector database."""
  16. def __init__(self, config: ZillizDBConfig = None):
  17. """Initialize the database. Save the config and client as an attribute.
  18. :param config: Database configuration class instance.
  19. :type config: ZillizDBConfig
  20. """
  21. if config is None:
  22. self.config = ZillizDBConfig()
  23. else:
  24. self.config = config
  25. self.client = MilvusClient(
  26. uri=self.config.uri,
  27. token=self.config.token,
  28. )
  29. self.connection = connections.connect(
  30. uri=self.config.uri,
  31. token=self.config.token,
  32. )
  33. super().__init__(config=self.config)
  34. def _initialize(self):
  35. """
  36. This method is needed because `embedder` attribute needs to be set externally before it can be initialized.
  37. So it's can't be done in __init__ in one step.
  38. """
  39. self._get_or_create_collection(self.config.collection_name)
  40. def _get_or_create_db(self):
  41. """Get or create the database."""
  42. return self.client
  43. def _get_or_create_collection(self, name):
  44. """
  45. Get or create a named collection.
  46. :param name: Name of the collection
  47. :type name: str
  48. """
  49. if utility.has_collection(name):
  50. logging.info(f"[ZillizDB]: found an existing collection {name}, make sure the auto-id is disabled.")
  51. self.collection = Collection(name)
  52. else:
  53. fields = [
  54. FieldSchema(name="id", dtype=DataType.VARCHAR, is_primary=True, max_length=512),
  55. FieldSchema(name="text", dtype=DataType.VARCHAR, max_length=2048),
  56. FieldSchema(name="embeddings", dtype=DataType.FLOAT_VECTOR, dim=self.embedder.vector_dimension),
  57. FieldSchema(name="metadata", dtype=DataType.JSON),
  58. ]
  59. schema = CollectionSchema(fields, enable_dynamic_field=True)
  60. self.collection = Collection(name=name, schema=schema)
  61. index = {
  62. "index_type": "AUTOINDEX",
  63. "metric_type": self.config.metric_type,
  64. }
  65. self.collection.create_index("embeddings", index)
  66. return self.collection
  67. def get(self, ids: Optional[list[str]] = None, where: Optional[dict[str, any]] = None, limit: Optional[int] = None):
  68. """
  69. Get existing doc ids present in vector database
  70. :param ids: list of doc ids to check for existence
  71. :type ids: list[str]
  72. :param where: Optional. to filter data
  73. :type where: dict[str, Any]
  74. :param limit: Optional. maximum number of documents
  75. :type limit: Optional[int]
  76. :return: Existing documents.
  77. :rtype: Set[str]
  78. """
  79. data_ids = []
  80. metadatas = []
  81. if self.collection.num_entities == 0 or self.collection.is_empty:
  82. return {"ids": data_ids, "metadatas": metadatas}
  83. filter_ = ""
  84. if ids:
  85. filter_ = f'id in "{ids}"'
  86. if where:
  87. if filter_:
  88. filter_ += " and "
  89. filter_ = f"{self._generate_zilliz_filter(where)}"
  90. results = self.client.query(collection_name=self.config.collection_name, filter=filter_, output_fields=["*"])
  91. for res in results:
  92. data_ids.append(res.get("id"))
  93. metadatas.append(res.get("metadata", {}))
  94. return {"ids": data_ids, "metadatas": metadatas}
  95. def add(
  96. self,
  97. documents: list[str],
  98. metadatas: list[object],
  99. ids: list[str],
  100. **kwargs: Optional[dict[str, any]],
  101. ):
  102. """Add to database"""
  103. embeddings = self.embedder.embedding_fn(documents)
  104. for id, doc, metadata, embedding in zip(ids, documents, metadatas, embeddings):
  105. data = {"id": id, "text": doc, "embeddings": embedding, "metadata": metadata}
  106. self.client.insert(collection_name=self.config.collection_name, data=data, **kwargs)
  107. self.collection.load()
  108. self.collection.flush()
  109. self.client.flush(self.config.collection_name)
  110. def query(
  111. self,
  112. input_query: list[str],
  113. n_results: int,
  114. where: dict[str, Any],
  115. citations: bool = False,
  116. **kwargs: Optional[dict[str, Any]],
  117. ) -> Union[list[tuple[str, dict]], list[str]]:
  118. """
  119. Query contents from vector database based on vector similarity
  120. :param input_query: list of query string
  121. :type input_query: list[str]
  122. :param n_results: no of similar documents to fetch from database
  123. :type n_results: int
  124. :param where: to filter data
  125. :type where: dict[str, Any]
  126. :raises InvalidDimensionException: Dimensions do not match.
  127. :param citations: we use citations boolean param to return context along with the answer.
  128. :type citations: bool, default is False.
  129. :return: The content of the document that matched your query,
  130. along with url of the source and doc_id (if citations flag is true)
  131. :rtype: list[str], if citations=False, otherwise list[tuple[str, str, str]]
  132. """
  133. if self.collection.is_empty:
  134. return []
  135. output_fields = ["*"]
  136. input_query_vector = self.embedder.embedding_fn([input_query])
  137. query_vector = input_query_vector[0]
  138. query_filter = self._generate_zilliz_filter(where)
  139. query_result = self.client.search(
  140. collection_name=self.config.collection_name,
  141. data=[query_vector],
  142. filter=query_filter,
  143. limit=n_results,
  144. output_fields=output_fields,
  145. **kwargs,
  146. )
  147. query_result = query_result[0]
  148. contexts = []
  149. for query in query_result:
  150. data = query["entity"]
  151. score = query["distance"]
  152. context = data["text"]
  153. if citations:
  154. metadata = data.get("metadata", {})
  155. metadata["score"] = score
  156. contexts.append(tuple((context, metadata)))
  157. else:
  158. contexts.append(context)
  159. return contexts
  160. def count(self) -> int:
  161. """
  162. Count number of documents/chunks embedded in the database.
  163. :return: number of documents
  164. :rtype: int
  165. """
  166. return self.collection.num_entities
  167. def reset(self, collection_names: list[str] = None):
  168. """
  169. Resets the database. Deletes all embeddings irreversibly.
  170. """
  171. if self.config.collection_name:
  172. if collection_names:
  173. for collection_name in collection_names:
  174. if collection_name in self.client.list_collections():
  175. self.client.drop_collection(collection_name=collection_name)
  176. else:
  177. self.client.drop_collection(collection_name=self.config.collection_name)
  178. self._get_or_create_collection(self.config.collection_name)
  179. def set_collection_name(self, name: str):
  180. """
  181. Set the name of the collection. A collection is an isolated space for vectors.
  182. :param name: Name of the collection.
  183. :type name: str
  184. """
  185. if not isinstance(name, str):
  186. raise TypeError("Collection name must be a string")
  187. self.config.collection_name = name
  188. def _generate_zilliz_filter(self, where: dict[str, str]):
  189. operands = []
  190. for key, value in where.items():
  191. operands.append(f'(metadata["{key}"] == "{value}")')
  192. return " and ".join(operands)
  193. def delete(self, where: dict[str, Any]):
  194. """
  195. Delete the embeddings from DB. Zilliz only support deleting with keys.
  196. :param keys: Primary keys of the table entries to delete.
  197. :type keys: Union[list, str, int]
  198. """
  199. data = self.get(where=where)
  200. keys = data.get("ids", [])
  201. if keys:
  202. self.client.delete(collection_name=self.config.collection_name, pks=keys)