Milvus向量数据库常见用法

本文介绍了如何使用MilvusPythonSDK进行客户端连接与断开,创建与管理集合,包括定义字段、创建、重命名和删除集合。同时,文章涵盖了数据插入、删除、查询,以及向量索引的创建与搜索,还有分区的管理。内容详细展示了Milvus中数据操作的各种功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建/断开客户端连接

from pymilvus import connections
# 创建连接
connections.connect(
  alias="default",
  user='username',
  password='password',
  host='localhost',
  port='19530'
)

# 断开连接
connections.disconnect("default")

管理Collection

创建Collection

# 定义Collection中的各个字段
fields = [
    FieldSchema(name="pk", dtype=DataType.INT64, is_primary=True, auto_id=False),
    FieldSchema(name="random", dtype=DataType.DOUBLE),
    FieldSchema(name="embeddings", dtype=DataType.FLOAT_VECTOR, dim=1024)
]
# 创建Collection
schema = CollectionSchema(fields, "hello_milvus is the simplest demo to introduce the APIs")
hello_milvus = Collection("hello_milvus", schema)

主要参数:

ParameterDescriptionOption
using (optional)By specifying the server alias here, you can choose in which Milvus server you create a collection.N/A
shards_num (optional)Number of the shards for the collection to create.[1,16]
num_partitions (optional)Number of logical partitions for the collection to create.[1,4096]
*kwargs: collection.ttl.seconds (optional)Collection time to live (TTL) is the expiration time of a collection. Data in an expired collection will be cleaned up and will not be involved in searches or queries. Specify TTL in the unit of seconds.The value should be 0 or greater. 0 means TTL is disabled.

重命名Collection

utility.rename_collection("old_collection", "new_collection") # Output: True

修改Collection属性

collection.set_properties(properties={"collection.ttl.seconds": 1800})

获取Collection各类属性

from pymilvus import Collection
collection = Collection("book")  # Get an existing collection.

collection.schema                # Return the schema.CollectionSchema of the collection.
collection.description           # Return the description of the collection.
collection.name                  # Return the name of the collection.
collection.is_empty              # Return the boolean value that indicates if the collection is empty.
collection.num_entities          # Return the number of entities in the collection.
collection.primary_field         # Return the schema.FieldSchema of the primary key field.
collection.partitions            # Return the list[Partition] object.
collection.indexes               # Return the list[Index] object.
collection.properties		# Return the expiration time of data in the collection.

删除一个集合(集合内的所有数据都被删除)

from pymilvus import utility
utility.drop_collection("book")

管理分区(Partitions)

使用分区可以更有效地组织和查询数据:我们可以将数据插入到特定的分区中,然后可以在查询时只查询和加载该分区,从而提高查询效率和减少资源占用。

创建分区

from pymilvus import Collection
collection = Collection("book")      # Get an existing collection.
collection.create_partition("novel")

判断分区是否存在

from pymilvus import Collection
collection = Collection("book")      # Get an existing collection.
collection.has_partition("novel")

删除分区(先释放再删除)

from pymilvus import Collection
collection.drop_partition("novel")

加载分区

from pymilvus import Collection
collection = Collection("book")      # Get an existing collection.
collection.load(["novel"], replica_number=2)

from pymilvus import Partition
partition = Partition("novel")       # Get an existing partition.
partition.load(replica_number=2)

释放分区

from pymilvus import Partition
partition = Partition("novel")       # Get an existing partition.
partition.release()

管理数据

插入数据

import random
data = [
  [i for i in range(2000)],
  [str(i) for i in range(2000)],
  [i for i in range(10000, 12000)],
  [[random.random() for _ in range(2)] for _ in range(2000)]
]

data.append([str("dy"*i) for i in range(2000)])

from pymilvus import Collection
collection = Collection("book")      # Get an existing collection.
mr = collection.insert(data)
collection.flush()

删除数据

expr = "book_id in [0,1]"
from pymilvus import Collection
collection = Collection("book")      # Get an existing collection.
collection.delete(expr)

管理索引

矢量索引是用于加速矢量相似性搜索的元数据的组织单元。如果没有基于向量构建的索引,Milvus将默认执行暴力搜索

创建矢量索引

index_params = {
  "metric_type":"L2",
  "index_type":"IVF_FLAT",
  "params":{"nlist":1024}
}

from pymilvus import Collection, utility
collection = Collection("book")      
collection.create_index(
  field_name="book_intro", 
  index_params=index_params
)

utility.index_building_progress("book")

创建标量索引

标量索引不需要设置索引类型以及索引参数,直接创建即可。

from pymilvus import Collection

collection = Collection("book")   
collection.create_index(
  field_name="book_name", 
  index_name="scalar_index",
)
collection.load()

删除索引

删除索引是删除该集合下的所有索引文件

from pymilvus import Collection
collection = Collection("book")      # Get an existing collection.
collection.drop_index()

搜索与查询

向量相似性搜索

Milvus中的向量相似度搜索会计算查询亮相与具有指定相似度度量的集合中的向量之间的距离,并返回最相似的结果。

from pymilvus import Collection
collection = Collection("book")      # Get an existing collection.
collection.drop_index()

search_params = {"metric_type": "L2", "params": {"nprobe": 10}, "offset": 5}

results = collection.search(
	data=[[0.1, 0.2]], 
	anns_field="book_intro", 
	param=search_params,
	limit=10, 
	expr=None,
	# set the names of the fields you want to retrieve from the search result.
	output_fields=['title'],
	consistency_level="Strong"
)

