修改外部Collection SchemaCompatible with Milvus 3.0.x
在创建外部Collection后,外部数据源通常会发生变化。例如,一个已经存储了Embeddings的湖屋表,后来可能会包含一个新的标量字段(如得分、类别或时间戳),而您希望在查询结果中返回该字段,或在过滤器中使用它。
与其重新创建外部 Collection 或将源数据复制到 Milvus 中,不如添加一个 Milvus 字段,将其映射到外部数据源中的现有字段。添加字段后,请刷新外部 Collection,以便在查询和搜索中使用该新字段。
限制
外部 Collections 目前支持在创建后添加字段。其他 Schema 更改(例如删除字段、重命名字段、更改字段数据类型、更改向量维度或重新映射
external_field)均不支持。您只能添加在外部数据源中已存在的字段。此操作将现有的外部字段映射到 Milvus 字段,不会在外部数据源中创建新字段,也不会回填源数据。
不支持向现有外部 Collection 添加
SPARSE_FLOAT_VECTOR字段。不支持将 StructArray 字段添加到现有外部集合中。如果您的外部集合需要 StructArray 字段,请在创建 Collection 时在 Schema 中进行定义。
添加字段
在将字段添加到外部Collection之前,请确认该字段已在外部数据源中存在。然后调用add_collection_field() ,通过将external_field 设置为外部数据源中的字段名称,在Milvus中暴露该字段。将data_type 设置为与外部数据源中该字段匹配的Milvus数据类型。例如,如果映射的字段存储双精度值,请使用DataType.DOUBLE 。
与管理 Collections 不同,在刷新外部 Collection 后,新增字段的值将从外部数据源中读取。
添加标量字段
若要在查询结果中返回该字段或在过滤器中使用该字段,请使用 `add_collection_field() ` 添加标量字段。以下示例添加了一个名为 `score ` 的字段,该字段映射到外部数据源中的 `score ` 字段。
from pymilvus import DataType, MilvusClient
client = MilvusClient(
uri="http://localhost:19530",
token="root:Milvus",
)
client.add_collection_field(
collection_name="product_embeddings",
field_name="score",
data_type=DataType.DOUBLE,
nullable=True,
external_field="score",
)
在此示例中,score 是 Milvus 字段名,external_field="score" 将其映射到外部数据源中的score 字段。由于该字段是在 Collection 创建之后添加的,因此需设置nullable=True 。
添加向量字段
如果外部数据源中已包含向量值,您也可以添加向量字段。将向量data_type 和dim 设置为与外部数据源中的向量字段相对应。
以下示例添加了一个名为image_embedding_v2 的密集向量字段。
from pymilvus import DataType, MilvusClient
client = MilvusClient(
uri="http://localhost:19530",
token="root:Milvus",
)
client.add_collection_field(
collection_name="product_embeddings",
field_name="image_embedding_v2",
data_type=DataType.FLOAT_VECTOR,
dim=768,
nullable=True,
external_field="image_embedding_v2",
)
如果您计划对添加的向量字段执行向量搜索,请在刷新外部Collection之前为该字段创建索引。
index_params = client.prepare_index_params()
index_params.add_index(
field_name="image_embedding_v2",
index_type="AUTOINDEX",
metric_type="COSINE",
)
client.create_index(
collection_name="product_embeddings",
index_params=index_params,
)
刷新外部Collection
修改外部 Collection Schema 后,请刷新外部 Collection,以便 Milvus 更新外部 Collection 元数据,并使 Schema 变更在查询、搜索和过滤结果中生效。
client.refresh_external_collection(
collection_name="product_embeddings"
)