建立資料集
您可以透過定義模式、索引參數、度量類型,以及是否在建立時載入,來建立集合。本頁面介紹如何從頭開始建立一個集合。
概觀
集合是一個二維表,有固定的列和變異的行。每列代表一個欄位,每行代表一個實體。要實現這種結構性資料管理,需要一個模式。要插入的每個實體都必須符合模式中定義的約束。
您可以決定集合的各個方面,包括其模式、索引參數、度量類型,以及是否在建立時載入,以確保集合完全符合您的需求。
若要建立資料集,您需要
建立模式
模式定義集合的資料結構。建立資料集時,您需要根據需求設計模式。如需詳細資訊,請參閱Schema Explained。
以下程式碼片段建立一個模式,其中包含啟用的動態欄位和三個必填欄位,分別命名為my_id
,my_vector
, 和my_varchar
。
您可以為任何標量欄位設定預設值,並使其可為空。詳情請參閱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 "github.com/milvus-io/milvus/client/v2/entity"
schema := entity.NewSchema().WithDynamicFieldEnabled(true).
WithField(entity.NewField().WithName("my_id").WithIsAutoID(true).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))thDim(5))
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
來選擇適當的方式,讓 Milvus 為欄位建立索引,並衡量向量嵌入之間的相似性。
在 Milvus 中,您可以使用AUTOINDEX
作為所有向量欄位的索引類型,並根據您的需求,使用COSINE
、L2
和IP
中的一種作為度量類型。
如上述程式碼片段所示,您需要同時設定向量欄位的索引類型和公制類型,而標量值欄位則只需設定索引類型。對於向量欄位,索引是必須的,建議您在篩選條件中常用的標量欄位上建立索引。
如需詳細資訊,請參閱索引。
# 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="STL_SORT"
)
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.STL_SORT)
.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: "STL_SORT"
},{
field_name: "my_vector",
index_type: "AUTOINDEX",
metric_type: "COSINE"
}]
import (
"github.com/milvus-io/milvus/client/v2"
"github.com/milvus-io/milvus/client/v2/entity"
"github.com/milvus-io/milvus/client/v2/index"
)
indexOptions := []client.CreateIndexOption{
client.NewCreateIndexOption(collectionName, "my_vector", index.NewAutoIndex(entity.COSINE)).WithIndexName("my_vector"),
client.NewCreateIndexOption(collectionName, "my_id", index.NewSortedIndex()).WithIndexName("my_id"),
}
export indexParams='[
{
"fieldName": "my_vector",
"metricType": "COSINE",
"indexName": "my_vector",
"indexType": "AUTOINDEX"
},
{
"fieldName": "my_id",
"indexName": "my_id",
"indexType": "STL_SORT"
}
]'
建立集合
如果您已經用索引參數建立了一個集合,Milvus 會在建立集合時自動載入。在這種情況下,索引參數中提到的所有欄位都會被索引。
以下程式碼片段示範如何以索引參數建立集合,並檢查其載入狀態。
# 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
//
import "github.com/milvus-io/milvus/client/v2"
err := cli.CreateCollection(ctx, client.NewCreateCollectionOption("customized_setup_1", schema).
WithIndexOptions(indexOptions...),
)
if err != nil {
// 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
}"
您也可以先建立一個沒有索引參數的集合,然後再加入索引參數。在這種情況下,Milvus 在建立集合時不會載入。有關如何為現有的集合建立索引的詳細資訊,請參考Index Explained。
以下程式碼片段示範如何在沒有索引的情況下建立集合,且集合的載入狀態在建立時仍保持未載入狀態。
# 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
//
import "github.com/milvus-io/milvus/client/v2"
err := cli.CreateCollection(ctx, client.NewCreateCollectionOption("customized_setup_2", schema))
if err != nil {
// 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_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\"
}"
Milvus 也提供了一個方法讓你立即建立一個集合。詳情請參閱立即建立集合。
設定集合屬性
你可以為要建立的集合設定屬性,使它適合你的服務。適用的屬性如下。
設定分片編號
分片是集合的水平切片。每個分片對應一個資料輸入通道。每個集合預設都有一個分片。您可以在建立資料集時,根據預期的吞吐量和要插入資料集的資料量,設定適當的分片數量。
在一般情況下,每當預期吞吐量增加 500 MB/秒或要插入的資料量增加 100 GB 時,就考慮增加一個分片。此建議是基於我們自己的經驗,可能不完全符合您的應用程式情境。您可以調整此數字以符合自己的需求,或直接使用預設值。
以下程式碼片段示範如何在建立集合時設定 Shard 編號。
# With shard number
client.create_collection(
collection_name="customized_setup_3",
schema=schema,
# highlight-next-line
num_shards=1
)
// With shard number
CreateCollectionReq customizedSetupReq3 = CreateCollectionReq.builder()
.collectionName("customized_setup_3")
.collectionSchema(collectionSchema)
// highlight-next-line
.numShards(1)
.build();
client.createCollection(customizedSetupReq3);
const createCollectionReq = {
collection_name: "customized_setup_3",
schema: schema,
// highlight-next-line
shards_num: 1
}
import "github.com/milvus-io/milvus/client/v2"
err := cli.CreateCollection(ctx, client.NewCreateCollectionOption("customized_setup_3", schema).WithShardNum(1))
if err != nil {
// 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 在所有集合上預設啟用 mmap,允許 Milvus 將原始欄位資料映射到記憶體,而不是完全載入它們。這可減少記憶體佔用量並增加集合容量。有關 mmap 的詳細資訊,請參閱使用 mmap。
# With mmap
client.create_collection(
collection_name="customized_setup_4",
schema=schema,
# highlight-next-line
enable_mmap=False
)
import io.milvus.param.Constant;
// With MMap
CreateCollectionReq customizedSetupReq4 = CreateCollectionReq.builder()
.collectionName("customized_setup_4")
.collectionSchema(schema)
// highlight-next-line
.property(Constant.MMAP_ENABLED, "false")
.build();
client.createCollection(customizedSetupReq4);
client.create_collection({
collection_name: "customized_setup_4",
schema: schema,
properties: {
'mmap.enabled': true,
},
})
import (
"github.com/milvus-io/milvus/client/v2"
"github.com/milvus-io/milvus/pkg/common"
)
err := cli.CreateCollection(ctx, client.NewCreateCollectionOption("customized_setup_4", schema).WithProperty(common.MmapEnabledKey, true))
if err != nil {
// handle error
}
fmt.Println("collection created")
# Currently not available for REST
設定集合 TTL
如果一個資料集需要在一段特定時間內丟棄,請考慮設定它的 Time-To-Live (TTL),單位為秒。一旦 TTL 超時,Milvus 就會刪除集合中的實體,並丟棄集合。刪除是異步的,表示在刪除完成之前,仍可進行搜尋與查詢。
以下程式碼片段將 TTL 設定為一天 (86400 秒)。建議您至少將 TTL 設定為幾天。
# With TTL
client.create_collection(
collection_name="customized_setup_5",
schema=schema,
# highlight-start
properties={
"collection.ttl.seconds": 86400
}
# highlight-end
)
import io.milvus.param.Constant;
// With TTL
CreateCollectionReq customizedSetupReq5 = CreateCollectionReq.builder()
.collectionName("customized_setup_5")
.collectionSchema(schema)
// highlight-next-line
.property(Constant.TTL_SECONDS, "86400")
.build();
client.createCollection(customizedSetupReq5);
const createCollectionReq = {
collection_name: "customized_setup_5",
schema: schema,
// highlight-start
properties: {
"collection.ttl.seconds": 86400
}
// highlight-end
}
import (
"github.com/milvus-io/milvus/client/v2"
"github.com/milvus-io/milvus/pkg/common"
)
err = cli.CreateCollection(ctx, client.NewCreateCollectionOption("customized_setup_5", schema).
WithProperty(common.CollectionTTLConfigKey, 86400)) // TTL in seconds
if err != nil {
// 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
}"
設定一致性等級
建立資料集時,您可以設定資料集中搜尋與查詢的一致性等級。您也可以在特定搜尋或查詢時變更集合的一致性層級。
# 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)
// highlight-next-line
.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);
import (
"github.com/milvus-io/milvus/client/v2"
"github.com/milvus-io/milvus/client/v2/entity"
)
err := cli.CreateCollection(ctx, client.NewCreateCollectionOption("customized_setup_6", schema).
WithConsistencyLevel(entity.ClBounded))
if err != nil {
// 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
}"
有關一致性層級的更多資訊,請參閱一致性層級。
啟用動態欄位
集合中的動態欄位是一個保留的 JavaScript Object Notation (JSON) 欄位,名為$meta。一旦啟用這個欄位,Milvus 會將每個實體中所有非模式定義的欄位及其值儲存為保留欄位中的鍵值對。
有關如何使用動態欄位的詳細資訊,請參閱動態欄位。