|
|
|
@ -1,4 +1,3 @@
|
|
|
|
|
|
|
|
|
|
import time
|
|
|
|
|
import jieba # 导入 jieba 分词库
|
|
|
|
|
from WxMini.Milvus.Utils.MilvusCollectionManager import MilvusCollectionManager
|
|
|
|
@ -7,10 +6,11 @@ from WxMini.Milvus.Config.MulvusConfig import *
|
|
|
|
|
from gensim.models import KeyedVectors
|
|
|
|
|
|
|
|
|
|
# 加载预训练的 Word2Vec 模型
|
|
|
|
|
model_path = "D:/Tencent_AILab_ChineseEmbedding/Tencent_AILab_ChineseEmbedding.txt" # 替换为你的 Word2Vec 模型路径
|
|
|
|
|
model = KeyedVectors.load_word2vec_format(model_path, binary=False, limit=10000)
|
|
|
|
|
model_path = MS_MODEL_PATH # 替换为你的 Word2Vec 模型路径
|
|
|
|
|
model = KeyedVectors.load_word2vec_format(model_path, binary=False, limit=MS_MODEL_LIMIT)
|
|
|
|
|
print(f"模型加载成功,词向量维度: {model.vector_size}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# 将文本转换为嵌入向量
|
|
|
|
|
def text_to_embedding(text):
|
|
|
|
|
words = jieba.lcut(text) # 使用 jieba 分词
|
|
|
|
@ -25,6 +25,7 @@ def text_to_embedding(text):
|
|
|
|
|
print("未找到有效词,返回零向量")
|
|
|
|
|
return [0.0] * model.vector_size
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# 1. 使用连接池管理 Milvus 连接
|
|
|
|
|
milvus_pool = MilvusConnectionPool(host=MS_HOST, port=MS_PORT, max_connections=MS_MAX_CONNECTIONS)
|
|
|
|
|
|
|
|
|
@ -46,8 +47,8 @@ current_embedding = text_to_embedding(input_text)
|
|
|
|
|
|
|
|
|
|
# 7. 查询与当前对话最相关的历史对话
|
|
|
|
|
search_params = {
|
|
|
|
|
"metric_type": "L2", # 使用 L2 距离度量方式
|
|
|
|
|
"params": {"nprobe": 100} # 设置 IVF_FLAT 的 nprobe 参数
|
|
|
|
|
"metric_type": "L2", # 使用 L2 距离度量方式
|
|
|
|
|
"params": {"nprobe": MS_NPROBE} # 设置 IVF_FLAT 的 nprobe 参数
|
|
|
|
|
}
|
|
|
|
|
start_time = time.time()
|
|
|
|
|
results = collection_manager.search(current_embedding, search_params, limit=2) # 返回 2 条结果
|
|
|
|
@ -73,4 +74,4 @@ print(f"查询耗时: {end_time - start_time:.4f} 秒")
|
|
|
|
|
milvus_pool.release_connection(connection)
|
|
|
|
|
|
|
|
|
|
# 11. 关闭连接池
|
|
|
|
|
milvus_pool.close()
|
|
|
|
|
milvus_pool.close()
|
|
|
|
|