コレクションの作成
スキーマ、インデックスパラメータ、メトリックタイプ、および作成時にロードするかどうかを定義することで、コレクションを作成できます。このページでは、ゼロからコレクションを作成する方法を紹介します。
強力なデータ分離を必要とし、少数のテナントのみを管理する場合は、各テナントに個別のコレクションを作成できます。
ただし、クラスタープランに応じて最大16,384個のコレクションしか作成できません。したがって、大規模なマルチテナンシーについては、使用ケースに応じてパーティションベースまたはパーティションキーベースのマルチテナンシーなどの代替戦略を検討してください。詳細については、マルチテナンシーの実装を参照してください。
概要
コレクションは固定列と可変行の2次元テーブルです。各列はフィールドを表し、各行はエンティティを表します。このような構造的データ管理を実装するにはスキーマが必要です。挿入するすべてのエンティティは、スキーマで定義された制約を満たす必要があります。
コレクションのすべての側面(スキーマ、インデックスパラメータ、メトリックタイプ、作成時のロードの有無)を決定して、コレクションが要件を完全に満たすようにできます。
コレクションを作成するには、次の手順が必要です:
-
インデックスパラメータの設定(オプション)
スキーマの作成
スキーマはコレクションのデータ構造を定義します。コレクションを作成する際には、要件に応じてスキーマを設計する必要があります。詳細については、スキーマの説明を参照してください。
以下のコードスニペットは、有効なダイナミックフィールドと、my_id、my_vector、my_varcharという名前の3つの必須フィールドを持つスキーマを作成します。
任意のスカラーフィールドにデフォルト値を設定し、NULLを許容するようにできます。詳細については、NULL許容とデフォルトを参照してください。
- Python
- Java
- NodeJS
- Go
- cURL
# 3. カスタマイズされたセットアップモードでコレクションを作成
from pymilvus import MilvusClient, DataType
client = MilvusClient(
uri="YOUR_CLUSTER_ENDPOINT",
token="YOUR_CLUSTER_TOKEN"
)
# 3.1. スキーマの作成
schema = MilvusClient.create_schema(
auto_id=False,
enable_dynamic_field=True,
)
# 3.2. スキーマにフィールドを追加
schema.add_field(field_name="my_id", datatype=DataType.INT64, is_primary=True)
schema.add_field(field_name="my_vector", datatype=DataType.FLOAT_VECTOR, dim=5)
schema.add_field(field_name="my_varchar", datatype=DataType.VARCHAR, max_length=512)
import io.milvus.v2.common.DataType;
import io.milvus.v2.client.ConnectConfig;
import io.milvus.v2.client.MilvusClientV2;
import io.milvus.v2.service.collection.request.AddFieldReq;
import io.milvus.v2.service.collection.request.CreateCollectionReq;
String CLUSTER_ENDPOINT = "YOUR_CLUSTER_ENDPOINT";
String TOKEN = "YOUR_CLUSTER_TOKEN";
// 1. Milvusサーバーに接続
ConnectConfig connectConfig = ConnectConfig.builder()
.uri(CLUSTER_ENDPOINT)
.token(TOKEN)
.build();
MilvusClientV2 client = new MilvusClientV2(connectConfig);
// 3. カスタマイズされたセットアップモードでコレクションを作成
// 3.1 スキーマの作成
CreateCollectionReq.CollectionSchema schema = client.createSchema();
// 3.2 スキーマにフィールドを追加
schema.addField(AddFieldReq.builder()
.fieldName("my_id")
.dataType(DataType.Int64)
.isPrimaryKey(true)
.autoID(false)
.build());
schema.addField(AddFieldReq.builder()
.fieldName("my_vector")
.dataType(DataType.FloatVector)
.dimension(5)
.build());
schema.addField(AddFieldReq.builder()
.fieldName("my_varchar")
.dataType(DataType.VarChar)
.maxLength(512)
.build());
import { MilvusClient, DataType } from "@zilliz/milvus2-sdk-node";
const address = "YOUR_CLUSTER_ENDPOINT";
const token = "YOUR_CLUSTER_TOKEN";
const client = new MilvusClient({address, token});
// 3. カスタマイズされたセットアップモードでコレクションを作成
// 3.1 フィールドの定義
const fields = [
{
name: "my_id",
data_type: DataType.Int64,
is_primary_key: true,
auto_id: false
},
{
name: "my_vector",
data_type: DataType.FloatVector,
dim: 5
},
{
name: "my_varchar",
data_type: DataType.VarChar,
max_length: 512
}
]
import (
"context"
"fmt"
"github.com/milvus-io/milvus/client/v2/entity"
"github.com/milvus-io/milvus/client/v2/index"
"github.com/milvus-io/milvus/client/v2/milvusclient"
"github.com/milvus-io/milvus/pkg/v2/common"
)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
milvusAddr := "YOUR_CLUSTER_ENDPOINT"
client, err := milvusclient.New(ctx, &milvusclient.ClientConfig{
Address: milvusAddr,
})
if err != nil {
fmt.Println(err.Error())
// エラー処理
}
defer client.Close(ctx)
schema := entity.NewSchema().WithDynamicFieldEnabled(true).
WithField(entity.NewField().WithName("my_id").WithIsAutoID(false).WithDataType(entity.FieldTypeInt64).WithIsPrimaryKey(true)).
WithField(entity.NewField().WithName("my_vector").WithDataType(entity.FieldTypeFloatVector).WithDim(5)).
WithField(entity.NewField().WithName("my_varchar").WithDataType(entity.FieldTypeVarChar).WithMaxLength(512))
export schema='{
"autoId": false,
"enabledDynamicField": false,
"fields": [
{
"fieldName": "my_id",
"dataType": "Int64",
"isPrimary": true
},
{
"fieldName": "my_vector",
"dataType": "FloatVector",
"elementTypeParams": {
"dim": "5"
}
},
{
"fieldName": "my_varchar",
"dataType": "VarChar",
"elementTypeParams": {
"max_length": 512
}
}
]
}'
(オプション)インデックスパラメータの設定
特定のフィールドにインデックスを作成すると、そのフィールドに対する検索が高速化されます。インデックスはコレクション内のエンティティの順序を記録します。以下のコードスニペットに示すように、metric_typeとindex_typeを使用して、Zilliz Cloudがフィールドにインデックスを作成し、ベクトル埋め込み間の類似性を測定する適切な方法を選択できます。
Zilliz Cloudでは、すべてのベクトルフィールドにインデックスタイプとしてAUTOINDEXを使用でき、必要に応じてメトリックタイプとしてCOSINE、L2、およびIPのいずれかを使用できます。
上記のコードスニペットに示されているように、ベクトルフィールドにはインデックスタイプとメトリックタイプの両方を設定し、スカラーフィールドにはインデックスタイプのみを設定する必要があります。ベクトルフィールドにはインデックスが必須であり、フィルター条件で頻繁に使用されるスカラーフィールドにはインデックスを作成することをお勧めします。
詳細については、インデックスの管理を参照してください。
- Python
- Java
- NodeJS
- Go
- cURL
# 3.3. インデックスパラメータの準備
index_params = client.prepare_index_params()
# 3.4. インデックスを追加
index_params.add_index(
field_name="my_id",
index_type="AUTOINDEX"
)
index_params.add_index(
field_name="my_vector",
index_type="AUTOINDEX",
metric_type="COSINE"
)
import io.milvus.v2.common.IndexParam;
import java.util.*;
// 3.3 インデックスパラメータの準備
IndexParam indexParamForIdField = IndexParam.builder()
.fieldName("my_id")
.indexType(IndexParam.IndexType.AUTOINDEX)
.build();
IndexParam indexParamForVectorField = IndexParam.builder()
.fieldName("my_vector")
.indexType(IndexParam.IndexType.AUTOINDEX)
.metricType(IndexParam.MetricType.COSINE)
.build();
List<IndexParam> indexParams = new ArrayList<>();
indexParams.add(indexParamForIdField);
indexParams.add(indexParamForVectorField);
// 3.2 インデックスパラメータの準備
const index_params = [{
field_name: "my_id",
index_type: "AUTOINDEX"
},{
field_name: "my_vector",
index_type: "AUTOINDEX",
metric_type: "COSINE"
}]
import (
"github.com/milvus-io/milvus/client/v2/entity"
"github.com/milvus-io/milvus/client/v2/index"
"github.com/milvus-io/milvus/client/v2/milvusclient"
)
collectionName := "customized_setup_1"
indexOptions := []milvusclient.CreateIndexOption{
milvusclient.NewCreateIndexOption(collectionName, "my_vector", index.NewAutoIndex(entity.COSINE)),
milvusclient.NewCreateIndexOption(collectionName, "my_id", index.NewAutoIndex(entity.COSINE)),
}
export indexParams='[
{
"fieldName": "my_vector",
"metricType": "COSINE",
"indexName": "my_vector",
"indexType": "AUTOINDEX"
},
{
"fieldName": "my_id",
"indexName": "my_id",
"indexType": "AUTOINDEX"
}
]'
コレクションの作成
インデックスパラメータでコレクションを作成すると、Zilliz Cloudはコレクションの作成時に自動的にロードします。この場合、インデックスパラメータで言及されているすべてのフィールドにインデックスが作成されます。
以下のコードスニペットは、インデックスパラメータでコレクションを作成し、そのロード状態を確認する方法を示しています。
- Python
- Java
- NodeJS
- Go
- cURL
# 3.5. インデックスを同時にロードしたコレクションを作成
client.create_collection(
collection_name="customized_setup_1",
schema=schema,
index_params=index_params
)
res = client.get_load_state(
collection_name="customized_setup_1"
)
print(res)
# 出力
#
# {
# "state": "<LoadState: Loaded>"
# }
import io.milvus.v2.service.collection.request.CreateCollectionReq;
import io.milvus.v2.service.collection.request.GetLoadStateReq;
// 3.4 スキーマとインデックスパラメータを使用してコレクションを作成
CreateCollectionReq customizedSetupReq1 = CreateCollectionReq.builder()
.collectionName("customized_setup_1")
.collectionSchema(schema)
.indexParams(indexParams)
.build();
client.createCollection(customizedSetupReq1);
// 3.5 コレクションのロード状態を取得
GetLoadStateReq customSetupLoadStateReq1 = GetLoadStateReq.builder()
.collectionName("customized_setup_1")
.build();
Boolean loaded = client.getLoadState(customSetupLoadStateReq1);
System.out.println(loaded);
// 出力:
// true
// 3.3 フィールドとインデックスパラメータでコレクションを作成
res = await client.createCollection({
collection_name: "customized_setup_1",
fields: fields,
index_params: index_params,
})
console.log(res.error_code)
// 出力
//
// Success
//
res = await client.getLoadState({
collection_name: "customized_setup_1"
})
console.log(res.state)
// 出力
//
// LoadStateLoaded
//
err = client.CreateCollection(ctx, milvusclient.NewCreateCollectionOption("customized_setup_1", schema).
WithIndexOptions(indexOptions...))
if err != nil {
fmt.Println(err.Error())
// エラー処理
}
fmt.Println("collection created")
export CLUSTER_ENDPOINT="YOUR_CLUSTER_ENDPOINT"
export TOKEN="YOUR_CLUSTER_TOKEN"
curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/collections/create" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
-d "{
\"collectionName\": \"customized_setup_1\",
\"schema\": $schema,
\"indexParams\": $indexParams
}"
インデックスパラメータを指定せずにコレクションを作成し、後でそれらを追加することもできます。この場合、Zilliz Cloudはコレクションの作成時にコレクションをロードしません。既存のコレクションにインデックスを作成する方法の詳細については、AUTOINDEXの説明を参照してください。
以下のコードスニペットは、インデックスなしでコレクションを作成する方法を示しており、コレクションのロード状態は作成時にロードされていない状態になります。
- Python
- Java
- NodeJS
- Go
- cURL
# 3.6. コレクションを作成し、別途インデックスを作成
client.create_collection(
collection_name="customized_setup_2",
schema=schema,
)
res = client.get_load_state(
collection_name="customized_setup_2"
)
print(res)
# 出力
#
# {
# "state": "<LoadState: NotLoad>"
# }
// 3.6 コレクションを作成し、別途インデックスを作成
CreateCollectionReq customizedSetupReq2 = CreateCollectionReq.builder()
.collectionName("customized_setup_2")
.collectionSchema(schema)
.build();
client.createCollection(customizedSetupReq2);
GetLoadStateReq customSetupLoadStateReq2 = GetLoadStateReq.builder()
.collectionName("customized_setup_2")
.build();
Boolean loaded = client.getLoadState(customSetupLoadStateReq2);
System.out.println(loaded);
// 出力:
// false
// 3.4 コレクションを作成し、別途インデックスを作成
res = await client.createCollection({
collection_name: "customized_setup_2",
fields: fields,
})
console.log(res.error_code)
// 出力
//
// Success
//
res = await client.getLoadState({
collection_name: "customized_setup_2"
})
console.log(res.state)
// 出力
//
// LoadStateNotLoad
//
err = client.CreateCollection(ctx, milvusclient.NewCreateCollectionOption("customized_setup_2", schema))
if err != nil {
fmt.Println(err.Error())
// エラー処理
}
fmt.Println("collection created")
state, err := client.GetLoadState(ctx, milvusclient.NewGetLoadStateOption("customized_setup_2"))
if err != nil {
fmt.Println(err.Error())
// エラー処理
}
fmt.Println(state.State)
export CLUSTER_ENDPOINT="YOUR_CLUSTER_ENDPOINT"
export TOKEN="YOUR_CLUSTER_TOKEN"
curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/collections/create" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
-d "{
\"collectionName\": \"customized_setup_2\",
\"schema\": $schema
}"
curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/collections/get_load_state" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
-d "{
\"collectionName\": \"customized_setup_2\"
}"
コレクションプロパティの設定
サービスに適したコレクションを作成するために、コレクションに対してプロパティを設定できます。適用可能なプロパティは以下のとおりです。
シャード数の設定
シャードはコレクションの水平分割であり、各シャードはデータ入力チャネルに対応します。デフォルトでは、すべてのコレクションには1つのシャードがあります。データ量とワークロードに適したシャード数を指定してコレクションを作成できます。
シャード数を設定する際の一般的なガイドラインは以下のとおりです:
- データサイズ: 一般的な方法は2億エンティティにつき1つのシャードです。計画されている挿入データの合計データサイズに基づいて推定することもできます。たとえば、挿入するデータの100GBにつき1つのシャードを追加します。
以下のコードスニペットは、コレクションを作成する際にシャード数を設定する方法を示しています。
- Python
- Java
- NodeJS
- Go
- cURL
# シャード数の指定
client.create_collection(
collection_name="customized_setup_3",
schema=schema,
num_shards=1
)
// シャード数の指定
CreateCollectionReq customizedSetupReq3 = CreateCollectionReq.builder()
.collectionName("customized_setup_3")
.collectionSchema(collectionSchema)
.numShards(1)
.build();
client.createCollection(customizedSetupReq3);
const createCollectionReq = {
collection_name: "customized_setup_3",
schema: schema,
shards_num: 1
}
err = client.CreateCollection(ctx, milvusclient.NewCreateCollectionOption("customized_setup_3", schema).WithShardNum(1))
if err != nil {
fmt.Println(err.Error())
// エラー処理
}
fmt.Println("collection created")
export params='{
"shardsNum": 1
}'
export CLUSTER_ENDPOINT="YOUR_CLUSTER_ENDPOINT"
export TOKEN="YOUR_CLUSTER_TOKEN"
curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/collections/create" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
-d "{
\"collectionName\": \"customized_setup_3\",
\"schema\": $schema,
\"params\": $params
}"
mmapの有効化
Zilliz Cloudはデフォルトですべてのコレクションでmmapを有効にしており、Zilliz Cloudが生フィールドデータを完全にロードする代わりにメモリにマッピングできるようにしています。これにより、メモリフットプリントが削減され、コレクションの容量が増加します。mmapの詳細については、mmapの使用を参照してください。
- Python
- Java
- NodeJS
- Go
# mmapの指定
client.create_collection(
collection_name="customized_setup_4",
schema=schema,
enable_mmap=False
)
import io.milvus.param.Constant;
// MMapの指定
CreateCollectionReq customizedSetupReq4 = CreateCollectionReq.builder()
.collectionName("customized_setup_4")
.collectionSchema(schema)
.property(Constant.MMAP_ENABLED, "false")
.build();
client.createCollection(customizedSetupReq4);
client.create_collection({
collection_name: "customized_setup_4",
schema: schema,
properties: {
'mmap.enabled': true,
},
})
err = client.CreateCollection(ctx, milvusclient.NewCreateCollectionOption("customized_setup_4", schema).
WithProperty(common.MmapEnabledKey, true))
if err != nil {
fmt.Println(err.Error())
// エラー処理
}
fmt.Println("collection created")
export params='{
"mmap.enabled": True
}'
export CLUSTER_ENDPOINT="YOUR_CLUSTER_ENDPOINT"
export TOKEN="YOUR_CLUSTER_TOKEN"
curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/collections/create" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
-d "{
\"collectionName\": \"customized_setup_5\",
\"schema\": $schema,
\"params\": $params
}"
コレクションTTLの設定
コレクション内のデータを特定の期間後に削除する必要がある場合は、秒単位でそのTime-To-Live(TTL)を設定することを検討してください。TTLがタイムアウトすると、Zilliz Cloudはコレクション内のエンティティを削除します。削除は非同期であるため、削除が完了する前までは検索およびクエリが可能です。
以下のコードスニペットは、TTLを1日(86400秒)に設定します。最低でも数日間はTTLを設定することをお勧めします。
- Python
- Java
- NodeJS
- Go
- cURL
# TTLの指定
client.create_collection(
collection_name="customized_setup_5",
schema=schema,
properties={
"collection.ttl.seconds": 86400
}
)
import io.milvus.param.Constant;
// TTLの指定
CreateCollectionReq customizedSetupReq5 = CreateCollectionReq.builder()
.collectionName("customized_setup_5")
.collectionSchema(schema)
.property(Constant.TTL_SECONDS, "86400")
.build();
client.createCollection(customizedSetupReq5);
const createCollectionReq = {
collection_name: "customized_setup_5",
schema: schema,
properties: {
"collection.ttl.seconds": 86400
}
}
err = client.CreateCollection(ctx, milvusclient.NewCreateCollectionOption("customized_setup_5", schema).
WithProperty(common.CollectionTTLConfigKey, true))
if err != nil {
fmt.Println(err.Error())
// エラー処理
}
fmt.Println("collection created")
export params='{
"ttlSeconds": 86400
}'
export CLUSTER_ENDPOINT="YOUR_CLUSTER_ENDPOINT"
export TOKEN="YOUR_CLUSTER_TOKEN"
curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/collections/create" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
-d "{
\"collectionName\": \"customized_setup_5\",
\"schema\": $schema,
\"params\": $params
}"
一貫性レベルの設定
コレクションを作成する際には、コレクション内の検索およびクエリの一貫性レベルを設定できます。特定の検索またはクエリ中にコレクションの一貫性レベルを変更することもできます。
- Python
- Java
- NodeJS
- Go
- cURL
# 一貫性レベルの指定
client.create_collection(
collection_name="customized_setup_6",
schema=schema,
# highlight-next
consistency_level="Bounded",
)
import io.milvus.v2.common.ConsistencyLevel;
// 一貫性レベルの指定
CreateCollectionReq customizedSetupReq6 = CreateCollectionReq.builder()
.collectionName("customized_setup_6")
.collectionSchema(schema)
.consistencyLevel(ConsistencyLevel.BOUNDED)
.build();
client.createCollection(customizedSetupReq6);
const createCollectionReq = {
collection_name: "customized_setup_6",
schema: schema,
// highlight-next
consistency_level: "Bounded",
}
client.cre... [truncated]
</TabItem>
<TabItem value='go'>
```go
err = client.CreateCollection(ctx, milvusclient.NewCreateCollectionOption("customized_setup_6", schema).
WithConsistencyLevel(entity.ClBounded))
if err != nil {
fmt.Println(err.Error())
// エラー処理
}
fmt.Println("collection created")
export params='{
"consistencyLevel": "Bounded"
}'
export CLUSTER_ENDPOINT="YOUR_CLUSTER_ENDPOINT"
export TOKEN="YOUR_CLUSTER_TOKEN"
curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/collections/create" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
-d "{
\"collectionName\": \"customized_setup_6\",
\"schema\": $schema,
\"params\": $params
}"
一貫性レベルの詳細については、一貫性レベルを参照してください。
ダイナミックフィールドの有効化
コレクション内のダイナミックフィールドは、$metaという名前の予約済みJavaScript Object Notation(JSON)フィールドです。このフィールドを有効にすると、Zilliz Cloudは各エンティティに含まれるスキーマ定義されていないすべてのフィールドとその値を、予約済みフィールド内にキーバリューペアとして保存します。
ダイナミックフィールドの使い方の詳細については、ダイナミックフィールドを参照してください。