results[0].ids

results[0].distances

hit = results[0][0]
hit.entity.get('title')

# 搜索完成后,需要释放Milvus中加载的集合以减少内存消耗
collection.release()

必要的搜索参数

范围描述
data用于搜索的向量。
anns_field要搜索的字段的名称。
param特定于索引的搜索参数。有关详细信息,请参阅https://milvus.io/docs/index.md
offset返回集中要跳过的结果数。该值与“limit”之和应小于 16384。
limit要返回的最相似结果的数量。该值与“offset”之和应小于 16384。
expr用于过滤属性的布尔表达式。有关详细信息,请参阅https://milvus.io/docs/boolean.md
partition_names(选修的)要搜索的分区名称列表。
output_fields(选修的)要返回的字段的名称。当前版本不支持矢量场。
timeout(选修的)允许 RPC 的持续时间(以秒为单位)。当设置为 None 时,客户端会等待服务器响应或发生错误。
round_decimal(选修的)返回距离的小数位数。
consistency_level(选修的)搜索的一致性级别。

向量标量查询

from pymilvus import Collection
collection = Collection("book")      # Get an existing collection.
collection.load()

res = collection.query(
  expr = "book_id in [2,4,6,8]",
  offset = 0,
  limit = 10, 
  output_fields = ["book_id", "book_intro"],
  consistency_level="Strong"
)
<think>嗯,用户想了解Milvus向量数据库使用方法、教程和示例。我需要结合之前提供的引用内容来组织回答。首先,用户的问题是关于使用指南,所以应该分步骤讲解,比如环境配置、数据准备、索引创建、查询操作等。 首先,系统级指令里提到要正确使用LaTeX格式,但用户的问题可能不涉及数学公式,所以可能不太需要,但要注意如果有相关变量或参数的话要用$...$。不过Milvus使用更多是代码示例,所以重点放在代码块和步骤说明上。 用户提供的引用中有安装配置部分,引用2提到用Docker部署,引用3有Python SDK的示例。所以应该先讲环境部署,比如Docker安装,然后Python SDK的连接。然后数据准备,生成向量,插入数据,创建索引,最后查询。每个步骤都需要代码示例,并且引用对应的来源,比如引用2和3。 还要生成相关问题,比如性能优化、应用场景、索引类型比较等。要确保问题与Milvus使用相关,并且符合用户可能的后续疑问。 需要检查是否结构清晰,分步骤说明,代码块是否正确使用反引号,引用标记是否正确添加。例如,在讲Docker部署时,引用[^2],在Python连接时引用[^3],在索引部分引用[^3]等。同时,确保回答使用中文,并且自然流畅,避免使用Markdown格式,但用户这里给的示例是允许使用代码块的,所以没问题。 可能还需要提到Milvus的核心原理,比如索引类型如IVF、HNSW,这部分在引用1和3中有提到,可以简要说明,但用户主要需要的是使用方法,所以原理部分可以简单带过,重点放在操作步骤。 最后,确保每个引用的地方都正确标注,比如环境配置部分引用[^2],数据插入引用[^3],索引创建引用[^3]等。然后生成的相关问题要围绕Milvus的进阶使用和实际应用,比如如何优化查询速度,如何选择索引类型,与其他数据库对比等。</think># Milvus 向量数据库使用指南与示例 ## 一、环境部署与配置 1. 使用 Docker 快速部署单机版(CPU 模式): ```bash docker pull milvusdb/milvus:latest docker run -d --name milvus_cpu -p 19530:19530 -p 19121:19121 -v /path/to/data:/var/lib/milvus milvusdb/milvus:latest ``` 通过 `19530` 端口访问服务,`19121` 为管理端口[^2] 2. Python 环境连接: ```python from pymilvus import connections connections.connect(host="localhost", port="19530") # 建立连接 ``` ## 二、数据操作全流程 ### 1. 创建集合(Collection) ```python from pymilvus import FieldSchema, CollectionSchema, DataType, Collection fields = [ FieldSchema(name="id", dtype=DataType.INT64, is_primary=True), FieldSchema(name="embedding", dtype=DataType.FLOAT_VECTOR, dim=128) ] schema = CollectionSchema(fields, description="示例集合") collection = Collection(name="demo_collection", schema=schema) ``` ### 2. 插入向量数据 ```python import numpy as np vectors = np.random.rand(1000, 128) # 生成1000个128维向量 data = [ [i for i in range(1000)], # ID列表 [v.tolist() for v in vectors] # 向量列表 ] collection.insert(data) collection.flush() # 确保数据持久化[^3] ``` ### 3. 创建向量索引 ```python index_params = { "index_type": "IVF_FLAT", "metric_type": "L2", "params": {"nlist": 128} } collection.create_index(field_name="embedding", index_params=index_params) ``` ### 4. 相似度检索 ```python search_params = {"metric_type": "L2", "params": {"nprobe": 10}} query_vector = np.random.rand(1, 128).tolist() results = collection.search( data=query_vector, anns_field="embedding", param=search_params, limit=5, output_fields=["id"] ) for hit in results[0]: print(f"ID: {hit.id}, 距离: {hit.distance}") ``` ## 三、进阶功能说明 1. **分区管理**:支持按业务维度创建分区,提升数据管理效率 2. **混合查询**:支持将向量搜索与结构化过滤条件结合 3. **动态扩展**:通过分布式架构支持PB级数据规模
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值