Modificar colección
Puede cambiar el nombre de una colección o modificar su configuración. Esta página se centra en cómo modificar una colección.
Cambiar el nombre de una colección
Puedes renombrar una colección de la siguiente manera.
from pymilvus import MilvusClient
client = MilvusClient(
uri="http://localhost:19530",
token="root:Milvus"
)
client.rename_collection(
old_name="my_collection",
new_name="my_new_collection"
)
import io.milvus.v2.service.collection.request.RenameCollectionReq;
import io.milvus.v2.client.ConnectConfig;
import io.milvus.v2.client.MilvusClientV2;
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);
RenameCollectionReq renameCollectionReq = RenameCollectionReq.builder()
.collectionName("my_collection")
.newCollectionName("my_new_collection")
.build();
client.renameCollection(renameCollectionReq);
import { MilvusClient, DataType } from "@zilliz/milvus2-sdk-node";
const address = "http://localhost:19530";
const token = "root:Milvus";
const client = new MilvusClient({address, token});
const res = await client.renameCollection({
oldName: "my_collection",
newName: "my_new_collection"
});
import (
"context"
"fmt"
"github.com/milvus-io/milvus/client/v2/milvusclient"
)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
milvusAddr := "localhost:19530"
token := "root:Milvus"
client, err := milvusclient.New(ctx, &milvusclient.ClientConfig{
Address: milvusAddr,
APIKey: token,
})
if err != nil {
fmt.Println(err.Error())
// handle error
}
defer client.Close(ctx)
err = client.RenameCollection(ctx, milvusclient.NewRenameCollectionOption("my_collection", "my_new_collection"))
if err != nil {
fmt.Println(err.Error())
// handle error
}
export CLUSTER_ENDPOINT="http://localhost:19530"
export TOKEN="root:Milvus"
curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/collections/rename" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
-d '{
"collectionName": "my_collection",
"newCollectionName": "my_new_collection"
}'
Establecer propiedades de la colección
Puede modificar las propiedades a nivel de colección después de crear una colección.
Propiedades admitidas
Propiedad |
Descripción |
|---|---|
|
Si los datos de una colección necesitan ser borrados después de un periodo específico, considere establecer su Tiempo de Vida (TTL) en segundos. Una vez que el TTL se agota, Milvus elimina todas las entidades de la colección. El borrado es asíncrono, lo que indica que las búsquedas y consultas siguen siendo posibles antes de que se complete el borrado. Para más detalles, consulte Establecer TTL de la colección. |
|
El mapeo de memoria (Mmap) permite el acceso directo en memoria a grandes archivos en disco, permitiendo a Milvus almacenar índices y datos tanto en memoria como en discos duros. Este enfoque ayuda a optimizar la política de colocación de datos basada en la frecuencia de acceso, ampliando la capacidad de almacenamiento de las colecciones sin afectar al rendimiento de la búsqueda. Para más detalles, consulte Utilizar mmap. |
|
Con el Aislamiento de Clave de Partición activado, Milvus agrupa las entidades basándose en el valor de la Clave de Partición y crea un índice separado para cada uno de estos grupos. Al recibir una petición de búsqueda, Milvus localiza el índice basado en el valor de la Clave de Partición especificado en la condición de filtrado y restringe el ámbito de búsqueda dentro de las entidades incluidas en el índice, evitando así escanear entidades irrelevantes durante la búsqueda y mejorando enormemente el rendimiento de la búsqueda. Para obtener más información, consulte Utilizar aislamiento de clave de partición. |
|
Habilita el campo dinámico para las colecciones que se crearon sin habilitarlo. Una vez habilitado, puede insertar entidades con campos no definidos en el esquema original. Para obtener más información, consulte Campo dinámico. |
|
Si se permite que una colección acepte valores de clave primaria proporcionados por el usuario cuando se ha habilitado AutoID para la colección.
|
|
Especifica la zona horaria por defecto para esta colección cuando se manejan operaciones sensibles al tiempo, especialmente los campos |
Ejemplo 1: Establecer TTL de recogida
El siguiente fragmento de código muestra cómo establecer el TTL de la colección.
from pymilvus import MilvusClient
client.alter_collection_properties(
collection_name="my_collection",
properties={"collection.ttl.seconds": 60}
)
import io.milvus.v2.service.collection.request.AlterCollectionReq;
import java.util.HashMap;
import java.util.Map;
Map<String, String> properties = new HashMap<>();
properties.put("collection.ttl.seconds", "60");
AlterCollectionReq alterCollectionReq = AlterCollectionReq.builder()
.collectionName("my_collection")
.properties(properties)
.build();
client.alterCollection(alterCollectionReq);
res = await client.alterCollection({
collection_name: "my_collection",
properties: {
"collection.ttl.seconds": 60
}
})
err = client.AlterCollectionProperties(ctx, milvusclient.NewAlterCollectionPropertiesOption("my_collection").WithProperty(common.CollectionTTLConfigKey, 60))
if err != nil {
fmt.Println(err.Error())
// handle error
}
export CLUSTER_ENDPOINT="http://localhost:19530"
export TOKEN="root:Milvus"
curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/collections/alter_properties" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
-d '{
"collectionName": "test_collection",
"properties": {
"collection.ttl.seconds": 60
}
}'
Ejemplo 2: Activar mmap
El siguiente fragmento de código muestra cómo activar mmap.
from pymilvus import MilvusClient
client.alter_collection_properties(
collection_name="my_collection",
properties={"mmap.enabled": True}
)
Map<String, String> properties = new HashMap<>();
properties.put("mmap.enabled", "True");
AlterCollectionReq alterCollectionReq = AlterCollectionReq.builder()
.collectionName("my_collection")
.properties(properties)
.build();
client.alterCollection(alterCollectionReq);
await client.alterCollectionProperties({
collection_name: "my_collection",
properties: {
"mmap.enabled": true
}
});
err = client.AlterCollectionProperties(ctx, milvusclient.NewAlterCollectionPropertiesOption("my_collection").WithProperty(common.MmapEnabledKey, true))
if err != nil {
fmt.Println(err.Error())
// handle error
}
# restful
curl -X POST "http://localhost:19530/v2/vectordb/collections/alter_properties" \
-H "Content-Type: application/json" \
-d '{
"collectionName": "my_collection",
"properties": {
"mmap.enabled": "true"
}
}'
Ejemplo 3: Habilitar partition key
El siguiente fragmento de código muestra cómo habilitar la clave de partición.
from pymilvus import MilvusClient
client.alter_collection_properties(
collection_name="my_collection",
properties={"partitionkey.isolation": True}
)
Map<String, String> properties = new HashMap<>();
properties.put("partitionkey.isolation", "True");
AlterCollectionReq alterCollectionReq = AlterCollectionReq.builder()
.collectionName("my_collection")
.properties(properties)
.build();
client.alterCollection(alterCollectionReq);
await client.alterCollectionProperties({
collection_name: "my_collection",
properties: {
"partitionkey.isolation": true
}
});
err = client.AlterCollectionProperties(ctx, milvusclient.NewAlterCollectionPropertiesOption("my_collection").WithProperty(common.PartitionKeyIsolationKey, true))
if err != nil {
fmt.Println(err.Error())
// handle error
}
# restful
curl -X POST "http://localhost:19530/v2/vectordb/collections/alter_properties" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <token>" \
-d '{
"collectionName": "my_collection",
"properties": {
"partitionkey.isolation": "true"
}
}'
Ejemplo 4: Habilitar campo dinámico
El siguiente fragmento de código muestra cómo habilitar el campo dinámico.
from pymilvus import MilvusClient
client.alter_collection_properties(
collection_name="my_collection",
properties={"dynamicfield.enabled": True}
)
Map<String, String> properties = new HashMap<>();
properties.put("dynamicfield.enabled", "True");
AlterCollectionReq alterCollectionReq = AlterCollectionReq.builder()
.collectionName("my_collection")
.properties(properties)
.build();
client.alterCollection(alterCollectionReq);
await client.alterCollectionProperties({
collection_name: "my_collection",
properties: {
"dynamicfield.enabled": true
}
});
err = client.AlterCollectionProperties(ctx, milvusclient.NewAlterCollectionPropertiesOption("my_collection").WithProperty(common.EnableDynamicSchemaKey, true))
if err != nil {
fmt.Println(err.Error())
// handle error
}
# restful
curl -X POST "http://localhost:19530/v2/vectordb/collections/alter_properties" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <token>" \
-d '{
"collectionName": "my_collection",
"properties": {
"dynamicfield.enabled": "true"
}
}'
Ejemplo 5: Habilitar allow_insert_auto_id
La propiedad allow_insert_auto_id permite que una colección con AutoID habilitado acepte valores de clave primaria proporcionados por el usuario durante la inserción, upsert e importación masiva. Cuando se establece a "true", Milvus utiliza el valor de clave primaria proporcionado por el usuario si está presente; de lo contrario, lo autogenera. Por defecto es "false".
El siguiente ejemplo muestra cómo habilitar allow_insert_auto_id:
client.alter_collection_properties(
collection_name="my_collection",
properties={"allow_insert_auto_id": "true"}
)
# After enabling, inserts with a PK column will use that PK; otherwise Milvus auto-generates.
Map<String, String> properties = new HashMap<>();
properties.put("allow_insert_auto_id", "True");
AlterCollectionReq alterCollectionReq = AlterCollectionReq.builder()
.collectionName("my_collection")
.properties(properties)
.build();
client.alterCollection(alterCollectionReq);
await client.alterCollectionProperties({
collection_name: "my_collection",
properties: {
"allow_insert_auto_id": true
}
});
err = client.AlterCollectionProperties(ctx, milvusclient.NewAlterCollectionPropertiesOption("my_collection").WithProperty(common.AllowInsertAutoIDKey, true))
if err != nil {
fmt.Println(err.Error())
// handle error
}
# restful
curl -X POST "http://localhost:19530/v2/vectordb/collections/alter_properties" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <token>" \
-d '{
"collectionName": "my_collection",
"properties": {
"allow_insert_auto_id": "true"
}
}'
Ejemplo 6: Establecer la zona horaria de la colección
Puede establecer una zona horaria por defecto para su colección utilizando la propiedad timezone. Esto determina cómo se interpretan y muestran los datos relacionados con la hora para todas las operaciones dentro de la colección, incluyendo la inserción de datos, la consulta y la presentación de resultados.
El valor de timezone debe ser un identificador de zona horaria IANA válido, como Asia/Shanghai, America/Chicago o UTC. Si se utiliza un valor no válido o no estándar, se producirá un error al modificar la propiedad de la colección.
El siguiente ejemplo muestra cómo establecer la zona horaria de la colección en Asia/Shanghai:
client.alter_collection_properties(
collection_name="my_collection",
properties={"timezone": "Asia/Shanghai"}
)
Map<String, String> properties = new HashMap<>();
properties.put("timezone", "Asia/Shanghai");
AlterCollectionReq alterCollectionReq = AlterCollectionReq.builder()
.collectionName("my_collection")
.properties(properties)
.build();
client.alterCollection(alterCollectionReq);
// js
err = client.AlterCollectionProperties(ctx, milvusclient.NewAlterCollectionPropertiesOption("my_collection").WithProperty(common.CollectionDefaultTimezone, true))
if err != nil {
fmt.Println(err.Error())
// handle error
}
# restful
curl -X POST "http://localhost:19530/v2/vectordb/collections/alter_properties" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <token>" \
-d '{
"collectionName": "my_collection",
"properties": {
"timezone": "Asia/Shanghai"
}
}'
Restablecer propiedades de colección
También puede restablecer una propiedad de colección soltándola de la siguiente manera.
client.drop_collection_properties(
collection_name="my_collection",
property_keys=[
"collection.ttl.seconds"
]
)
client.dropCollectionProperties(DropCollectionPropertiesReq.builder()
.collectionName("my_collection")
.propertyKeys(Collections.singletonList("collection.ttl.seconds"))
.build());
client.dropCollectionProperties({
collection_name:"my_collection",
properties: ['collection.ttl.seconds'],
});
err = client.DropCollectionProperties(ctx, milvusclient.NewDropCollectionPropertiesOption("my_collection", common.CollectionTTLConfigKey))
if err != nil {
fmt.Println(err.Error())
// handle error
}
curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/collections/drop_properties" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
-d '{
"collectionName": "my_collection",
"propertyKeys": [
"collection.ttl.seconds"
]
}'