기본값
Milvus에서는 스칼라 필드(기본 필드 제외)에 대한 기본값을 설정할 수 있습니다. 필드에 기본값이 설정되어 있는 경우, 삽입 중에 데이터가 제공되지 않으면 Milvus는 자동으로 이 값을 적용합니다.
기본값은 기존 기본값 설정을 유지하여 다른 데이터베이스 시스템에서 Milvus로 데이터 마이그레이션을 간소화합니다. 또한 삽입 시 값이 불확실한 필드에 기본값을 사용할 수도 있습니다.
제한 사항
스칼라 필드만 기본값을 지원합니다. 기본 필드와 벡터 필드는 기본값을 가질 수 없습니다.
JSON및ARRAY필드는 기본값을 지원하지 않습니다.기본값은 컬렉션 생성 중에만 구성할 수 있으며 이후에는 수정할 수 없습니다.
기본값 설정하기
컬렉션을 만들 때 add_field() 에서 default_value 매개 변수를 사용하여 필드의 기본값을 정의합니다.
다음 예제에서는 기본값이 age 기본값은 18, status 기본값은 "active" 인 두 개의 스칼라 필드가 있는 컬렉션을 만듭니다.
from pymilvus import MilvusClient, DataType
client = MilvusClient(uri='http://localhost:19530')
# Define collection schema
schema = client.create_schema(
auto_id=False,
enable_dynamic_schema=True,
)
schema.add_field(field_name="id", datatype=DataType.INT64, is_primary=True)
schema.add_field(field_name="vector", datatype=DataType.FLOAT_VECTOR, dim=5)
schema.add_field(field_name="age", datatype=DataType.INT64, default_value=18)
schema.add_field(field_name="status", datatype=DataType.VARCHAR, default_value="active", max_length=10)
# Set index params
index_params = client.prepare_index_params()
index_params.add_index(field_name="vector", index_type="AUTOINDEX", metric_type="L2")
# Create collection
client.create_collection(collection_name="my_collection", schema=schema, index_params=index_params)
// java
// js
// go
# restful
엔티티 삽입
데이터를 삽입할 때 기본값이 있는 필드를 생략하거나 명시적으로 NULL로 설정하면 Milvus는 자동으로 구성된 기본값을 사용합니다.
data = [
# All fields provided explicitly
{"id": 1, "vector": [0.1, 0.2, 0.3, 0.4, 0.5], "age": 30, "status": "premium"},
# age and status omitted → both use default values (18 and "active")
{"id": 2, "vector": [0.2, 0.3, 0.4, 0.5, 0.6]},
# status set to None → uses default value "active"
{"id": 3, "vector": [0.3, 0.4, 0.5, 0.6, 0.7], "age": 25, "status": None},
# age set to None → uses default value 18
{"id": 4, "vector": [0.4, 0.5, 0.6, 0.7, 0.8], "age": None, "status": "inactive"}
]
client.insert(collection_name="my_collection", data=data)
// java
// js
// go
# restful
기본값으로 검색 및 쿼리
기본값을 포함하는 엔티티는 벡터 검색 및 스칼라 필터링 중에 다른 엔티티와 동일하게 작동합니다. search 및 query 작업 모두에서 기본값을 기준으로 필터링할 수 있습니다.
다음 예는 age 이 기본값 18 과 같은 엔티티를 검색하는 예제입니다:
res = client.search(
collection_name="my_collection",
data=[[0.1, 0.2, 0.4, 0.3, 0.5]],
search_params={"params": {"nprobe": 16}},
filter="age == 18",
limit=10,
output_fields=["id", "age", "status"]
)
print("Search results (age == 18):")
for hit in res[0]:
print(f" id: {hit['id']}, age: {hit['entity']['age']}, status: {hit['entity']['status']}")
// java
// js
// go
# restful
Output:
Search results (age == 18):
id: 2, age: 18, status: active
id: 4, age: 18, status: inactive
기본값을 직접 일치시켜 엔티티를 쿼리할 수도 있습니다:
# Query entities where age equals the default value (18)
default_age_results = client.query(
collection_name="my_collection",
filter="age == 18",
output_fields=["id", "age", "status"]
)
print("\nQuery results (age == 18):")
for r in default_age_results:
print(f" id: {r['id']}, age: {r['age']}, status: {r['status']}")
# Query entities where status equals the default value ("active")
default_status_results = client.query(
collection_name="my_collection",
filter='status == "active"',
output_fields=["id", "age", "status"]
)
print("\nQuery results (status == 'active'):")
for r in default_status_results:
print(f" id: {r['id']}, age: {r['age']}, status: {r['status']}")
// java
// js
// go
# restful
Query results (age == 18):
id: 2, age: 18, status: active
id: 4, age: 18, status: inactive
Query results (status == 'active'):
id: 2, age: 18, status: active
id: 3, age: 25, status: active
적용 가능한 규칙
필드에 대해 nullable 및 default_value 을 모두 구성한 경우, 다음 규칙에 따라 Milvus가 삽입 중에 NULL 입력 또는 누락된 필드 값을 처리하는 방식이 결정됩니다.
Null 가능 |
기본값 |
사용자 입력 |
결과 |
|---|---|---|---|
✅ |
✅ (NULL이 아님) |
NULL 또는 생략 |
기본값 사용 |
✅ |
❌ |
NULL 또는 생략 |
NULL로 저장 |
❌ |
✅ (비 NULL) |
NULL 또는 생략 |
기본값 사용 |
❌ |
❌ |
NULL 또는 생략 |
오류를 던집니다. |
❌ |
✅ (NULL) |
NULL 또는 생략 |
오류를 발생시킵니다. |
핵심 사항:
필드에 NULL이 아닌 기본값이 있는 경우
nullable활성화 여부에 관계없이 해당 값이 사용됩니다.nullable=True이지만 기본값이 설정되지 않은 경우 필드에 NULL이 저장됩니다.nullable=False에 기본값이 설정되지 않은 경우 오류와 함께 삽입이 실패합니다.NULL이 아닌 필드에 NULL 기본값을 설정하면 유효하지 않으며 오류가 발생합니다.