Collection の作成
schema、index パラメータ、metric type、作成時にロードするかどうかを定義して collection を作成できます。このページでは、collection をゼロから作成する方法を紹介します。
強力なデータ分離が必要で、管理するテナント数が少ない場合は、各テナントごとに個別の collection を作成できます。
ただし、作成できる collection の最大数は、プロジェクトプランと cluster のデプロイオプションに応じて 16,384 までです。したがって、大規模なマルチテナンシーでは、ユースケースに応じて、partition ベースまたは partition-key ベースのマルチテナンシーなどの代替戦略の使用を検討してください。詳細については、マルチテナンシーの実装を参照してください。
Overview
collection は、固定された列と可変の行を持つ二次元テーブルです。各列は field を表し、各行は entity を表します。このような構造化データ管理を実現するには schema が必要です。挿入するすべての entity は、schema で定義された制約を満たしている必要があります。
schema、index パラメータ、metric type、作成時にロードするかどうかなど、collection のあらゆる要素を決定して、要件に完全に適合する collection を作成できます。
collection を作成するには、以下が必要です。
Schema の作成
schema は collection のデータ構造を定義します。collection を作成する際は、要件に基づいて schema を設計する必要があります。詳細については、Schema Explained を参照してください。
以下のコードスニペットでは、動的 field を有効にし、my_id、my_vector、my_varchar という 3 つの必須 field を持つ schema を作成します。
任意の scalar field にデフォルト値を設定し、nullable にすることができます。詳細については、Nullable & Default を参照してください。
- Python
- Java
- NodeJS
- Go
- cURL
- C++
# 3. Create a collection in customized setup mode
from pymilvus import MilvusClient, DataType
client = MilvusClient(
uri="YOUR_CLUSTER_ENDPOINT",
token="YOUR_CLUSTER_TOKEN"
)
# 3.1. Create schema
schema = MilvusClient.create_schema(
auto_id=False,
enable_dynamic_field=True,
)
# 3.2. Add fields to schema
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. Connect to Milvus server
ConnectConfig connectConfig = ConnectConfig.builder()
.uri(CLUSTER_ENDPOINT)
.token(TOKEN)
.build();
MilvusClientV2 client = new MilvusClientV2(connectConfig);
// 3. Create a collection in customized setup mode
// 3.1 Create schema
CreateCollectionReq.CollectionSchema schema = client.createSchema();
// 3.2 Add fields to schema
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. Create a collection in customized setup mode
// 3.1 Define fields
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"
token := "YOUR_CLUSTER_TOKEN"
client, err := milvusclient.New(ctx, &milvusclient.ClientConfig{
Address: milvusAddr,
APIKey: token
})
if err != nil {
fmt.Println(err.Error())
// handle 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
}
}
]
}'
#include "milvus/MilvusClientV2.h"
auto client = milvus::MilvusClientV2::Create();
milvus::ConnectParam connect_param{"YOUR_CLUSTER_ENDPOINT"};
auto status = client->Connect(connect_param);
milvus::CollectionSchemaPtr schema = std::make_shared<milvus::CollectionSchema>();
schema->AddField(milvus::FieldSchema("my_id", milvus::DataType::INT64, "my id", true, false));
schema->AddField(milvus::FieldSchema("my_vector", milvus::DataType::FLOAT_VECTOR).WithDimension(5));
schema->AddField(milvus::FieldSchema("my_varchar", milvus::DataType::VARCHAR).WithMaxLength(512));
(任意)Index パラメータの設定
特定の field に index を作成すると、その field に対する検索が高速化されます。index は、collection 内の entity の順序を記録します。以下のコードスニペットに示すように、metric_type と index_type を使用して、Zilliz Cloud が field に index を作成する適切な方法と、vector 埋め込み間の類似度を測定する方法を選択できます。
Zilliz Cloud では、すべての vector field の index type として AUTOINDEX を使用でき、必要に応じて COSINE、L2、IP のいずれかを metric type として使用できます。
上記のコードスニペットに示したように、vector field には index type と metric type の両方を設定し、scalar field には index type のみを設定する必要があります。vector field では index は必須であり、フィルタ条件で頻繁に使用される scalar field にも index を作成することが推奨されます。
詳細については、Indexes を参照してください。
- Python
- Java
- NodeJS
- Go
- cURL
- C++
# 3.3. Prepare index parameters
index_params = client.prepare_index_params()
# 3.4. Add indexes
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 Prepare index parameters
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 Prepare index parameters
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"
}
]'
#include "milvus/MilvusClientV2.h"
std::vector<milvus::IndexDesc> indexes = {
milvus::IndexDesc("my_vector", "my_vector", milvus::IndexType::AUTOINDEX, milvus::MetricType::COSINE),
milvus::IndexDesc("my_id", "my_id", milvus::IndexType::AUTOINDEX)};
}
Collection の作成
index パラメータ付きで collection を作成した場合、Zilliz Cloud は作成時に自動的に collection をロードします。この場合、index パラメータで指定されたすべての field に index が作成されます。
以下のコードスニペットは、index パラメータ付きで collection を作成し、そのロード状態を確認する方法を示しています。
- Python
- Java
- NodeJS
- Go
- cURL
- C++
# 3.5. Create a collection with the index loaded simultaneously
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)
# Output
#
# {
# "state": "<LoadState: Loaded>"
# }
import io.milvus.v2.service.collection.request.CreateCollectionReq;
import io.milvus.v2.service.collection.request.GetLoadStateReq;
// 3.4 Create a collection with schema and index parameters
CreateCollectionReq customizedSetupReq1 = CreateCollectionReq.builder()
.collectionName("customized_setup_1")
.collectionSchema(schema)
.indexParams(indexParams)
.build();
client.createCollection(customizedSetupReq1);
// 3.5 Get load state of the collection
GetLoadStateReq customSetupLoadStateReq1 = GetLoadStateReq.builder()
.collectionName("customized_setup_1")
.build();
Boolean loaded = client.getLoadState(customSetupLoadStateReq1);
System.out.println(loaded);
// Output:
// true
// 3.3 Create a collection with fields and index parameters
res = await client.createCollection({
collection_name: "customized_setup_1",
fields: fields,
index_params: index_params,
})
console.log(res.error_code)
// Output
//
// Success
//
res = await client.getLoadState({
collection_name: "customized_setup_1"
})
console.log(res.state)
// Output
//
// LoadStateLoaded
//
err = client.CreateCollection(ctx, milvusclient.NewCreateCollectionOption("customized_setup_1", schema).
WithIndexOptions(indexOptions...))
if err != nil {
fmt.Println(err.Error())
// handle 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" \
--header "Request-Timeout: 10" \
-d "{
\"collectionName\": \"customized_setup_1\",
\"schema\": $schema,
\"indexParams\": $indexParams
}"
auto status = client->CreateCollection(milvus::CreateCollectionRequest()
.WithCollectionName("customized_setup_1")
.WithCollectionSchema(schema))
.WithIndexes(std::move(indexes));
if (!status.IsOk()) {
std::cout << status.Message() << std::endl;
}
milvus::GetLoadStateResponse response;
status = client->GetLoadState(milvus::GetLoadStateRequest()
.WithCollectionName("customized_setup_1"),
response);
std::cout << std::to_string(response.State()) << std::endl;
index パラメータなしで collection を作成し、その後で追加することもできます。この場合、Zilliz Cloud は collection 作成時にその collection をロードしません。既存の collection に対して index を作成する方法の詳細については、AUTOINDEX Explained を参照してください。
以下のコードスニペットは、index なしで collection を作成する方法を示しており、collection のロード状態は作成時に未ロードのままになります。
- Python
- Java
- NodeJS
- Go
- cURL
- C++
# 3.6. Create a collection and index it separately
client.create_collection(
collection_name="customized_setup_2",
schema=schema,
)
res = client.get_load_state(
collection_name="customized_setup_2"
)
print(res)
# Output
#
# {
# "state": "<LoadState: NotLoad>"
# }
// 3.6 Create a collection and index it separately
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);
// Output:
// false
// 3.4 Create a collection and index it seperately
res = await client.createCollection({
collection_name: "customized_setup_2",
fields: fields,
})
console.log(res.error_code)
// Output
//
// Success
//
res = await client.getLoadState({
collection_name: "customized_setup_2"
})
console.log(res.state)
// Output
//
// LoadStateNotLoad
//
err = client.CreateCollection(ctx, milvusclient.NewCreateCollectionOption("customized_setup_2", schema))
if err != nil {
fmt.Println(err.Error())
// handle error
}
fmt.Println("collection created")
state, err := client.GetLoadState(ctx, milvusclient.NewGetLoadStateOption("customized_setup_2"))
if err != nil {
fmt.Println(err.Error())
// handle 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" \
--header "Request-Timeout: 10" \
-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" \
--header "Request-Timeout: 10" \
-d "{
\"collectionName\": \"customized_setup_2\"
}"
auto status = client->CreateCollection(milvus::CreateCollectionRequest()
.WithCollectionName("customized_setup_2")
.WithCollectionSchema(schema));
if (!status.IsOk()) {
std::cout << status.Message() << std::endl;
}
milvus::GetLoadStateResponse response;
status = client->GetLoadState(milvus::GetLoadStateRequest()
.WithCollectionName("customized_setup_2"),
response);
std::cout << std::to_string(response.State()) << std::endl;
Collection プロパティの設定
作成する collection には、サービスに適合するようプロパティを設定できます。適用可能なプロパティは以下のとおりです。
Shard 数の設定
Shard は collection の水平方向の分割単位であり、各 shard は 1 つのデータ入力チャネルに対応します。デフォルトでは、すべての collection には 1 つの shard があります。collection の作成時に shard 数を指定することで、データ量やワークロードにより適した構成にできます。
一般的なガイドラインとして、shard 数を設定する際は次の点を考慮してください。
- データサイズ: 一般的な方法として、2 億 entities ごとに 1 つの shard を設定します。総データサイズに基づいて見積もることもでき、たとえば挿入予定のデータ 100 GB ごとに 1 つの shard を追加します。
次のコードスニペットは、collection の作成時に shard 数を設定する方法を示しています。
- Python
- Java
- NodeJS
- Go
- cURL
- C++
# With shard number
client.create_collection(
collection_name="customized_setup_3",
schema=schema,
num_shards=1
)
// With shard number
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())
// handle 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" \
--header "Request-Timeout: 10" \
-d "{
\"collectionName\": \"customized_setup_3\",
\"schema\": $schema,
\"params\": $params
}"
auto status = client->CreateCollection(milvus::CreateCollectionRequest()
.WithCollectionName("customized_setup_3")
.WithCollectionSchema(schema)
.WithNumShards(1));
if (!status.IsOk()) {
std::cout << status.Message() << std::endl;
}
mmap の有効化
Zilliz Cloud では、デフォルトですべての collection で mmap が有効になっており、フィールドの生データを完全に読み込むのではなく、Zilliz Cloud がそれらをメモリにマップできるようになっています。これにより、メモリ使用量が削減され、collection の容量が増加します。mmap の詳細については、Use mmap を参照してください。
- Python
- Java
- NodeJS
- Go
- cURL
- C++
# With mmap
client.create_collection(
collection_name="customized_setup_4",
schema=schema,
enable_mmap=False
)
import io.milvus.param.Constant;
// With 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())
// handle 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" \
--header "Request-Timeout: 10" \
-d "{
\"collectionName\": \"customized_setup_5\",
\"schema\": $schema,
\"params\": $params
}"
auto status = client->CreateCollection(milvus::CreateCollectionRequest()
.WithCollectionName("customized_setup_4")
.WithCollectionSchema(schema)
.AddProperty(milvus::MMAP_ENABLED, "true"));
if (!status.IsOk()) {
std::cout << status.Message() << std::endl;
}
Collection TTL の設定
collection 内のデータを一定期間後に削除する必要がある場合は、Time-To-Live (TTL) を秒単位で設定することを検討してください。TTL が期限切れになると、Zilliz Cloud は collection 内の entities を削除します。この削除は非同期で行われるため、削除が完了するまでの間も search と query は引き続き実行できます。
次のコードスニペットでは、TTL を 1 日(86400 秒)に設定しています。TTL は最低でも数日に設定することを推奨します。
- Python
- Java
- NodeJS
- Go
- cURL
- C++
# With TTL
client.create_collection(
collection_name="customized_setup_5",
schema=schema,
properties={
"collection.ttl.seconds": 86400
}
)
import io.milvus.param.Constant;
// With 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())
// handle 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" \
--header "Request-Timeout: 10" \
-d "{
\"collectionName\": \"customized_setup_5\",
\"schema\": $schema,
\"params\": $params
}"
auto status = client->CreateCollection(milvus::CreateCollectionRequest()
.WithCollectionName("customized_setup_5")
.WithCollectionSchema(schema)
.AddProperty(milvus::COLLECTION_TTL_SECONDS, "86400"));
if (!status.IsOk()) {
std::cout << status.Message() << std::endl;
}
Consistency Level の設定
collection の作成時に、その collection 内での search と query の consistency level を設定できます。特定の search または query の実行時に collection の consistency level を変更することもできます。
- Python
- Java
- NodeJS
- Go
- cURL
- C++
# With consistency level
client.create_collection(
collection_name="customized_setup_6",
schema=schema,
# highlight-next
consistency_level="Bounded",
)
import io.milvus.v2.common.ConsistencyLevel;
// With consistency level
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.createCollection(createCollectionReq);
err = client.CreateCollection(ctx, milvusclient.NewCreateCollectionOption("customized_setup_6", schema).
WithConsistencyLevel(entity.ClBounded))
if err != nil {
fmt.Println(err.Error())
// handle 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" \
--header "Request-Timeout: 10" \
-d "{
\"collectionName\": \"customized_setup_6\",
\"schema\": $schema,
\"params\": $params
}"
auto status = client->CreateCollection(milvus::CreateCollectionRequest()
.WithCollectionName("customized_setup_6")
.WithCollectionSchema(schema)
.WithConsistencyLevel(milvus::ConsistencyLevel::BOUNDED));
if (!status.IsOk()) {
std::cout << status.Message() << std::endl;
}
consistency level の詳細については、Consistency Level を参照してください。
Dynamic Field の有効化
collection の dynamic field は、$meta という名前の予約済み JavaScript Object Notation (JSON) フィールドです。このフィールドを有効にすると、Zilliz Cloud は各 entity に含まれる schema で定義されていないすべてのフィールドとその値を、この予約済みフィールドにキーと値のペアとして保存します。
dynamic field の使用方法の詳細については、Dynamic Field を参照してください。