pymilvus
是 Milvus 向量数据库的 Python SDK,为用户提供了与 Milvus 服务交互的接口,用于管理集合、插入向量、构建索引、执行搜索等操作。在版本 2.5.0 中,pymilvus
提供了灵活的 MilvusClient
模块和传统的 ORM(对象关系映射)模块,支持同步和异步操作,并新增了模型集成(如嵌入生成)。以下是对 pymilvus
2.5.0 中 API 的全面分类、示例和详细说明,旨在帮助理解其功能和使用场景。
pymilvus
2.5.0 提供了两种主要接口:
MilvusClient
,支持异步编程,提高并发性能。此外,pymilvus
新增了 model
模块,集成了嵌入生成和重排序功能,简化了从文本、图像等数据生成向量的过程。本教程将重点介绍 MilvusClient
的 API 分类,并提及 AsyncMilvusClient
和 model
模块的相关功能。
API 可以分为以下几大类:
以下逐一介绍每个分类的功能、示例和说明。
连接管理 API 用于初始化与 Milvus 服务的连接,配置服务器地址、认证信息和数据库。
from pymilvus import MilvusClient
# 无认证连接(本地服务器)
client = MilvusClient(uri="http://localhost:19530")
# 根用户认证
client = MilvusClient(
uri="http://localhost:19530",
token="root:Milvus",
db_name="default"
)
# 非根用户认证
client = MilvusClient(
uri="http://localhost:19530",
token="user:password",
db_name="default"
)
# 本地 Milvus Lite
client = MilvusClient(uri="./milvus_demo.db")
uri
:指定 Milvus 服务器地址(远程)或本地文件路径(Milvus Lite)。token
:用于认证,格式为 username:password
。db_name
:指定数据库名称,默认为 default
。集合(Collection)是 Milvus 中存储向量的基本单位,类似于数据库中的表。集合管理 API 用于创建、删除、描述和列出集合。
# 创建集合
client.create_collection(
collection_name="example_collection",
dimension=128, # 向量维度
metric_type="L2" # 欧几里得距离
)
# 查看集合信息
schema = client.describe_collection(collection_name="example_collection")
print("Collection schema:", schema)
# 列出所有集合
collections = client.list_collections()
print("Collections:", collections)
# 删除集合
client.drop_collection(collection_name="example_collection")
create_collection
:需要指定集合名称、向量维度和距离度量(如 L2
、COSINE
、IP
)。metric_type
:影响相似性计算,常见选项包括:
L2
:欧几里得距离,适合计算机视觉。COSINE
:余弦相似度,适合自然语言处理。IP
:内积,适合某些 NLP 任务。describe_collection
:返回集合的 schema,包括字段定义和属性。list_collections
:返回当前数据库中的所有集合名称。drop_collection
:永久删除集合及其数据,谨慎使用。数据操作 API 用于向集合中插入、删除、查询和更新向量数据。
import random
# 插入数据
data = [
{
"id": i,
"vector": [random.random() for _ in range(128)],
"metadata": {"category": f"cat_{i % 3}"}
}
for i in range(1000)
]
client.insert(collection_name="example_collection", data=data)
# 查询数据(基于 ID)
results = client.query(
collection_name="example_collection",
ids=[0, 1, 2],
output_fields=["id", "metadata"]
)
print("Query results:", results)
# 删除数据(基于过滤条件)
client.delete(
collection_name="example_collection",
filter="category == 'cat_0'"
)
# 更新数据
client.upsert(
collection_name="example_collection",
data=[
{"id": 0, "metadata": {"category": "updated_cat"}}
]
)
insert
:批量插入向量数据,每个实体包含 id
(主键)、vector
(向量)和元数据(如 metadata
)。query
:根据 ID 或过滤表达式检索数据,返回指定字段。delete
:支持基于主键 ID 或过滤表达式(如 category == 'cat_0'
)删除数据。upsert
:插入或更新数据,如果 ID 已存在则更新,否则插入。==
、>
、<
和 in
。索引管理 API 用于创建、删除和描述索引,以加速向量搜索。
# 创建 HNSW 索引
client.create_index(
collection_name="example_collection",
field_name="vector",
index_params={
"index_type": "HNSW",
"metric_type": "L2",
"params": {"M": 16, "efConstruction": 200}
}
)
# 查看索引信息
index_info = client.describe_index(collection_name="example_collection", field_name="vector")
print("Index info:", index_info)
# 删除索引
client.drop_index(collection_name="example_collection", field_name="vector")
create_index
:支持多种索引类型:
HNSW
:高精度、低延迟,适合中小规模数据。IVF_FLAT
:适合大规模数据,平衡精度和速度。FLAT
:无索引,精确搜索,适合小数据集。index_params
:根据索引类型设置参数,例如:
HNSW
:M
(邻居数量)、efConstruction
(构建时的搜索范围)。IVF_FLAT
:nlist
(簇数量)。describe_index
:返回索引类型和参数。搜索与查询 API 是 Milvus 的核心功能,用于执行向量相似性搜索和混合查询。
# 单向量搜索
query_vector = [random.random() for _ in range(128)]
results = client.search(
collection_name="example_collection",
data=[query_vector],
limit=5,
output_fields=["id", "metadata"],
filter="category == 'cat_1'"
)
print("Search results:", results)
# 批量搜索
query_vectors = [[random.random() for _ in range(128)] for _ in range(2)]
results = client.search(
collection_name="example_collection",
data=query_vectors,
limit=3,
output_fields=["id"]
)
print("Batch search results:", results)
search
:返回与查询向量最相似的 Top-K 结果。data
:支持单向量或多向量搜索。limit
:指定返回结果数量。filter
:元数据过滤表达式,如 category == 'cat_1'
或 id > 100
。output_fields
:指定返回的字段,如 id
或元数据。分区(Partition)用于将集合分割成逻辑子集,提高搜索效率。分区管理 API 用于创建、删除和操作分区。
# 创建分区
client.create_partition(
collection_name="example_collection",
partition_name="part1"
)
# 加载分区到内存
client.load_partition(
collection_name="example_collection",
partition_name="part1"
)
# 列出分区
partitions = client.list_partitions(collection_name="example_collection")
print("Partitions:", partitions)
# 删除分区
client.drop_partition(
collection_name="example_collection",
partition_name="part1"
)
create_partition
:创建一个逻辑分区,默认分区为 _default
。load_partition
:将分区加载到内存以加速搜索。release_partition
:释放分区,节省内存。pymilvus
2.5.0 的 model
模块集成了嵌入生成和重排序功能,简化了从原始数据(如文本)生成向量的过程。
from pymilvus import model
# 密集嵌入
ef = model.DefaultEmbeddingFunction() # 使用 all-MiniLM-L6-v2 模型
docs = [
"Artificial intelligence was founded in 1956.",
"Alan Turing contributed to AI."
]
embeddings = ef.encode_documents(docs)
print("Dense embeddings dimension:", ef.dim) # 384
# 稀疏嵌入(BM25)
bm25_ef = model.sparse.BM25EmbeddingFunction()
bm25_ef.fit(docs)
docs_embeddings = bm25_ef.encode_documents(docs)
query = "AI history"
query_embedding = bm25_ef.encode_queries([query])
print("Sparse embeddings dimension:", bm25_ef.dim)
# 保存 BM25 参数
bm25_ef.save("bm25_params.json")
DefaultEmbeddingFunction
:默认使用 all-MiniLM-L6-v2
模型,生成 384 维密集向量,适合语义搜索。BM25EmbeddingFunction
:生成稀疏向量,适合关键词搜索,需先 fit
数据。model.rerank
模块优化搜索结果。sentence-transformers
)的依赖。AsyncMilvusClient
是 pymilvus
2.5.0 新增的异步客户端,支持异步编程,适合高并发场景。
import asyncio
from pymilvus import AsyncMilvusClient
async def main():
async_client = AsyncMilvusClient(uri="http://localhost:19530")
await async_client.create_collection("async_collection", dimension=128)
await async_client.insert(
collection_name="async_collection",
data=[{"id": 0, "vector": [0.1] * 128}]
)
results = await async_client.search(
collection_name="async_collection",
data=[[0.1] * 128],
limit=1
)
print("Async search results:", results)
await async_client.drop_collection("async_collection")
await async_client.close()
asyncio.run(main())
AsyncMilvusClient
:功能与 MilvusClient
类似,但使用 await
关键字。MilvusClient
的子集,未来版本可能扩展。pymilvus
2.5.0 还提供了一些辅助功能:
client.create_database(db_name="new_db")
client.drop_database(db_name="new_db")
client.create_alias(collection_name="example_collection", alias="alias1")
client.drop_alias(alias="alias1")
client.grant_privilege(...)
client.revoke_privilege(...)
# 创建数据库
client.create_database(db_name="test_db")
# 切换数据库
client.using_database(db_name="test_db")
# 删除数据库
client.drop_database(db_name="test_db")
以下是一个完整的语义搜索示例,结合 model
模块和 MilvusClient
,展示 pymilvus
的综合应用。
from pymilvus import MilvusClient, model
# 初始化客户端和嵌入模型
client = MilvusClient(uri="http://localhost:19530")
ef = model.DefaultEmbeddingFunction()
# 准备数据
docs = [
"Artificial intelligence was founded in 1956.",
"Alan Turing contributed to AI.",
"Deep learning is a subset of AI."
]
embeddings = ef.encode_documents(docs)
# 创建集合
client.create_collection(
collection_name="semantic_search",
dimension=384, # all-MiniLM-L6-v2 输出 384 维
metric_type="COSINE"
)
# 插入数据
data = [
{"id": i, "vector": embeddings[i], "text": docs[i]}
for i in range(len(docs))
]
client.insert(collection_name="semantic_search", data=data)
# 构建索引
client.create_index(
collection_name="semantic_search",
field_name="vector",
index_params={"index_type": "HNSW", "metric_type": "COSINE", "params": {"M": 16, "efConstruction": 200}}
)
# 搜索
query = "History of AI"
query_embedding = ef.encode_queries([query])[0]
results = client.search(
collection_name="semantic_search",
data=[query_embedding],
limit=2,
output_fields=["text"]
)
for result in results[0]:
print(f"Text: {result['entity']['text']}, Distance: {result['distance']}")
# 清理
client.drop_collection("semantic_search")
Text: Artificial intelligence was founded in 1956., Distance: 0.92
Text: Alan Turing contributed to AI., Distance: 0.85
model.DefaultEmbeddingFunction
生成文本嵌入。COSINE
距离进行语义搜索。pymilvus
2.5.0 与 Milvus 服务器版本匹配(推荐 Milvus 2.4.x 或 2.5.x)。M
、efConstruction
)以平衡精度和速度。try:
client.create_collection("test", dimension=128)
except Exception as e:
print(f"Error: {e}")
release_collection
、release_partition
)。client.close()
)以释放连接。pymilvus
2.5.0 提供了丰富的 API,涵盖连接管理、集合管理、数据操作、索引管理、搜索与查询、分区管理、模型集成和异步操作。MilvusClient
模块简单易用,适合快速开发;AsyncMilvusClient
支持高并发场景;model
模块简化了嵌入生成。结合这些功能,可以轻松构建语义搜索、推荐系统或图像检索等应用。