zilliz.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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 (
  8. Collection,
  9. CollectionSchema,
  10. DataType,
  11. FieldSchema,
  12. MilvusClient,
  13. connections,
  14. utility,
  15. )
  16. except ImportError:
  17. raise ImportError(
  18. "Zilliz requires extra dependencies. Install with `pip install --upgrade embedchain[milvus]`"
  19. ) from None
  20. @register_deserializable
  21. class ZillizVectorDB(BaseVectorDB):
  22. """Base class for vector database."""
  23. def __init__(self, config: ZillizDBConfig = None):
  24. """Initialize the database. Save the config and client as an attribute.
  25. :param config: Database configuration class instance.
  26. :type config: ZillizDBConfig
  27. """
  28. if config is None:
  29. self.config = ZillizDBConfig()
  30. else:
  31. self.config = config
  32. self.client = MilvusClient(
  33. uri=self.config.uri,
  34. token=self.config.token,
  35. )
  36. self.connection = connections.connect(
  37. uri=self.config.uri,
  38. token=self.config.token,
  39. )
  40. super().__init__(config=self.config)
  41. def _initialize(self):
  42. """
  43. This method is needed because `embedder` attribute needs to be set externally before it can be initialized.
  44. So it's can't be done in __init__ in one step.
  45. """
  46. self._get_or_create_collection(self.config.collection_name)
  47. def _get_or_create_db(self):
  48. """Get or create the database."""
  49. return self.client
  50. def _get_or_create_collection(self, name):
  51. """
  52. Get or create a named collection.
  53. :param name: Name of the collection
  54. :type name: str
  55. """
  56. if utility.has_collection(name):
  57. logging.info(f"[ZillizDB]: found an existing collection {name}, make sure the auto-id is disabled.")
  58. self.collection = Collection(name)
  59. else:
  60. fields = [
  61. FieldSchema(name="id", dtype=DataType.VARCHAR, is_primary=True, max_length=512),
  62. FieldSchema(name="text", dtype=DataType.VARCHAR, max_length=2048),
  63. FieldSchema(name="embeddings", dtype=DataType.FLOAT_VECTOR, dim=self.embedder.vector_dimension),
  64. ]
  65. schema = CollectionSchema(fields, enable_dynamic_field=True)
  66. self.collection = Collection(name=name, schema=schema)
  67. index = {
  68. "index_type": "AUTOINDEX",
  69. "metric_type": self.config.metric_type,
  70. }
  71. self.collection.create_index("embeddings", index)
  72. return self.collection
  73. def get(self, ids: Optional[list[str]] = None, where: Optional[dict[str, any]] = None, limit: Optional[int] = None):
  74. """
  75. Get existing doc ids present in vector database
  76. :param ids: list of doc ids to check for existence
  77. :type ids: list[str]
  78. :param where: Optional. to filter data
  79. :type where: dict[str, Any]
  80. :param limit: Optional. maximum number of documents
  81. :type limit: Optional[int]
  82. :return: Existing documents.
  83. :rtype: Set[str]
  84. """
  85. if ids is None or len(ids) == 0 or self.collection.num_entities == 0:
  86. return {"ids": []}
  87. if not self.collection.is_empty:
  88. filter_ = f"id in {ids}"
  89. results = self.client.query(
  90. collection_name=self.config.collection_name, filter=filter_, output_fields=["id"]
  91. )
  92. results = [res["id"] for res in results]
  93. return {"ids": set(results)}
  94. def add(
  95. self,
  96. embeddings: list[list[float]],
  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 = {**metadata, "id": id, "text": doc, "embeddings": embedding}
  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: str
  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. if not isinstance(where, str):
  136. where = None
  137. output_fields = ["*"]
  138. input_query_vector = self.embedder.embedding_fn([input_query])
  139. query_vector = input_query_vector[0]
  140. query_result = self.client.search(
  141. collection_name=self.config.collection_name,
  142. data=[query_vector],
  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 "embeddings" in data:
  154. data.pop("embeddings")
  155. if citations:
  156. data["score"] = score
  157. contexts.append(tuple((context, data)))
  158. else:
  159. contexts.append(context)
  160. return contexts
  161. def count(self) -> int:
  162. """
  163. Count number of documents/chunks embedded in the database.
  164. :return: number of documents
  165. :rtype: int
  166. """
  167. return self.collection.num_entities
  168. def reset(self, collection_names: list[str] = None):
  169. """
  170. Resets the database. Deletes all embeddings irreversibly.
  171. """
  172. if self.config.collection_name:
  173. if collection_names:
  174. for collection_name in collection_names:
  175. if collection_name in self.client.list_collections():
  176. self.client.drop_collection(collection_name=collection_name)
  177. else:
  178. self.client.drop_collection(collection_name=self.config.collection_name)
  179. self._get_or_create_collection(self.config.collection_name)
  180. def set_collection_name(self, name: str):
  181. """
  182. Set the name of the collection. A collection is an isolated space for vectors.
  183. :param name: Name of the collection.
  184. :type name: str
  185. """
  186. if not isinstance(name, str):
  187. raise TypeError("Collection name must be a string")
  188. self.config.collection_name = name
  189. def delete(self, keys: Union[list, str, int]):
  190. """
  191. Delete the embeddings from DB. Zilliz only support deleting with keys.
  192. :param keys: Primary keys of the table entries to delete.
  193. :type keys: Union[list, str, int]
  194. """
  195. self.client.delete(
  196. collection_name=self.config.collection_name,
  197. pks=keys,
  198. )