zilliz.py 7.9 KB

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