You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.5 KiB

4 months ago
import time
from WxMini.Milvus.Utils.MilvusCollectionManager import MilvusCollectionManager
from WxMini.Milvus.Utils.MilvusConnectionPool import *
from WxMini.Milvus.Config.MulvusConfig import *
4 months ago
from gensim.models import KeyedVectors
4 months ago
4 months ago
# 1. 加载预训练的 Word2Vec 模型
4 months ago
model_path = MS_MODEL_PATH # 替换为你的 Word2Vec 模型路径
model = KeyedVectors.load_word2vec_format(model_path, binary=False, limit=MS_MODEL_LIMIT)
4 months ago
print(f"模型加载成功,词向量维度: {model.vector_size}")
4 months ago
4 months ago
4 months ago
# 将文本转换为嵌入向量
def text_to_embedding(text):
4 months ago
# 直接使用全句进行向量计算
if text in model:
embedding = model[text]
print(f"生成的全句向量: {embedding[:5]}...") # 打印前 5 维
return embedding
4 months ago
else:
4 months ago
print("未找到有效词,返回零向量")
return [0.0] * model.vector_size
4 months ago
4 months ago
4 months ago
# 2. 使用连接池管理 Milvus 连接
4 months ago
milvus_pool = MilvusConnectionPool(host=MS_HOST, port=MS_PORT, max_connections=MS_MAX_CONNECTIONS)
4 months ago
# 3. 从连接池中获取一个连接
4 months ago
connection = milvus_pool.get_connection()
4 months ago
# 4. 初始化集合管理器
4 months ago
collection_name = MS_COLLECTION_NAME
collection_manager = MilvusCollectionManager(collection_name)
4 months ago
# 5. 加载集合到内存
4 months ago
collection_manager.load_collection()
4 months ago
# 6. 输入一句话
4 months ago
input_text = input("请输入一句话:") # 例如:“我今天心情不太好”
4 months ago
# 7. 将文本转换为嵌入向量
4 months ago
current_embedding = text_to_embedding(input_text)
4 months ago
4 months ago
# 8. 查询与当前对话最相关的历史对话
4 months ago
search_params = {
4 months ago
"metric_type": "L2", # 使用 L2 距离度量方式
"params": {"nprobe": MS_NPROBE} # 设置 IVF_FLAT 的 nprobe 参数
4 months ago
}
start_time = time.time()
4 months ago
results = collection_manager.search(current_embedding, search_params, limit=2) # 返回 2 条结果
4 months ago
end_time = time.time()
4 months ago
# 9. 输出查询结果
4 months ago
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("未找到相关历史对话,请检查查询参数或数据。")
4 months ago
# 10. 输出查询耗时
4 months ago
print(f"查询耗时: {end_time - start_time:.4f}")
4 months ago
# 11. 释放连接
4 months ago
milvus_pool.release_connection(connection)
4 months ago
# 12. 关闭连接池
4 months ago
milvus_pool.close()