创建 Collection
您可以通过定义 schema、index 参数、metric 类型以及是否在创建时加载来创建 collection。本页介绍如何从头开始创建 collection。
概述
Collection 是一个具有固定列和可变行的二维表。每列代表一个 field,每行代表一个 entity。需要 schema 来实现这种结构化数据管理。要插入的每个 entity 都必须满足 schema 中定义的约束。
您可以确定 collection 的各个方面,包括其 schema、index 参数、metric 类型以及是否在创建时加载,以确保 collection 完全满足您的要求。
要创建 collection,您需要
创建 Schema
Schema 定义了 collection 的数据结构。创建 collection 时,您需要根据需求设计 schema。有关详细信息,请参阅 Schema 说明。
以下代码片段创建了一个启用动态 field 的 schema,包含三个必需 field:my_id
、my_vector
和 my_varchar
。
您可以为任何标量 field 设置默认值并使其可为空。有关详细信息,请参阅 Nullable & Default。
# 3. Create a collection in customized setup mode
from pymilvus import MilvusClient, DataType
client = MilvusClient(
uri="http://localhost:19530",
token="root:Milvus"
)
# 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 = "http://localhost:19530";
String TOKEN = "root:Milvus";
// 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 = "http://localhost:19530";
const token = "root:Milvus";
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 := "localhost:19530"
client, err := milvusclient.New(ctx, &milvusclient.ClientConfig{
Address: milvusAddr,
})
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
}
}
]
}'
(可选)设置 Index 参数
在特定 field 上创建 index 可以加速对该 field 的搜索。Index 记录 collection 中 entity 的顺序。如以下代码片段所示,您可以使用 metric_type
和 index_type
为 Milvus 选择合适的方式来索引 field 并测量向量嵌入之间的相似性。
在 Milvus 上,您可以使用 AUTOINDEX
作为所有向量 field 的 index 类型,并根据需要使用 COSINE
、L2
和 IP
中的一种作为 metric 类型。
如上面的代码片段所示,您需要为向量 field 设置 index 类型和 metric 类型,而对于标量 field 只需设置 index 类型。向量 field 的 index 是必需的,建议您为经常用于过滤条件的标量 field 创建 index。
有关详细信息,请参阅 Index Vector Fields 和 Index Scalar Fields。
# 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"
}
]'
Create a Collection
如果您使用 index 参数创建了 collection,Milvus 会在创建时自动加载该 collection。在这种情况下,index 参数中提到的所有 field 都会被索引。
以下代码片段演示了如何使用 index 参数创建 collection 并检查其加载状态。
# 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="http://localhost:19530"
export TOKEN="root:Milvus"
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
}"
您也可以创建一个没有任何 index 参数的 collection,然后再添加它们。在这种情况下,Milvus 不会在创建时加载 collection。
以下代码片段演示了如何创建没有 index 的 collection,创建后 collection 的加载状态保持未加载。
# 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="http://localhost:19530"
export TOKEN="root:Milvus"
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\"
}"
设置 Collection 属性
您可以为要创建的 collection 设置属性,以使其适合您的服务。适用的属性如下。
设置 Shard 数量
Shard 是 collection 的水平切片。每个 shard 对应一个数据输入通道。每个 collection 默认有一个 shard。您可以在创建 collection 时根据预期吞吐量和要插入到 collection 中的数据量设置适当的 shard 数量。
在常见情况下,考虑每当预期吞吐量增加 500 MB/s 或要插入的数据量增加 100 GB 时,将 shard 数量增加一个。此建议基于我们自己的经验,可能不完全适合您的应用场景。您可以调整此数字以适合您自己的需求,或者只使用默认值。
以下代码片段演示了如何在创建 collection 时设置 shard 数量。
# 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="http://localhost:19530"
export TOKEN="root:Milvus"
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
Milvus 默认在所有 collection 上启用 mmap,允许 Milvus 将原始 field 数据映射到内存中,而不是完全加载它们。这减少了内存占用并增加了 collection 容量。有关 mmap 的详细信息,请参阅 Use mmap。
# 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="http://localhost:19530"
export TOKEN="root:Milvus"
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
}"
设置 Collection TTL
如果 collection 中的数据需要在特定时间段后删除,请考虑设置其生存时间 (TTL),以秒为单位。一旦 TTL 超时,Milvus 会删除 collection 中的 entity。删除是异步的,表示在删除完成之前仍可以进行搜索和查询。
以下代码片段将 TTL 设置为一天(86400 秒)。建议您将 TTL 设置为至少几天。
# 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="http://localhost:19530"
export TOKEN="root:Milvus"
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
}"
设置一致性级别
创建 collection 时,您可以为 collection 中的搜索和查询设置一致性级别。您也可以在特定搜索或查询期间更改 collection 的一致性级别。
# 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",
# highlight-end
}
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="http://localhost:19530"
export TOKEN="root:Milvus"
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
}"
有关一致性级别的更多信息,请参阅 Consistency Level。
启用动态 Field
Collection 中的动态 field 是一个名为 $meta 的保留 JavaScript Object Notation (JSON) field。一旦启用此 field,Milvus 会将每个 entity 中携带的所有非 schema 定义的 field 及其值作为键值对保存在保留 field 中。
有关如何使用动态 field 的详细信息,请参阅 Dynamic Field.