Skip to content

用pymilvus管理向量数据库Milvus

当我们已经学会了在Attu中创建Collection,本文我们将学习如何用Python的pymilvus包管理Milvus数据库。

1. 安装必需的包

python
pip install protobuf==3.20.0
pip install grpcio-tools
pip install pymilvus==2.4.9

需要注意Python版本需要Python 3.7 或更高版本。

2. 引入要使用的包

python
import time
from pymilvus import DataType, MilvusClient

3. 实例化client

python
client = MilvusClient(uri="http://localhost:19530")

此处的服务地址即为容器化部署的Milvus服务,还没有启动服务的可以参考下文中相关文章。

4. 创建数据库

判断数据库yuma是否存在,不存在则创建

python
if 'yuma' not in client.list_databases():
    client.create_database("yuma")
    client.using_database("yuma")
else:
    print("yuma database exists")
    client.using_database("yuma")
    # 如果数据库存在但是想要重新创建,则取消一下注释即可
    # for cn in client.list_collections():
    #     print(cn)
    #     client.drop_collection(cn)
    # client.drop_database("yuma")
    # client.create_database("yuma")

5. 创建Collection

python
if client.has_collection("news"):
    print("news collection exists")
    # 可以删除指定Collection
    # client.drop_collection("news")
else:
    schema = client.create_schema(
        auto_id=True,  
        enable_dynamic_field=False,
        description="文章"
    )
    schema.add_field(field_name="id", datatype=DataType.INT64, is_primary=True, description="id")
    schema.add_field(field_name="vector", datatype=DataType.FLOAT_VECTOR, dim=1024, description="全文向量")
    schema.add_field(field_name="title", datatype=DataType.VARCHAR, max_length=200, description="标题")
    schema.add_field(field_name="title_vec", datatype=DataType.FLOAT_VECTOR, dim=1024, description="标题向量")
    schema.add_field(field_name="content", datatype=DataType.VARCHAR, max_length=2000, description="内容")

    index_params = client.prepare_index_params()
    index_params.add_index(
        field_name="id",
        index_type="INVERTED",
    )

    index_params.add_index(
        field_name="vector",
        index_type="IVF_FLAT",
        metric_type="COSINE",
        params={"nlist": 128},
    )

    index_params.add_index(
        field_name="title_vec",
        index_type="IVF_FLAT",
        metric_type="COSINE",
        params={"nlist": 128},
    )

    client.create_collection(
        collection_name="news",
        schema=schema,
        index_params=index_params
    )

    load_state = "NotLoad"
    while load_state != "Loaded":
        res = client.get_load_state("news")
        load_state = res.get('state').name
        print("load_state: ", load_state)
        time.sleep(1)
    print("news collection created")

其中schema为定义的Collection的结构,包含字段和字段属性,index_params为定义的字段的索引,字段id为标量索引,字段vectortitle_vec为向量索引。

需要注意的是,Collection中至少要包含一个向量字段,并且所有的向量字段都必须创建索引。

至此,我们就可以通过代码来管理我们的向量数据库了。

进阶

界面化使用Milvus确实很方便,但是在开发过程中我们更希望通过代码逻辑来管理我们的数据库。为此,Milvus官方提供了对PythonJavaGoNode.js等编程语言的支持,大家可以根据自己的情况选择。如果您想要进一步深入学习Milvus,可以关注:遇码,回复milvus,获取官方文档。

遇码MeetCoding 开源技术社区