vector_store.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. """
  2. Milvus Lite 存储封装
  3. 单一存储架构,存储完整知识数据 + 向量。
  4. """
  5. from milvus import default_server
  6. from pymilvus import (
  7. connections, Collection, FieldSchema,
  8. CollectionSchema, DataType, utility
  9. )
  10. from typing import List, Dict, Optional
  11. import json
  12. import time
  13. class MilvusStore:
  14. def __init__(self, data_dir: str = "./milvus_data"):
  15. """
  16. 初始化 Milvus Lite 存储
  17. Args:
  18. data_dir: 数据存储目录
  19. """
  20. # 启动内嵌服务器
  21. default_server.set_base_dir(data_dir)
  22. # 检查是否已经有 Milvus 实例在运行
  23. try:
  24. # 尝试连接到可能已存在的实例
  25. connections.connect(
  26. alias="default",
  27. host='127.0.0.1',
  28. port=default_server.listen_port,
  29. timeout=5
  30. )
  31. print(f"[Milvus] 连接到已存在的 Milvus 实例 (端口 {default_server.listen_port})")
  32. except Exception:
  33. # 没有运行的实例,启动新的
  34. print(f"[Milvus] 启动新的 Milvus Lite 实例...")
  35. try:
  36. default_server.start()
  37. print(f"[Milvus] Milvus Lite 启动成功 (端口 {default_server.listen_port})")
  38. except Exception as e:
  39. print(f"[Milvus] 启动失败: {e}")
  40. # 尝试连接到可能已经在运行的实例
  41. try:
  42. connections.connect(
  43. alias="default",
  44. host='127.0.0.1',
  45. port=default_server.listen_port,
  46. timeout=5
  47. )
  48. print(f"[Milvus] 连接到已存在的实例")
  49. except Exception as e2:
  50. raise RuntimeError(f"无法启动或连接到 Milvus: {e}, {e2}")
  51. self._init_collection()
  52. def _init_collection(self):
  53. """初始化 collection"""
  54. collection_name = "knowledge"
  55. if utility.has_collection(collection_name):
  56. self.collection = Collection(collection_name)
  57. else:
  58. # 定义 schema
  59. fields = [
  60. FieldSchema(name="id", dtype=DataType.VARCHAR,
  61. max_length=100, is_primary=True),
  62. FieldSchema(name="embedding", dtype=DataType.FLOAT_VECTOR,
  63. dim=1536),
  64. FieldSchema(name="message_id", dtype=DataType.VARCHAR,
  65. max_length=100),
  66. FieldSchema(name="task", dtype=DataType.VARCHAR,
  67. max_length=2000),
  68. FieldSchema(name="content", dtype=DataType.VARCHAR,
  69. max_length=50000),
  70. FieldSchema(name="types", dtype=DataType.JSON),
  71. FieldSchema(name="tags", dtype=DataType.JSON),
  72. FieldSchema(name="scopes", dtype=DataType.JSON),
  73. FieldSchema(name="owner", dtype=DataType.VARCHAR,
  74. max_length=200),
  75. FieldSchema(name="resource_ids", dtype=DataType.JSON),
  76. FieldSchema(name="source", dtype=DataType.JSON),
  77. FieldSchema(name="eval", dtype=DataType.JSON),
  78. FieldSchema(name="created_at", dtype=DataType.INT64),
  79. FieldSchema(name="updated_at", dtype=DataType.INT64),
  80. ]
  81. schema = CollectionSchema(fields, description="KnowHub Knowledge")
  82. self.collection = Collection(collection_name, schema)
  83. # 创建向量索引
  84. index_params = {
  85. "metric_type": "COSINE",
  86. "index_type": "HNSW",
  87. "params": {"M": 16, "efConstruction": 200}
  88. }
  89. self.collection.create_index("embedding", index_params)
  90. self.collection.load()
  91. def insert(self, knowledge: Dict):
  92. """
  93. 插入单条知识
  94. Args:
  95. knowledge: 知识数据(包含 embedding)
  96. """
  97. self.collection.insert([knowledge])
  98. self.collection.flush()
  99. def insert_batch(self, knowledge_list: List[Dict]):
  100. """
  101. 批量插入知识
  102. Args:
  103. knowledge_list: 知识列表
  104. """
  105. if not knowledge_list:
  106. return
  107. self.collection.insert(knowledge_list)
  108. self.collection.flush()
  109. def search(self,
  110. query_embedding: List[float],
  111. filters: Optional[str] = None,
  112. limit: int = 10) -> List[Dict]:
  113. """
  114. 向量检索 + 标量过滤
  115. Args:
  116. query_embedding: 查询向量
  117. filters: 过滤表达式(如: 'owner == "agent"')
  118. limit: 返回数量
  119. Returns:
  120. 知识列表
  121. """
  122. search_params = {"metric_type": "COSINE", "params": {"ef": 100}}
  123. results = self.collection.search(
  124. data=[query_embedding],
  125. anns_field="embedding",
  126. param=search_params,
  127. limit=limit,
  128. expr=filters,
  129. output_fields=["id", "message_id", "task", "content", "types",
  130. "tags", "scopes", "owner", "resource_ids",
  131. "source", "eval", "created_at", "updated_at"]
  132. )
  133. if not results or not results[0]:
  134. return []
  135. return [hit.entity.to_dict() for hit in results[0]]
  136. def query(self, filters: str, limit: int = 100) -> List[Dict]:
  137. """
  138. 纯标量查询(不使用向量)
  139. Args:
  140. filters: 过滤表达式
  141. limit: 返回数量
  142. Returns:
  143. 知识列表
  144. """
  145. results = self.collection.query(
  146. expr=filters,
  147. output_fields=["id", "message_id", "task", "content", "types",
  148. "tags", "scopes", "owner", "resource_ids",
  149. "source", "eval", "created_at", "updated_at"],
  150. limit=limit
  151. )
  152. return results
  153. def get_by_id(self, knowledge_id: str) -> Optional[Dict]:
  154. """
  155. 根据 ID 获取知识
  156. Args:
  157. knowledge_id: 知识 ID
  158. Returns:
  159. 知识数据,不存在返回 None
  160. """
  161. results = self.collection.query(
  162. expr=f'id == "{knowledge_id}"',
  163. output_fields=["id", "message_id", "task", "content", "types",
  164. "tags", "scopes", "owner", "resource_ids",
  165. "source", "eval", "created_at", "updated_at"]
  166. )
  167. return results[0] if results else None
  168. def update(self, knowledge_id: str, updates: Dict):
  169. """
  170. 更新知识(先删除再插入)
  171. Args:
  172. knowledge_id: 知识 ID
  173. updates: 更新字段
  174. """
  175. # 1. 查询现有数据
  176. existing = self.get_by_id(knowledge_id)
  177. if not existing:
  178. raise ValueError(f"Knowledge not found: {knowledge_id}")
  179. # 2. 合并更新
  180. existing.update(updates)
  181. existing["updated_at"] = int(time.time())
  182. # 3. 删除旧数据
  183. self.delete(knowledge_id)
  184. # 4. 插入新数据
  185. self.insert(existing)
  186. def delete(self, knowledge_id: str):
  187. """
  188. 删除知识
  189. Args:
  190. knowledge_id: 知识 ID
  191. """
  192. self.collection.delete(f'id == "{knowledge_id}"')
  193. self.collection.flush()
  194. def count(self) -> int:
  195. """返回知识总数"""
  196. return self.collection.num_entities
  197. def drop_collection(self):
  198. """删除 collection(危险操作)"""
  199. utility.drop_collection("knowledge")