跳到主要内容
版本:BYOC 开发指南

创建 Scalar Index

Zilliz Cloud 支持对标量字段(非向量字段)进行索引,从而显著加速过滤和搜索性能,尤其适用于大型数据集。

概述

对标量字段进行索引是可选操作,但如果你经常在过滤条件中访问某个特定标量字段,建议为其建立索引以加速查询性能。

Zilliz Cloud 支持对以下字段类型使用 AUTOINDEX

字段类型

描述

VARCHAR

字符串

INT8, INT32, INT64

整数

FLOAT, DOUBLE

浮点数

BOOL

布尔值

ARRAY

标量值的同质数组

准备工作

在创建索引之前,定义一个包含向量字段和标量字段的 collection。Zilliz Cloud 要求每个 collection 都有一个向量字段。

在此示例中,我们为产品目录定义一个 schema,其中包含一个必需的向量字段(vector)和一个 DOUBLE 类型的标量字段(price):

from pymilvus import MilvusClient, DataType

client = MilvusClient(uri="YOUR_CLUSTER_ENDPOINT") # Replace with your cluster endpoint

# Define schema with dynamic field support
schema = client.create_schema(
auto_id=False,
# highlight-next-line
enable_dynamic_field=True # Enable dynamic field
)

# Define fields
schema.add_field(field_name="product_id", datatype=DataType.INT64, is_primary=True)
schema.add_field(field_name="vector", datatype=DataType.FLOAT_VECTOR, dim=5) # Vector field
schema.add_field(field_name="price", datatype=DataType.DOUBLE) # Scalar field

# Create the collection
client.create_collection(
collection_name="product_catalog",
schema=schema
)

为标量字段建立索引

您可以使用 AUTOINDEX 为任何非 JSON 标量字段创建索引。无需额外的索引参数。以下示例展示了如何为 price 字段建立索引:

index_params = client.prepare_index_params() # Prepare an empty IndexParams object, without having to specify any index parameters

index_params.add_index(
field_name="price", # Name of the scalar field to be indexed
# highlight-next-line
index_type="AUTOINDEX", # Type of index to be created
index_name="price_index" # Name of the index to be created
)

定义索引参数后,您可以使用 create_index() 将它们应用到 collection:

client.create_index(
collection_name="product_catalog",
index_params=index_params
)

查看索引详情

创建索引后,您可以查看其详细信息:

# Describe index
res = client.list_indexes(
collection_name="product_catalog"
)

print(res)

res = client.describe_index(
collection_name="product_catalog",
index_name="price_index"
)

print(res)

删除索引

当您不需要索引时,可以考虑将其删除。

# Drop index
client.drop_index(
collection_name="product_catalog",
index_name="price_index"
)

高级功能

除了基础功能外,标量索引还提供了一些进阶特性,能够满足更复杂的数据检索需求。

NGRAM [READ MORE]

在 Zilliz Cloud 中,NGRAM 索引 用于加速对 VARCHAR 字段 或 JSON 字段中指定路径的 LIKE 查询。在建立索引之前,Zilliz Cloud 会将文本拆分为固定长度 n 的 重叠子串(n-gram)。例如,当 `n = 3` 时,单词 `"Milvus"` 会被拆分为以下 3-gram:`"Mil"`, `"ilv"`, `"lvu"`, `"vus"`。这些 n-gram 随后会存储在倒排索引中,每个 gram 都映射到包含它的文档 ID。在查询时,该索引使 Zilliz Cloud 能快速缩小候选范围,从而显著加速查询执行。