スカラーフィールドのインデックス
Zilliz Cloudは、特に大規模なデータセットにおいて、フィルタリングおよび検索パフォーマンスを大幅に高速化するために、スカラーフィールド(非ベクトルフィールド)のインデックス作成をサポートしています。
概要
スカラーフィールドのインデックス作成は任意ですが、フィルター条件で特定のスカラーフィールドに頻繁にアクセスする場合は推奨されます。
Zilliz Cloudは、以下のフィールドタイプに対してAUTOINDEXをサポートしています。
フィールドタイプ | 説明 |
|---|---|
| 文字列 |
| 整数 |
| 浮動小数点数 |
| ブール値 |
| スカラー値の同種配列 |
| 空間情報を格納するジオメトリックデータ |
事前準備
インデックスを作成する前に、ベクトルフィールドとスカラーフィールドの両方を含むコレクションを定義します。Zilliz Cloudでは、すべてのコレクションにベクトルフィールドが必要です。
この例では、必須のベクトルフィールド(vector)とDOUBLE型のスカラーフィールド(price)を含む商品カタログのスキーマを定義します。
- Python
- Java
- NodeJS
- Go
- cURL
from pymilvus import MilvusClient, DataType
client = MilvusClient(uri="YOUR_CLUSTER_ENDPOINT") # ご使用のクラスターエンドポイントに置き換えてください
# 動的フィールドサポート付きスキーマを定義
schema = client.create_schema(
auto_id=False,
enable_dynamic_field=True # 動的フィールドを有効化
)
# フィールドを定義
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) # ベクトルフィールド
schema.add_field(field_name="price", datatype=DataType.DOUBLE) # スカラーフィールド
# コレクションを作成
client.create_collection(
collection_name="product_catalog",
schema=schema
)
import io.milvus.v2.client.*;
import io.milvus.v2.service.collection.request.CreateCollectionReq;
import io.milvus.v2.service.collection.request.AddFieldReq;
ConnectConfig config = ConnectConfig.builder()
.uri("YOUR_CLUSTER_ENDPOINT")
.build();
MilvusClientV2 client = new MilvusClientV2(config);
CreateCollectionReq.CollectionSchema schema = CreateCollectionReq.CollectionSchema.builder()
.enableDynamicField(true)
.build();
schema.addField(AddFieldReq.builder()
.fieldName("product_id")
.dataType(DataType.Int64)
.isPrimaryKey(Boolean.TRUE)
.build());
schema.addField(AddFieldReq.builder()
.fieldName("vector")
.dataType(DataType.FloatVector)
.dimension(5)
.build());
schema.addField(AddFieldReq.builder()
.fieldName("price")
.dataType(DataType.Double)
.build());
CreateCollectionReq requestCreate = CreateCollectionReq.builder()
.collectionName("product_catalog")
.collectionSchema(schema)
.build();
client.createCollection(requestCreate);
import { MilvusClient, DataType } from '@zilliz/milvus2-sdk-node';
// クライアントを初期化
const client = new MilvusClient({
address: 'YOUR_CLUSTER_ENDPOINT', // ご使用のクラスターエンドポイントに置き換えてください
});
const collectionName = 'product_catalog';
// スキーマを定義
const schema = [
{
name: 'product_id',
description: '主キー',
data_type: DataType.Int64,
is_primary_key: true,
autoID: false,
},
{
name: 'vector',
description: '埋め込みベクトル',
data_type: DataType.FloatVector,
type_params: {
dim: '5',
},
},
{
name: 'price',
description: '商品価格',
data_type: DataType.Double,
},
];
// コレクションを作成
const res = await client.createCollection({
collection_name: collectionName,
fields: schema,
enable_dynamic_field: true,
});
console.log('コレクション作成結果:', res);
import (
"context"
"github.com/milvus-io/milvus/client/v2/entity"
"github.com/milvus-io/milvus/client/v2/milvusclient"
)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
client, err := milvusclient.New(ctx, &milvusclient.ClientConfig{
Address: "YOUR_CLUSTER_ENDPOINT",
})
if err != nil {
return err
}
schema := entity.NewSchema().WithDynamicFieldEnabled(true)
schema.WithField(entity.NewField().
WithName("product_id").pk
WithDataType(entity.FieldTypeInt64).
WithIsPrimaryKey(true),
).WithField(entity.NewField().
WithName("vector").
WithDataType(entity.FieldTypeFloatVector).
WithDim(5),
).WithField(entity.NewField().
WithName("price").
WithDataType(entity.FieldTypeDouble),
)
err = client.CreateCollection(ctx, milvusclient.NewCreateCollectionOption("product_catalog", schema))
if err != nil {
return err
}
export TOKEN="YOUR_CLUSTER_TOKEN"
export CLUSTER_ENDPOINT="YOUR_CLUSTER_ENDPOINT"
export productIdField='{
"fieldName": "product_id",
"dataType": "Int64",
"isPrimary": true,
"autoID": false
}'
export vectorField='{
"fieldName": "vector",
"dataType": "FloatVector",
"elementTypeParams": {
"dim": 5
}
}'
export priceField='{
"fieldName": "price",
"dataType": "Double"
}'
export schema="{
\"autoID\": false,
\"enableDynamicField\": true,
\"fields\": [
$productIdField,
$vectorField,
$priceField
]
}"
curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/collections/create" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
--data "{
\"collectionName\": \"product_catalog\",
\"schema\": $schema
}"
スカラーフィールドにインデックスを作成
AUTOINDEXを使用してスカラーフィールドにインデックスを作成できます。追加のインデックスパラメータは必要ありません。以下の例では、priceフィールドにインデックスを作成します。
- Python
- Java
- NodeJS
- Go
- cURL
index_params = client.prepare_index_params() # どのインデックスパラメータも指定せずに、空のIndexParamsオブジェクトを準備
index_params.add_index(
field_name="price", # インデックス対象のスカラーフィールド名
index_type="AUTOINDEX", # 作成するインデックスの種類
index_name="price_index" # 作成するインデックス名
)
import io.milvus.v2.common.IndexParam;
List<IndexParam> indexParams = new ArrayList<>();
indexParams.add(IndexParam.builder()
.fieldName("price")
.indexName("price_index")
.indexType(IndexParam.IndexType.AUTOINDEX)
.build());
const indexParams = [{
collection_name: collectionName,
field_name: 'price',
index_type: 'AUTOINDEX',
index_name: 'price_index'
}];
import (
"github.com/milvus-io/milvus/client/v2/index"
)
indexOpt := client.NewCreateIndexOption("product_catalog", "price",
index.NewInvertedIndex())
export priceIndex='{
"fieldName": "price",
"indexName": "price_index",
"params": {
"index_type": "AUTOINDEX"
}
}'
インデックスパラメータを定義したら、create_index()を使用してコレクションに適用できます。
- Python
- Java
- NodeJS
- Go
- cURL
client.create_index(
collection_name="product_catalog",
index_params=index_params
)
import io.milvus.v2.service.index.request.CreateIndexReq;
client.createIndex(CreateIndexReq.builder()
.collectionName("product_catalog")
.indexParams(indexParams)
.build());
client.createIndex(indexParams)
indexTask1, err := client.CreateIndex(ctx, indexOpt1)
if err != nil {
return err
}
indexTask2, err := client.CreateIndex(ctx, indexOpt2)
if err != nil {
return err
}
indexTask3, err := client.CreateIndex(ctx, indexOpt3)
if err != nil {
return err
}
indexTask4, err := client.CreateIndex(ctx, indexOpt4)
if err != nil {
return err
}
curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/indexes/create" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
--data "{
\"collectionName\": \"product_catalog\",
\"indexParams\": [$priceIndex]
}"
インデックスの詳細を確認
インデックスを作成した後、その詳細を確認できます。
- Python
- Java
- NodeJS
# インデックスを説明
res = client.list_indexes(
collection_name="product_catalog"
)
print(res)
res = client.describe_index(
collection_name="product_catalog",
index_name="price_index"
)
print(res)
import io.milvus.v2.service.index.request.DescribeIndexReq;
import io.milvus.v2.service.index.response.DescribeIndexResp;
// インデックスを説明
// インデックス名を一覧表示
ListIndexesReq listIndexesReq = ListIndexesReq.builder()
.collectionName("product_catalog")
.build();
List<String> indexNames = client.listIndexes(listIndexesReq);
System.out.println(indexNames);
// インデックスを説明
DescribeIndexReq describeIndexReq = DescribeIndexReq.builder()
.collectionName("product_catalog")
.indexName("price_index")
.build();
DescribeIndexResp describeIndexResp = client.describeIndex(describeIndexReq);
System.out.println(JSONObject.toJSON(describeIndexResp));
// インデックスを説明
res = await client.describeIndex({
collection_name: "product_catalog",
index_name: "price_index"
})
console.log(JSON.stringify(res.index_descriptions, null, 2))
インデックスを削除
必要なくなった場合、簡単にインデックスを削除できます。
- Python
- Java
- NodeJS
# インデックスを削除
client.drop_index(
collection_name="product_catalog",
index_name="price_index"
)
// インデックスを削除
DropIndexReq dropIndexReq = DropIndexReq.builder()
.collectionName("product_catalog")
.indexName("price_index")
.build();
client.dropIndex(dropIndexReq);
// インデックスを削除
res = await client.dropIndex({
collection_name: "product_catalog",
index_name: "price_index"
})
console.log(res.error_code)
高度な機能
スカラーインデックスに関する他にも、ご興味をお持ちいただける高度な機能がいくつかあります。
NGRAM [READ MORE]
Zilliz Cloudの`NGRAM`インデックスは、`VARCHAR`フィールドまたは`JSON`フィールド内の特定のJSONパスの`LIKE`クエリを高速化するために構築されています。インデックスを構築する前に、Zilliz Cloudはテキストを固定長nの短い重複するサブストリングに分割します。これはn-gramとして知られています。例えば、n = 3の場合、単語「Milvus」は3-gramの「Mil」、「ilv」、「lvu」、および「vus」に分割されます。これらのn-gramは、各グラムをそのグラムが出現するドキュメントIDにマッピングする反転インデックスに格納されます。クエリ時には、このインデックスによりZilliz Cloudは検索を候補の少数に迅速に絞り込むことができ、はるかに高速なクエリ実行が可能になります。