索引向量字段
本指南将指导您完成在 Collection 中创建和管理向量字段索引的基本操作。
概述
利用存储在索引文件中的元数据,Milvus 以专门的结构组织数据,便于在搜索或查询过程中快速检索所需的信息。
Milvus 提供多种索引类型和指标,可对字段值进行排序,以实现高效的相似性搜索。下表列出了不同向量字段类型所支持的索引类型和度量。目前,Milvus 支持各种类型的向量数据,包括浮点嵌入(通常称为浮点向量或稠密向量)、二进制嵌入(也称为二进制向量)和稀疏嵌入(也称为稀疏向量)。详情请参阅 "内存索引 和 相似度指标"。
| 度量类型 | 索引类型 |
|---|---|
|
|
| 度量类型 | 索引类型 |
|---|---|
|
|
| 度量类型 | 索引类型 |
|---|---|
| IP | SPARSE_INVERTED_INDEX |
| BM25 | SPARSE_INVERTED_INDEX |
从 Milvus 2.5.4 起,SPARSE_WAND 已被弃用。建议在保持兼容性的前提下,使用 "inverted_index_algo": "DAAT_WAND" 来实现等价。更多信息,请参阅 稀疏向量。
建议为经常访问的向量字段和标量字段创建索引。
准备工作
正如 管理 Collection 中所解释的,如果在创建 Collection 请求中指定了以下任一条件,Milvus 会在创建 Collection 时自动生成索引并将其加载到内存中:
-
向量字段的维度和度量类型,或
-
Schema 和索引参数。
下面的代码片段对现有代码进行了重新利用,以建立与 Milvus 实例的连接,并在不指定其索引参数的情况下创建 Collection。在这种情况下,Collection 缺乏索引并保持未加载状态。
- Python
- Java
- Node.js
- Go
- cURL
要准备索引,请使用 MilvusClient 连接到 Milvus 服务器,并通过使用 create_schema(), add_field() 和 create_collection().
from pymilvus import DataType, MilvusClient
client = MilvusClient(uri="http://localhost:19530")
schema = client.create_schema(auto_id=False, enable_dynamic_field=True)
schema.add_field("id", DataType.INT64, is_primary=True)
schema.add_field("vector", DataType.FLOAT_VECTOR, dim=5)
client.create_collection(
collection_name="customized_setup",
schema=schema,
)
要准备索引,使用 MilvusClientV2 连接到 Milvus 服务器,并通过使用 createSchema(), addField() 和 createCollection().
import io.milvus.v2.client.ConnectConfig;
import io.milvus.v2.client.MilvusClientV2;
import io.milvus.v2.common.DataType;
import io.milvus.v2.service.collection.request.AddFieldReq;
import io.milvus.v2.service.collection.request.CreateCollectionReq;
MilvusClientV2 client = new MilvusClientV2(
ConnectConfig.builder().uri("http://localhost:19530").build()
);
CreateCollectionReq.CollectionSchema schema = client.createSchema();
schema.setEnableDynamicField(true);
schema.addField(AddFieldReq.builder()
.fieldName("id")
.dataType(DataType.Int64)
.isPrimaryKey(true)
.autoID(false)
.build());
schema.addField(AddFieldReq.builder()
.fieldName("vector")
.dataType(DataType.FloatVector)
.dimension(5)
.build());
client.createCollection(CreateCollectionReq.builder()
.collectionName("customized_setup")
.collectionSchema(schema)
.build());
要准备索引,使用 MilvusClient 连接到 Milvus 服务器,并通过使用 createCollection().
import {
DataType,
MilvusClient,
} from "@zilliz/milvus2-sdk-node";
const client = new MilvusClient({
address: "http://localhost:19530",
});
await client.createCollection({
collection_name: "customized_setup",
schema: [
{
name: "id",
data_type: DataType.Int64,
is_primary_key: true,
autoID: false,
},
{
name: "vector",
data_type: DataType.FloatVector,
dim: 5,
},
],
enable_dynamic_field: true,
});
schema := entity.NewSchema().
WithDynamicFieldEnabled(true).
WithField(entity.NewField().
WithName("id").
WithDataType(entity.FieldTypeInt64).
WithIsPrimaryKey(true).
WithIsAutoID(false)).
WithField(entity.NewField().
WithName("vector").
WithDataType(entity.FieldTypeFloatVector).
WithDim(5))
if err := client.CreateCollection(
ctx,
milvusclient.NewCreateCollectionOption("customized_setup", schema),
); err != nil {
panic(err)
}
curl --request POST \
--url "http://localhost:19530/v2/vectordb/collections/create" \
--header "Authorization: Bearer root:Milvus" \
--header "Content-Type: application/json" \
--data '{
"collectionName": "customized_setup",
"schema": {
"autoId": false,
"enableDynamicField": true,
"fields": [
{
"fieldName": "id",
"dataType": "Int64",
"isPrimary": true
},
{
"fieldName": "vector",
"dataType": "FloatVector",
"elementTypeParams": {
"dim": "5"
}
}
]
}
}'
索引一个 Collection
- Python
- Java
- Node.js
- Go
- cURL
要为一个 Collection 创建索引或为一个 Collection 建立索引,请使用 prepare_index_params() 准备索引参数,并使用 create_index() 来创建索引。
from pymilvus import MilvusClient
client = MilvusClient(uri="http://localhost:19530")
index_params = client.prepare_index_params()
index_params.add_index(
field_name="vector",
index_type="IVF_FLAT",
index_name="vector_index",
metric_type="COSINE",
params={
"nlist": 128
},
)
client.create_index(
collection_name="customized_setup",
index_params=index_params,
)
| 参数 | 参数 |
|---|---|
field_name | 应用此对象的目标文件名称。 |
metric_type | 用于衡量向量间相似性的算法。可能的值有 IP、L2、COSINE、JACCARD、HAMMING。只有当指定字段是向量字段时才可用。更多信息,请参阅Milvus 支持的索引。 |
index_type | 用于在特定字段中排列数据的算法名称。有关适用算法,请参阅内存索引和磁盘索引。 |
index_name | 应用此对象后生成的索引文件名称。 |
params | 指定索引类型的微调参数。有关可能的键和值范围的详细信息,请参阅内存索引。 |
collection_name | 现有 Collection 的名称。 |
index_params | 包含 IndexParam 对象列表的 IndexParams 对象。 |
sync | 控制与客户端请求相关的索引构建方式。有效值:
|
要为 Collection 创建索引或为 Collection 建立索引,请使用 IndexParam 准备索引参数和 createIndex() 来创建索引。
import io.milvus.v2.common.IndexParam;
import io.milvus.v2.service.index.request.CreateIndexReq;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Collections;
Map<String, Object> extraParams = new HashMap<>();
extraParams.put("nlist", 128);
IndexParam indexParam = IndexParam.builder()
.fieldName("vector")
.indexName("vector_index")
.indexType(IndexParam.IndexType.IVF_FLAT)
.metricType(IndexParam.MetricType.COSINE)
.extraParams(extraParams)
.build();
client.createIndex(CreateIndexReq.builder()
.collectionName("customized_setup")
.indexParams(Collections.singletonList(indexParam))
.build());
要为 Collection 创建索引或为 Collection 创建索引,请使用 createIndex().
await client.createIndex({
"collection_name": "customized_setup",
"field_name": "vector",
"index_name": "vector_index",
"index_type": "IVF_FLAT",
"metric_type": "COSINE",
"params": {
"nlist": 128
}
});
| 参数 | 说明 |
|---|---|
collection_name | 现有 Collection 的名称。 |
field_name | 要创建索引的字段名称。 |
index_type | 要创建索引的类型。 |
metric_type | 用于测量向量距离的度量类型。 |
index_name | 要创建的索引名称。 |
params | 其他特定于索引的参数。 |
idx := index.NewGenericIndex("", map[string]string{
"index_type": "IVF_FLAT",
"metric_type": "COSINE",
"nlist": "128",
})
task, err := client.CreateIndex(
ctx,
milvusclient.NewCreateIndexOption(
"customized_setup",
"vector",
idx,
).WithIndexName("vector_index"),
)
if err != nil {
panic(err)
}
if err := task.Await(ctx); err != nil {
panic(err)
}
curl --request POST \
--url "http://localhost:19530/v2/vectordb/indexes/create" \
--header "Authorization: Bearer root:Milvus" \
--header "Content-Type: application/json" \
--data '{
"collectionName": "customized_setup",
"indexParams": [
{
"fieldName": "vector",
"indexName": "vector_index",
"indexType": "IVF_FLAT",
"metricType": "COSINE",
"params": {
"nlist": 128
}
}
]
}'
备注
目前,只能为 Collection 中的每个字段创建一个索引文件。
检查索引详细信息
创建索引后,可以检查其详细信息。
- Python
- Java
- Node.js
- Go
- cURL
要检查索引详细信息,请使用 list_indexes() 列出索引名称,并用 describe_index() 获取索引详细信息。
index_names = client.list_indexes(collection_name="customized_setup")
print(index_names)
index_info = client.describe_index(
collection_name="customized_setup",
index_name="vector_index",
)
print(index_info)
要检查索引详情,请使用 describeIndex() 获取索引详情。
import io.milvus.v2.service.index.request.DescribeIndexReq;
import io.milvus.v2.service.index.request.ListIndexesReq;
import io.milvus.v2.service.index.response.DescribeIndexResp;
import java.util.List;
List<String> indexNames = client.listIndexes(
ListIndexesReq.builder()
.collectionName("customized_setup")
.build()
);
DescribeIndexResp indexInfo = client.describeIndex(
DescribeIndexReq.builder()
.collectionName("customized_setup")
.indexName("vector_index")
.build()
);
System.out.println(indexNames);
System.out.println(indexInfo);
要检查索引详情,请使用 describeIndex() 获取索引详情。
const indexNames = await client.listIndexes({
collection_name: "customized_setup",
});
const indexInfo = await client.describeIndex({
collection_name: "customized_setup",
index_name: "vector_index",
});
console.log(indexNames.indexes);
console.log(indexInfo.index_descriptions);
indexNames, err := client.ListIndexes(
ctx,
milvusclient.NewListIndexOption("customized_setup"),
)
if err != nil {
panic(err)
}
indexInfo, err := client.DescribeIndex(
ctx,
milvusclient.NewDescribeIndexOption("customized_setup", "vector_index"),
)
if err != nil {
panic(err)
}
fmt.Println(indexNames)
fmt.Println(indexInfo)
curl --request POST \
--url "http://localhost:19530/v2/vectordb/indexes/list" \
--header "Authorization: Bearer root:Milvus" \
--header "Content-Type: application/json" \
--data '{
"collectionName": "customized_setup"
}'
curl --request POST \
--url "http://localhost:19530/v2/vectordb/indexes/describe" \
--header "Authorization: Bearer root:Milvus" \
--header "Content-Type: application/json" \
--data '{
"collectionName": "customized_setup",
"indexName": "vector_index"
}'
您可以检查在特定字段上创建的索引文件,并收集使用该索引文件索引的行数统计。
删除索引
如果不再需要索引,可以直接将其删除。
在丢弃索引之前,首先要确保它已被释放。
- Python
- Java
- Node.js
- Go
- cURL
要删除索引,请使用 drop_index().
client.drop_index(
collection_name="customized_setup",
index_name="vector_index",
)
要删除索引,请使用 dropIndex().
import io.milvus.v2.service.index.request.DropIndexReq;
client.dropIndex(DropIndexReq.builder()
.collectionName("customized_setup")
.indexName("vector_index")
.build());
要删除索引,请使用 dropIndex().
await client.dropIndex({
collection_name: "customized_setup",
index_name: "vector_index",
});
if err := client.DropIndex(
ctx,
milvusclient.NewDropIndexOption("customized_setup", "vector_index"),
); err != nil {
panic(err)
}
curl --request POST \
--url "http://localhost:19530/v2/vectordb/indexes/drop" \
--header "Authorization: Bearer root:Milvus" \
--header "Content-Type: application/json" \
--data '{
"collectionName": "customized_setup",
"indexName": "vector_index"
}'