langchain milvus稀疏向量化
时间: 2025-02-22 08:05:01 浏览: 70
### LangChain 中使用 Milvus 进行稀疏向量化的实现方法
#### 使用背景与准备
在构建基于LangChain的应用程序时,利用Milvus作为向量存储引擎可以显著提升查询效率和效果。对于稀疏向量的支持,虽然Milvus更擅长处理密集型向量,但也能够有效管理某些类型的稀疏数据结构[^1]。
#### 数据预处理阶段
当涉及到稀疏向量化操作时,通常会先对原始文本或其他形式的数据进行特征提取转换成数值表示。这一步骤可能涉及词袋模型(Bag of Words),TF-IDF权重计算等方式来生成适合输入给Milvus的稀疏矩阵格式[^2]。
```python
from sklearn.feature_extraction.text import TfidfVectorizer
# 假设有一个字符串列表代表文档集合
documents = ["Document 1 text", "Document 2 text"]
vectorizer = TfidfVectorizer()
sparse_matrix = vectorizer.fit_transform(documents)
print(sparse_matrix.shape) # 输出形状以确认是否为稀疏矩阵
```
#### 配置并连接到Milvus实例
完成上述准备工作之后,则需配置好Python客户端以便于同远端或本地部署好的Milvus服务建立通信链接。这里推荐采用pymilvus库来进行交互。
```python
from pymilvus import connections, FieldSchema, CollectionSchema, DataType, Collection
connections.connect("default", host="localhost", port="19530")
fields = [
FieldSchema(name="id", dtype=DataType.INT64, is_primary=True),
FieldSchema(name="embedding", dtype=DataType.FLOAT_VECTOR, dim=sparse_matrix.shape[1])
]
schema = CollectionSchema(fields)
collection_name = 'my_collection'
if collection_name not in list_collections():
collection = Collection(name=collection_name, schema=schema)
else:
collection = Collection(name=collection_name)
```
#### 插入稀疏向量至Milvus
一旦建立了正确的表结构定义以及确保了待插入项符合预期规格后,就可以批量加载这些经过编码后的条目进入目标表格内等待后续检索调用了。
```python
import numpy as np
ids = [i for i in range(len(documents))]
embeddings = sparse_matrix.toarray().tolist()
mr = collection.insert([ids, embeddings])
print(f"Number of entities inserted: {len(mr.primary_keys)}")
```
#### 执行相似度搜索请求
最后,在完成了全部前期设置工作以后,便可通过指定参数发起一次近似最近邻算法(ANN)查找命令从而获取最接近查询条件的结果集返回给前端展示层面上去。
```python
search_params = {"metric_type": "L2", "params": {"nprobe": 10}}
results = collection.search(embedding_to_search, "embedding", search_params, limit=5)
for result in results:
print(result.id, result.distance)
```
阅读全文
相关推荐


















