主键字段与自动生成ID
Milvus 中的每个 Collection 都必须有一个主字段,用于唯一标识每个实体。该字段可确保对每个实体的插入、更新、查询或删除操作均无歧义。
根据您的具体用例,您可以选择让 Milvus 自动生成 ID(AutoID),也可以手动分配 ID。
什么是主字段?
主字段作为 Collection 中每个实体的唯一标识符,类似于传统数据库中的主键。Milvus 利用主字段在插入、更新、删除和查询操作中管理实体。
关键要求:
每个Collection必须且仅有一个主字段。
主字段的值不能为空。
数据类型必须在创建时指定,且之后无法更改。
支持的数据类型
主字段必须使用受支持的标量数据类型,且该类型能够唯一标识实体。
数据类型 |
描述 |
|---|---|
|
64 位整数类型,通常与 AutoID 一起使用。对于大多数用例,这是推荐的选项。 |
|
可变长度字符串类型。当实体标识符来自外部系统(例如产品代码或用户 ID)时,请使用此类型。需要通过 |
在 AutoID 和手动 ID 之间进行选择
Milvus 支持两种主键值分配模式。
模式 |
描述 |
推荐用于 |
|---|---|---|
AutoID |
Milvus 会为插入或导入的实体自动生成唯一标识符。 |
大多数情况下,您无需手动管理 ID。 |
手动 ID |
在插入或导入数据时,由您自行提供唯一 ID。 |
当 ID 必须与外部系统或现有数据集保持一致时。 |
如果您不确定应选择哪种模式,建议先使用“自动ID”(AutoID),这样不仅能简化数据导入流程,还能确保ID的唯一性。
除非手动设置主键能带来好处,否则建议在所有情况下都依赖
autoId。
快速入门:使用“AutoID”
您可以让 Milvus 自动处理 ID 生成。
步骤 1:创建一个启用 AutoID 的 Collection
在主字段定义中启用auto_id=True 。Milvus将自动处理ID生成。
from pymilvus import MilvusClient, DataType
client = MilvusClient(uri="http://localhost:19530")
schema = client.create_schema()
# Define primary field with AutoID enabled
schema.add_field(
field_name="id", # Primary field name
is_primary=True,
auto_id=True, # Milvus generates IDs automatically; Defaults to False
datatype=DataType.INT64
)
# Define the other fields
schema.add_field(field_name="embedding", datatype=DataType.FLOAT_VECTOR, dim=4) # Vector field
schema.add_field(field_name="category", datatype=DataType.VARCHAR, max_length=1000) # Scalar field of the VARCHAR type
# Create the collection
if client.has_collection("demo_autoid"):
client.drop_collection("demo_autoid")
client.create_collection(collection_name="demo_autoid", schema=schema)
import io.milvus.v2.client.ConnectConfig;
import io.milvus.v2.client.MilvusClientV2;
import io.milvus.v2.common.DataType;
import io.milvus.v2.service.collection.request.AddFieldReq;
import io.milvus.v2.service.collection.request.CreateCollectionReq;
import io.milvus.v2.service.collection.request.DropCollectionReq;
MilvusClientV2 client = new MilvusClientV2(ConnectConfig.builder()
.uri("http://localhost:19530")
.build());
CreateCollectionReq.CollectionSchema collectionSchema = CreateCollectionReq.CollectionSchema.builder()
.build();
collectionSchema.addField(AddFieldReq.builder()
.fieldName("id")
.dataType(DataType.Int64)
.isPrimaryKey(true)
.autoID(true)
.build());
collectionSchema.addField(AddFieldReq.builder()
.fieldName("embedding")
.dataType(DataType.FloatVector)
.dimension(4)
.build());
collectionSchema.addField(AddFieldReq.builder()
.fieldName("category")
.dataType(DataType.VarChar)
.maxLength(1000)
.build());
client.dropCollection(DropCollectionReq.builder()
.collectionName("demo_autoid")
.build());
CreateCollectionReq requestCreate = CreateCollectionReq.builder()
.collectionName("demo_autoid")
.collectionSchema(collectionSchema)
.build();
client.createCollection(requestCreate);
import (
"context"
"fmt"
"log"
"github.com/milvus-io/milvus/client/v3/entity"
"github.com/milvus-io/milvus/client/v3/milvusclient"
)
ctx := context.Background()
cli, err := milvusclient.New(ctx, &milvusclient.ClientConfig{
Address: "http://localhost:19530",
APIKey: "root:Milvus",
})
if err != nil {
log.Fatal("failed to connect:", err)
}
defer cli.Close(ctx)
schema := &entity.Schema{
CollectionName: "demo_autoid",
Fields: []*entity.Field{
entity.NewField().WithName("id").WithDataType(entity.FieldTypeInt64).WithIsPrimaryKey(true).WithIsAutoID(true),
entity.NewField().WithName("embedding").WithDataType(entity.FieldTypeFloatVector).WithDim(4),
entity.NewField().WithName("category").WithDataType(entity.FieldTypeVarChar).WithMaxLength(1000),
},
}
cli.DropCollection(ctx, milvusclient.NewDropCollectionOption("demo_autoid"))
err = cli.CreateCollection(ctx, milvusclient.NewCreateCollectionOption("demo_autoid", schema))
if err != nil {
log.Fatal("failed to create collection:", err)
}
use milvus::v2::prelude::*;
let client = ClientV2::new(
&ConnectConfig::new()
.uri("http://localhost:19530")
.token("root:Milvus"),
)
.await?;
let schema = CollectionSchema::new()
.add_field(
FieldSchema::new()
.name("id")
.data_type(DataType::Int64)
.primary_key(true)
.auto_id(true),
)
.add_field(
FieldSchema::new()
.name("embedding")
.data_type(DataType::FloatVector)
.dimension(4),
)
.add_field(
FieldSchema::new()
.name("category")
.data_type(DataType::VarChar)
.max_length(1000),
);
if client
.has_collection(
HasCollectionRequest::builder()
.collection_name("demo_autoid")
.build()?,
)
.await?
.exists()
{
client
.drop_collection(
DropCollectionRequest::builder()
.collection_name("demo_autoid")
.build()?,
)
.await?;
}
client
.create_collection(
CreateCollectionRequest::builder()
.collection_name("demo_autoid")
.schema(schema)
.build()?,
)
.await?;
#include <iostream>
#include "milvus/MilvusClientV2.h"
auto client = milvus::MilvusClientV2::Create();
milvus::ConnectParam connect_param{"http://localhost:19530", "root:Milvus"};
auto status = client->Connect(connect_param);
if (!status.IsOk()) {
std::cout << status.Message() << std::endl;
}
milvus::CollectionSchemaPtr schema = std::make_shared<milvus::CollectionSchema>();
schema->AddField({"id", milvus::DataType::INT64, "Primary field", true, true});
schema->AddField(milvus::FieldSchema("embedding", milvus::DataType::FLOAT_VECTOR, "Vector field").WithDimension(4));
schema->AddField(milvus::FieldSchema("category", milvus::DataType::VARCHAR, "Scalar field").WithMaxLength(1000));
status = client->DropCollection(milvus::DropCollectionRequest().WithCollectionName("demo_autoid"));
if (!status.IsOk()) {
std::cout << status.Message() << std::endl;
}
status = client->CreateCollection(milvus::CreateCollectionRequest()
.WithCollectionName("demo_autoid")
.WithCollectionSchema(schema));
if (!status.IsOk()) {
std::cout << status.Message() << std::endl;
}
import { MilvusClient, DataType } from "@zilliz/milvus2-sdk-node";
const client = new MilvusClient({
address: "http://localhost:19530",
});
// Define schema fields
const schema = [
{
name: "id",
description: "Primary field",
data_type: DataType.Int64,
is_primary_key: true,
autoID: true, // Milvus generates IDs automatically
},
{
name: "embedding",
description: "Vector field",
data_type: DataType.FloatVector,
dim: 4,
},
{
name: "category",
description: "Scalar field",
data_type: DataType.VarChar,
max_length: 1000,
},
];
// Create the collection
await client.createCollection({
collection_name: "demo_autoid",
fields: schema,
});
using Milvus.Client.V2;
using Milvus.Client.V2.Requests.Collection;
using Milvus.Client.V2.Types;
var client = new MilvusClientV2(new ConnectConfig
{
Uri = "http://localhost:19530",
ApiKey = "root:Milvus"
});
await client.ConnectAsync();
var schema = new CollectionSchema
{
Fields =
{
new FieldSchema("id", DataType.Int64, isPrimaryKey: true, autoId: true), // Milvus generates IDs automatically
FieldSchema.CreateFloatVector("embedding", dimension: 4), // Vector field
FieldSchema.CreateVarchar("category", maxLength: 1000) // Scalar field of the VARCHAR type
}
};
if ((await client.HasCollectionAsync(new HasCollectionReq { CollectionName = "demo_autoid" })).Has)
{
await client.DropCollectionAsync(new DropCollectionReq { CollectionName = "demo_autoid" });
}
await client.CreateCollectionAsync(new CreateCollectionReq
{
CollectionName = "demo_autoid",
Schema = schema
});
# restful
export SCHEMA='{
"autoID": true,
"fields": [
{
"fieldName": "id",
"dataType": "Int64",
"isPrimary": true,
"elementTypeParams": {}
},
{
"fieldName": "embedding",
"dataType": "FloatVector",
"isPrimary": false,
"elementTypeParams": {
"dim": "4"
}
},
{
"fieldName": "category",
"dataType": "VarChar",
"isPrimary": false,
"elementTypeParams": {
"max_length": "1000"
}
}
]
}'
curl -X POST 'http://localhost:19530/v2/vectordb/collections/create' \
-H 'Content-Type: application/json' \
-H "Request-Timeout: 10" \
-d "{
\"collectionName\": \"demo_autoid\",
\"schema\": $SCHEMA
}"
步骤 2:插入数据
重要提示:请勿在数据中包含主键字段。Milvus 会自动生成 ID。
data = [
{"embedding": [0.1, 0.2, 0.3, 0.4], "category": "book"},
{"embedding": [0.2, 0.3, 0.4, 0.5], "category": "toy"},
]
res = client.insert(collection_name="demo_autoid", data=data)
print("Generated IDs:", res.get("ids"))
# Output example:
# Generated IDs: [461526052788333649, 461526052788333650]
import com.google.gson.*;
import io.milvus.v2.service.vector.request.InsertReq;
import io.milvus.v2.service.vector.response.InsertResp;
import java.util.ArrayList;
import java.util.List;
List<JsonObject> rows = new ArrayList<>();
Gson gson = new Gson();
JsonObject row1 = new JsonObject();
row1.add("embedding", gson.toJsonTree(new float[]{0.1f, 0.2f, 0.3f, 0.4f}));
row1.addProperty("category", "book");
rows.add(row1);
JsonObject row2 = new JsonObject();
row2.add("embedding", gson.toJsonTree(new float[]{0.2f, 0.3f, 0.4f, 0.5f}));
row2.addProperty("category", "toy");
rows.add(row2);
InsertResp insertR = client.insert(InsertReq.builder()
.collectionName("demo_autoid")
.data(rows)
.build());
System.out.printf("Generated IDs: %s\n", insertR.getPrimaryKeys());
import (
"fmt"
"log"
"github.com/milvus-io/milvus/client/v3/milvusclient"
)
data := []any{
map[string]any{"embedding": []float32{0.1, 0.2, 0.3, 0.4}, "category": "book"},
map[string]any{"embedding": []float32{0.2, 0.3, 0.4, 0.5}, "category": "toy"},
}
result, err := cli.Insert(ctx, milvusclient.NewRowBasedInsertOption("demo_autoid", data...))
if err != nil {
log.Fatal("failed to insert:", err)
}
for i := 0; i < result.IDs.Len(); i++ {
id, _ := result.IDs.GetAsInt64(i)
fmt.Println("Generated ID:", id)
}
use milvus::v2::prelude::*;
client
.insert(
InsertRequest::builder()
.collection_name("demo_autoid")
.rows([
serde_json::json!({"embedding": [0.1, 0.2, 0.3, 0.4], "category": "book"}),
serde_json::json!({"embedding": [0.2, 0.3, 0.4, 0.5], "category": "toy"}),
])
.build()?,
)
.await?;
#include <iostream>
milvus::EntityRows data = {{{"embedding", std::vector<float>{0.1, 0.2, 0.3, 0.4}}, {"category", "book"}},
{{"embedding", std::vector<float>{0.2, 0.3, 0.4, 0.5}}, {"category", "toy"}}};
milvus::InsertResponse response;
auto status = client->Insert(milvus::InsertRequest()
.WithCollectionName("demo_autoid")
.WithRowsData(std::move(data))
, response);
if (!status.IsOk()) {
std::cout << status.Message() << std::endl;
}
auto ids = response.Results().IdArray().IntIDArray();
const data = [
{"embedding": [0.1, 0.2, 0.3, 0.4], "category": "book"},
{"embedding": [0.2, 0.3, 0.4, 0.5], "category": "toy"},
];
const res = await client.insert({
collection_name: "demo_autoid",
fields_data: data,
});
console.log(res);
using Milvus.Client.V2;
using Milvus.Client.V2.Requests.Dml;
using Milvus.Client.V2.Responses.Dml;
using Milvus.Client.V2.Types;
var data = new[]
{
new Dictionary<string, object?>
{
["embedding"] = new[] { 0.1f, 0.2f, 0.3f, 0.4f },
["category"] = "book"
},
new Dictionary<string, object?>
{
["embedding"] = new[] { 0.2f, 0.3f, 0.4f, 0.5f },
["category"] = "toy"
}
};
MutationResp res = await client.InsertAsync(new InsertReq
{
CollectionName = "demo_autoid",
RowsData = data
});
Console.WriteLine("Generated IDs: " + string.Join(", ", res.LongIds ?? []));
# restful
export INSERT_DATA='[
{
"embedding": [0.1, 0.2, 0.3, 0.4],
"category": "book"
},
{
"embedding": [0.2, 0.3, 0.4, 0.5],
"category": "toy"
}
]'
curl -X POST 'http://localhost:19530/v2/vectordb/entities/insert' \
-H 'Content-Type: application/json' \
-H "Request-Timeout: 10" \
-d "{
\"collectionName\": \"demo_autoid\",
\"data\": $INSERT_DATA
}"
处理现有实体时,请使用 `upsert() ` 代替 `insert() `,以避免 ID 重复错误。
使用手动 ID
如果您需要手动控制 ID,请禁用 AutoID 并提供自定义值。
步骤 1:创建不启用 AutoID 的 Collection
from pymilvus import MilvusClient, DataType
client = MilvusClient(uri="http://localhost:19530")
schema = client.create_schema()
# Define the primary field without AutoID
schema.add_field(
field_name="product_id",
is_primary=True,
auto_id=False, # You'll provide IDs manually at data ingestion
datatype=DataType.VARCHAR,
max_length=100 # Required when datatype is VARCHAR
)
# Define the other fields
schema.add_field(field_name="embedding", datatype=DataType.FLOAT_VECTOR, dim=4) # Vector field
schema.add_field(field_name="category", datatype=DataType.VARCHAR, max_length=1000) # Scalar field of the VARCHAR type
# Create the collection
if client.has_collection("demo_manual_ids"):
client.drop_collection("demo_manual_ids")
client.create_collection(collection_name="demo_manual_ids", schema=schema)
import io.milvus.v2.client.ConnectConfig;
import io.milvus.v2.client.MilvusClientV2;
import io.milvus.v2.common.DataType;
import io.milvus.v2.service.collection.request.AddFieldReq;
import io.milvus.v2.service.collection.request.CreateCollectionReq;
import io.milvus.v2.service.collection.request.DropCollectionReq;
MilvusClientV2 client = new MilvusClientV2(ConnectConfig.builder()
.uri("http://localhost:19530")
.build());
CreateCollectionReq.CollectionSchema collectionSchema = CreateCollectionReq.CollectionSchema.builder()
.build();
collectionSchema.addField(AddFieldReq.builder()
.fieldName("product_id")
.dataType(DataType.VarChar)
.isPrimaryKey(true)
.autoID(false)
.maxLength(100)
.build());
collectionSchema.addField(AddFieldReq.builder()
.fieldName("embedding")
.dataType(DataType.FloatVector)
.dimension(4)
.build());
collectionSchema.addField(AddFieldReq.builder()
.fieldName("category")
.dataType(DataType.VarChar)
.maxLength(1000)
.build());
client.dropCollection(DropCollectionReq.builder()
.collectionName("demo_manual_ids")
.build());
CreateCollectionReq requestCreate = CreateCollectionReq.builder()
.collectionName("demo_manual_ids")
.collectionSchema(collectionSchema)
.build();
client.createCollection(requestCreate);
import (
"context"
"fmt"
"log"
"github.com/milvus-io/milvus/client/v3/entity"
"github.com/milvus-io/milvus/client/v3/milvusclient"
)
ctx := context.Background()
cli, err := milvusclient.New(ctx, &milvusclient.ClientConfig{
Address: "http://localhost:19530",
APIKey: "root:Milvus",
})
if err != nil {
log.Fatal("failed to connect:", err)
}
defer cli.Close(ctx)
schema := &entity.Schema{
CollectionName: "demo_manual_ids",
Fields: []*entity.Field{
entity.NewField().WithName("product_id").WithDataType(entity.FieldTypeVarChar).WithIsPrimaryKey(true).WithMaxLength(100),
entity.NewField().WithName("embedding").WithDataType(entity.FieldTypeFloatVector).WithDim(4),
entity.NewField().WithName("category").WithDataType(entity.FieldTypeVarChar).WithMaxLength(1000),
},
}
cli.DropCollection(ctx, milvusclient.NewDropCollectionOption("demo_manual_ids"))
err = cli.CreateCollection(ctx, milvusclient.NewCreateCollectionOption("demo_manual_ids", schema))
if err != nil {
log.Fatal("failed to create collection:", err)
}
use milvus::v2::prelude::*;
let client = ClientV2::new(
&ConnectConfig::new()
.uri("http://localhost:19530")
.token("root:Milvus"),
)
.await?;
let schema = CollectionSchema::new()
.add_field(
FieldSchema::new()
.name("product_id")
.data_type(DataType::VarChar)
.primary_key(true)
.max_length(100),
)
.add_field(
FieldSchema::new()
.name("embedding")
.data_type(DataType::FloatVector)
.dimension(4),
)
.add_field(
FieldSchema::new()
.name("category")
.data_type(DataType::VarChar)
.max_length(1000),
);
if client
.has_collection(
HasCollectionRequest::builder()
.collection_name("demo_manual_ids")
.build()?,
)
.await?
.exists()
{
client
.drop_collection(
DropCollectionRequest::builder()
.collection_name("demo_manual_ids")
.build()?,
)
.await?;
}
client
.create_collection(
CreateCollectionRequest::builder()
.collection_name("demo_manual_ids")
.schema(schema)
.build()?,
)
.await?;
#include <iostream>
#include "milvus/MilvusClientV2.h"
auto client = milvus::MilvusClientV2::Create();
milvus::ConnectParam connect_param{"http://localhost:19530"};
auto status = client->Connect(connect_param);
if (!status.IsOk()) {
std::cout << status.Message() << std::endl;
}
milvus::CollectionSchemaPtr schema = std::make_shared<milvus::CollectionSchema>();
schema->AddField(milvus::FieldSchema("product_id", milvus::DataType::VARCHAR, "", true, false).WithMaxLength(100));
schema->AddField(milvus::FieldSchema("embedding", milvus::DataType::FLOAT_VECTOR).WithDimension(4));
schema->AddField(milvus::FieldSchema("category", milvus::DataType::VARCHAR).WithMaxLength(1000));
status = client->DropCollection(milvus::DropCollectionRequest().WithCollectionName("demo_manual_ids"));
if (!status.IsOk()) {
std::cout << status.Message() << std::endl;
}
status = client->CreateCollection(milvus::CreateCollectionRequest()
.WithCollectionName("demo_manual_ids")
.WithCollectionSchema(schema));
if (!status.IsOk()) {
std::cout << status.Message() << std::endl;
}
import { MilvusClient, DataType } from "@zilliz/milvus2-sdk-node";
const client = new MilvusClient({
address: "http://localhost:19530",
});
const schema = [
{
name: "product_id",
data_type: DataType.VarChar,
is_primary_key: true,
autoID: false,
max_length: 100,
},
{
name: "embedding",
data_type: DataType.FloatVector,
dim: 4,
},
{
name: "category",
data_type: DataType.VarChar,
max_length: 1000,
},
];
await client.createCollection({
collection_name: "demo_manual_ids",
fields: schema,
});
using Milvus.Client.V2;
using Milvus.Client.V2.Requests.Collection;
using Milvus.Client.V2.Types;
var client = new MilvusClientV2(new ConnectConfig
{
Uri = "http://localhost:19530",
ApiKey = "root:Milvus"
});
await client.ConnectAsync();
var schema = new CollectionSchema
{
Fields =
{
FieldSchema.CreateVarchar("product_id", maxLength: 100, isPrimaryKey: true, autoId: false), // You provide IDs manually
FieldSchema.CreateFloatVector("embedding", dimension: 4), // Vector field
FieldSchema.CreateVarchar("category", maxLength: 1000) // Scalar field of the VARCHAR type
}
};
if ((await client.HasCollectionAsync(new HasCollectionReq { CollectionName = "demo_manual_ids" })).Has)
{
await client.DropCollectionAsync(new DropCollectionReq { CollectionName = "demo_manual_ids" });
}
await client.CreateCollectionAsync(new CreateCollectionReq
{
CollectionName = "demo_manual_ids",
Schema = schema
});
# restful
export SCHEMA='{
"autoID": false,
"fields": [
{
"fieldName": "product_id",
"dataType": "VarChar",
"isPrimary": true,
"elementTypeParams": {
"max_length": "100"
}
},
{
"fieldName": "embedding",
"dataType": "FloatVector",
"isPrimary": false,
"elementTypeParams": {
"dim": "4"
}
},
{
"fieldName": "category",
"dataType": "VarChar",
"isPrimary": false,
"elementTypeParams": {
"max_length": "1000"
}
}
]
}'
curl -X POST 'http://localhost:19530/v2/vectordb/collections/create' \
-H 'Content-Type: application/json' \
-H "Request-Timeout: 10" \
-d "{
\"collectionName\": \"demo_manual_ids\",
\"schema\": $SCHEMA
}"
步骤 2:使用自定义 ID 插入数据
在每次插入操作中,都必须包含主键字段。
# Each entity must contain the primary field `product_id`
data = [
{"product_id": "PROD-001", "embedding": [0.1, 0.2, 0.3, 0.4], "category": "book"},
{"product_id": "PROD-002", "embedding": [0.2, 0.3, 0.4, 0.5], "category": "toy"},
]
res = client.insert(collection_name="demo_manual_ids", data=data)
print("Generated IDs:", res.get("ids"))
# Output example:
# Generated IDs: ['PROD-001', 'PROD-002']
import com.google.gson.*;
import io.milvus.v2.service.vector.request.InsertReq;
import io.milvus.v2.service.vector.response.InsertResp;
import java.util.ArrayList;
import java.util.List;
List<JsonObject> rows = new ArrayList<>();
Gson gson = new Gson();
JsonObject row1 = new JsonObject();
row1.addProperty("product_id", "PROD-001");
row1.add("embedding", gson.toJsonTree(new float[]{0.1f, 0.2f, 0.3f, 0.4f}));
row1.addProperty("category", "book");
rows.add(row1);
JsonObject row2 = new JsonObject();
row2.addProperty("product_id", "PROD-002");
row2.add("embedding", gson.toJsonTree(new float[]{0.2f, 0.3f, 0.4f, 0.5f}));
row2.addProperty("category", "toy");
rows.add(row2);
InsertResp insertR = client.insert(InsertReq.builder()
.collectionName("demo_manual_ids")
.data(rows)
.build());
System.out.printf("Generated IDs: %s\n", insertR.getPrimaryKeys());
import (
"fmt"
"log"
"github.com/milvus-io/milvus/client/v3/milvusclient"
)
data = []any{
map[string]any{"product_id": "PROD-001", "embedding": []float32{0.1, 0.2, 0.3, 0.4}, "category": "book"},
map[string]any{"product_id": "PROD-002", "embedding": []float32{0.2, 0.3, 0.4, 0.5}, "category": "toy"},
}
result, err = cli.Insert(ctx, milvusclient.NewRowBasedInsertOption("demo_manual_ids", data...))
if err != nil {
log.Fatal("failed to insert:", err)
}
for i := 0; i < result.IDs.Len(); i++ {
id, _ := result.IDs.GetAsString(i)
fmt.Println("Inserted ID:", id)
}
use milvus::v2::prelude::*;
client
.insert(
InsertRequest::builder()
.collection_name("demo_manual_ids")
.rows([
serde_json::json!({"product_id": "PROD-001", "embedding": [0.1, 0.2, 0.3, 0.4], "category": "book"}),
serde_json::json!({"product_id": "PROD-002", "embedding": [0.2, 0.3, 0.4, 0.5], "category": "toy"}),
])
.build()?,
)
.await?;
#include <iostream>
milvus::EntityRows data = {{{"product_id", "PROD-001"}, {"embedding", std::vector<float>{0.1, 0.2, 0.3, 0.4}}, {"category", "book"}},
{{"product_id", "PROD-002"}, {"embedding", std::vector<float>{0.2, 0.3, 0.4, 0.5}}, {"category", "toy"}}};
milvus::InsertResponse response;
auto status = client->Insert(milvus::InsertRequest()
.WithCollectionName("demo_manual_ids")
.WithRowsData(std::move(data))
, response);
if (!status.IsOk()) {
std::cout << status.Message() << std::endl;
}
auto string_ids = response.Results().IdArray().StrIDArray();
const data = [
{"product_id": "PROD-001", "embedding": [0.1, 0.2, 0.3, 0.4], "category": "book"},
{"product_id": "PROD-002", "embedding": [0.2, 0.3, 0.4, 0.5], "category": "toy"},
];
const insert = await client.insert({
collection_name: "demo_manual_ids",
fields_data: data,
});
console.log(insert);
using Milvus.Client.V2;
using Milvus.Client.V2.Requests.Dml;
using Milvus.Client.V2.Responses.Dml;
using Milvus.Client.V2.Types;
// Each entity must contain the primary field `product_id`
var data = new[]
{
new Dictionary<string, object?>
{
["product_id"] = "PROD-001",
["embedding"] = new[] { 0.1f, 0.2f, 0.3f, 0.4f },
["category"] = "book"
},
new Dictionary<string, object?>
{
["product_id"] = "PROD-002",
["embedding"] = new[] { 0.2f, 0.3f, 0.4f, 0.5f },
["category"] = "toy"
}
};
MutationResp res = await client.InsertAsync(new InsertReq
{
CollectionName = "demo_manual_ids",
RowsData = data
});
Console.WriteLine("Generated IDs: " + string.Join(", ", res.StringIds ?? []));
# restful
export INSERT_DATA='[
{
"product_id": "PROD-001",
"embedding": [0.1, 0.2, 0.3, 0.4],
"category": "book"
},
{
"product_id": "PROD-002",
"embedding": [0.2, 0.3, 0.4, 0.5],
"category": "toy"
}
]'
# 插入数据
curl -X POST 'http://localhost:19530/v2/vectordb/entities/insert' \
-H 'Content-Type: application/json' \
-H "Request-Timeout: 10" \
-d "{
\"collectionName\": \"demo_manual_ids\",
\"data\": $INSERT_DATA
}"
您的职责:
确保所有实体中的 ID 均唯一
在每次插入/导入操作中都包含主键字段
自行处理ID冲突和重复检测
高级用法
迁移包含现有自动生成ID的数据
若要在数据迁移过程中保留现有 ID,请通过调用 `alter_collection_properties ` 方法启用 `allow_insert_auto_id ` 属性。当该属性设置为 `true` 时,即使启用了自动 ID 功能,Milvus 也会接受用户提供的 ID。
有关配置的详细信息,请参阅“修改Collection”。
确保跨集群的全局 AutoID 唯一性
在运行多个 Milvus 集群时,请为每个集群配置唯一的集群 ID,以确保 AutoID 绝不重叠。
配置:在初始化集群之前,编辑milvus.yaml 中的common.clusterID 配置:
common:
clusterID: 3 # Must be unique across all clusters (Range: 0-7)
在此配置中,clusterID 指定了 AutoID 生成所使用的唯一标识符,范围为 0 到 7(最多支持八个集群)。
Milvus 会在内部处理位反转,以确保未来扩展时 ID 不会发生冲突。除设置集群 ID 外,无需进行其他手动配置。
参考:AutoID 的工作原理
了解 AutoID 在内部如何生成唯一标识符,有助于您正确配置集群 ID并排查与 ID 相关的问题。
AutoID 采用结构化的 64 位格式来保证唯一性:
[sign_bit][cluster_id][physical_ts][logical_ts]
分段 |
描述 |
|---|---|
|
保留供内部使用 |
|
标识生成该 ID 的集群(取值范围:0-7) |
|
生成 ID 时的毫秒级时间戳 |
|
用于区分在同一毫秒内生成的 ID 的计数器 |
即使启用了 AutoID 且数据类型为 `VARCHAR `,Milvus 仍会生成数值 ID。这些 ID 以数值字符串的形式存储,最大长度为 20 个字符(uint64 范围)。