import numpy as np import time from WxMini.Milvus.Utils.MilvusCollectionManager import MilvusCollectionManager from WxMini.Milvus.Utils.MilvusConnectionPool import * from WxMini.Milvus.Config.MulvusConfig import * # 1. 使用连接池管理 Milvus 连接 milvus_pool = MilvusConnectionPool(host=MS_HOST, port=MS_PORT, max_connections=MS_MAX_CONNECTIONS) # 2. 从连接池中获取一个连接 connection = milvus_pool.get_connection() # 3. 初始化集合管理器 collection_name = MS_COLLECTION_NAME collection_manager = MilvusCollectionManager(collection_name) # 4. 加载集合到内存 collection_manager.load_collection() # 5. 模拟当前对话的嵌入向量 current_embedding = np.random.random(128).tolist() # 随机生成一个 128 维向量 # 6. 查询与当前对话最相关的历史对话 search_params = { "metric_type": "L2", # 使用 L2 距离度量方式 "params": {"nprobe": 100} # 设置 IVF_FLAT 的 nprobe 参数 } start_time = time.time() results = collection_manager.search(current_embedding, search_params, limit=2) end_time = time.time() # 7. 输出查询结果 print("当前对话的嵌入向量:", current_embedding) print("最相关的历史对话:") if results: for hits in results: for hit in hits: try: text = collection_manager.query_text_by_id(hit.id) print(f"- {text} (距离: {hit.distance})") except Exception as e: print(f"查询失败: {e}") else: print("未找到相关历史对话,请检查查询参数或数据。") # 8. 输出查询耗时 print(f"查询耗时: {end_time - start_time:.4f} 秒") # 9. 释放连接 milvus_pool.release_connection(connection) # 10. 关闭连接池 milvus_pool.close()