JSON 欄位
JSON(JavaScript Object Notation) 是一種輕量級的資料交換格式,可提供靈活的方式來儲存和查詢複雜的資料結構。在 Milvus 中,您可以使用 JSON 欄位將額外的結構化資訊與向量資料一起儲存,以實現結合向量相似性與結構化過濾的進階搜尋與查詢。
JSON 欄位是需要元資料來優化檢索結果的應用程式的理想選擇。例如,在電子商務中,產品向量可以透過類別、價格和品牌等屬性來增強。在推薦系統中,使用者向量可以結合偏好和人口統計資訊。以下是典型 JSON 欄位的範例。
{
"category": "electronics",
"price": 99.99,
"brand": "BrandA"
}
新增 JSON 欄位
要在 Milvus 中使用 JSON 欄位,請在集合模式中定義相關的欄位類型,將datatype
設定為支援的 JSON 類型,即JSON
。
以下是如何定義包含 JSON 欄位的集合模式。
from pymilvus import MilvusClient, DataType
client = MilvusClient(uri="http://localhost:19530")
schema = client.create_schema(
auto_id=False,
enable_dynamic_fields=True,
)
schema.add_field(field_name="metadata", datatype=DataType.JSON)
schema.add_field(field_name="pk", datatype=DataType.INT64, is_primary=True)
schema.add_field(field_name="embedding", datatype=DataType.FLOAT_VECTOR, dim=3)
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;
MilvusClientV2 client = new MilvusClientV2(ConnectConfig.builder()
.uri("http://localhost:19530")
.build());
CreateCollectionReq.CollectionSchema schema = client.createSchema();
schema.setEnableDynamicField(true);
schema.addField(AddFieldReq.builder()
.fieldName("metadata")
.dataType(DataType.JSON)
.build());
schema.addField(AddFieldReq.builder()
.fieldName("pk")
.dataType(DataType.Int64)
.isPrimaryKey(true)
.build());
schema.addField(AddFieldReq.builder()
.fieldName("embedding")
.dataType(DataType.FloatVector)
.dimension(3)
.build());
import { MilvusClient, DataType } from "@zilliz/milvus2-sdk-node";
const schema = [
{
name: "metadata",
data_type: DataType.JSON,
},
{
name: "pk",
data_type: DataType.Int64,
is_primary_key: true,
},
{
name: "embedding",
data_type: DataType.FloatVector,
dim: 3,
},
];
export jsonField='{
"fieldName": "metadata",
"dataType": "JSON"
}'
export pkField='{
"fieldName": "pk",
"dataType": "Int64",
"isPrimary": true
}'
export vectorField='{
"fieldName": "embedding",
"dataType": "FloatVector",
"elementTypeParams": {
"dim": 3
}
}'
export schema="{
\"autoID\": false,
\"fields\": [
$jsonField,
$pkField,
$vectorField
]
}"
在這個範例中,我們新增一個名為metadata
的 JSON 欄位,以儲存與向量資料相關的附加元資料,例如產品類別、價格和品牌資訊。
當您建立一個集合時,主欄位和向量欄位是必須的。Primary 欄位可唯一識別每個實體,而向量欄位對相似性搜尋至關重要。如需詳細資訊,請參閱Primary Field & AutoID、Dense Vector、Binary Vector 或Sparse Vector。
建立集合
建立集合時,您必須為向量欄位建立索引,以確保擷取效能。在本範例中,我們使用AUTOINDEX
來簡化索引設定。如需詳細資訊,請參閱AUTOINDEX。
index_params = client.prepare_index_params()
index_params.add_index(
field_name="embedding",
index_type="AUTOINDEX",
metric_type="COSINE"
)
import io.milvus.v2.common.IndexParam;
import java.util.*;
List<IndexParam> indexes = new ArrayList<>();
indexes.add(IndexParam.builder()
.fieldName("embedding")
.indexType(IndexParam.IndexType.AUTOINDEX)
.metricType(IndexParam.MetricType.COSINE)
.build());
const indexParams = {
index_name: 'embedding_index',
field_name: 'embedding',
metricType: MetricType.CONSINE,
index_type: IndexType.AUTOINDEX,
);
export indexParams='[
{
"fieldName": "embedding",
"metricType": "COSINE",
"indexType": "AUTOINDEX"
}
]'
使用已定義的模式和索引參數建立集合。
client.create_collection(
collection_name="my_json_collection",
schema=schema,
index_params=index_params
)
CreateCollectionReq requestCreate = CreateCollectionReq.builder()
.collectionName("my_json_collection")
.collectionSchema(schema)
.indexParams(indexes)
.build();
client.createCollection(requestCreate);
client.create_collection({
collection_name: "my_json_collection",
schema: schema,
index_params: indexParams
})
curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/collections/create" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
-d "{
\"collectionName\": \"my_json_collection\",
\"schema\": $schema,
\"indexParams\": $indexParams
}"
插入資料
建立資料集後,您可以插入包含 JSON 欄位的資料。
# Data to be inserted
data = [
{
"metadata": {"category": "electronics", "price": 99.99, "brand": "BrandA"},
"pk": 1,
"embedding": [0.12, 0.34, 0.56]
},
{
"metadata": {"category": "home_appliances", "price": 249.99, "brand": "BrandB"},
"pk": 2,
"embedding": [0.56, 0.78, 0.90]
},
{
"metadata": {"category": "furniture", "price": 399.99, "brand": "BrandC"},
"pk": 3,
"embedding": [0.91, 0.18, 0.23]
}
]
# Insert data into the collection
client.insert(
collection_name="your_collection_name",
data=data
)
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import io.milvus.v2.service.vector.request.InsertReq;
import io.milvus.v2.service.vector.response.InsertResp;
List<JsonObject> rows = new ArrayList<>();
Gson gson = new Gson();
rows.add(gson.fromJson("{\"metadata\": {\"category\": \"electronics\", \"price\": 99.99, \"brand\": \"BrandA\"}, \"pk\": 1, \"embedding\": [0.1, 0.2, 0.3]}", JsonObject.class));
rows.add(gson.fromJson("{\"metadata\": {\"category\": \"home_appliances\", \"price\": 249.99, \"brand\": \"BrandB\"}, \"pk\": 2, \"embedding\": [0.4, 0.5, 0.6]}", JsonObject.class));
rows.add(gson.fromJson("{\"metadata\": {\"category\": \"furniture\", \"price\": 399.99, \"brand\": \"BrandC\"}, \"pk\": 3, \"embedding\": [0.7, 0.8, 0.9]}", JsonObject.class));
InsertResp insertR = client.insert(InsertReq.builder()
.collectionName("my_json_collection")
.data(rows)
.build());
const data = [
{
"metadata": {"category": "electronics", "price": 99.99, "brand": "BrandA"},
"pk": 1,
"embedding": [0.12, 0.34, 0.56]
},
{
"metadata": {"category": "home_appliances", "price": 249.99, "brand": "BrandB"},
"pk": 2,
"embedding": [0.56, 0.78, 0.90]
},
{
"metadata": {"category": "furniture", "price": 399.99, "brand": "BrandC"},
"pk": 3,
"embedding": [0.91, 0.18, 0.23]
}
]
client.insert({
collection_name: "my_json_collection",
data: data
});
curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/entities/insert" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
-d '{
"data": [
{
"metadata": {"category": "electronics", "price": 99.99, "brand": "BrandA"},
"pk": 1,
"embedding": [0.12, 0.34, 0.56]
},
{
"metadata": {"category": "home_appliances", "price": 249.99, "brand": "BrandB"},
"pk": 2,
"embedding": [0.56, 0.78, 0.90]
},
{
"metadata": {"category": "furniture", "price": 399.99, "brand": "BrandC"},
"pk": 3,
"embedding": [0.91, 0.18, 0.23]
}
],
"collectionName": "my_json_collection"
}'
在這個範例中。
每個資料項目包含一個主要欄位 (
pk
),metadata
為 JSON 欄位,用來儲存產品類別、價格和品牌等資訊。embedding
是三維向量欄位,用於向量相似性搜尋。
搜尋與查詢
JSON 欄位允許在搜尋過程中進行標量篩選,增強了 Milvus 的向量搜尋功能。您可以根據 JSON 屬性與向量相似性進行查詢。
篩選查詢
您可以根據 JSON 屬性篩選資料,例如匹配特定值或檢查數字是否在特定範圍內。
filter = 'metadata["category"] == "electronics" and metadata["price"] < 150'
res = client.query(
collection_name="my_json_collection",
filter=filter,
output_fields=["metadata"]
)
print(res)
# Output
# data: ["{'metadata': {'category': 'electronics', 'price': 99.99, 'brand': 'BrandA'}, 'pk': 1}"]
import io.milvus.v2.service.vector.request.QueryReq;
import io.milvus.v2.service.vector.response.QueryResp;
String filter = "metadata[\"category\"] == \"electronics\" and metadata[\"price\"] < 150";
QueryResp resp = client.query(QueryReq.builder()
.collectionName("my_json_collection")
.filter(filter)
.outputFields(Collections.singletonList("metadata"))
.build());
System.out.println(resp.getQueryResults());
// Output
//
// [QueryResp.QueryResult(entity={metadata={"category":"electronics","price":99.99,"brand":"BrandA"}, pk=1})]
client.query({
collection_name: 'my_scalar_collection',
filter: 'metadata["category"] == "electronics" and metadata["price"] < 150',
output_fields: ['metadata']
});
curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/entities/query" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
-d '{
"collectionName": "my_json_collection",
"filter": "metadata[\"category\"] == \"electronics\" and metadata[\"price\"] < 150",
"outputFields": ["metadata"]
}'
{"code":0,"cost":0,"data":[{"metadata":"{\"category\": \"electronics\", \"price\": 99.99, \"brand\": \"BrandA\"}","pk":1}]}
在上述查詢中,Milvus 篩選出metadata
欄位的類別為"electronics"
且價格低於 150 的實體,並傳回符合這些條件的實體。
向量搜尋與 JSON 過濾
透過結合向量相似性與 JSON 過濾功能,您可以確保擷取的資料不僅在語意上相符,同時也符合特定的業務條件,讓搜尋結果更精確、更符合使用者需求。
filter = 'metadata["brand"] == "BrandA"'
res = client.search(
collection_name="my_json_collection",
data=[[0.3, -0.6, 0.1]],
limit=5,
search_params={"params": {"nprobe": 10}},
output_fields=["metadata"],
filter=filter
)
print(res)
# Output
# data: ["[{'id': 1, 'distance': -0.2479381263256073, 'entity': {'metadata': {'category': 'electronics', 'price': 99.99, 'brand': 'BrandA'}}}]"]
import io.milvus.v2.service.vector.request.SearchReq;
import io.milvus.v2.service.vector.response.SearchResp;
String filter = "metadata[\"brand\"] == \"BrandA\"";
SearchResp resp = client.search(SearchReq.builder()
.collectionName("my_json_collection")
.annsField("embedding")
.data(Collections.singletonList(new FloatVec(new float[]{0.3f, -0.6f, 0.1f})))
.topK(5)
.outputFields(Collections.singletonList("metadata"))
.filter(filter)
.build());
System.out.println(resp.getSearchResults());
// Output
//
// [[SearchResp.SearchResult(entity={metadata={"category":"electronics","price":99.99,"brand":"BrandA"}}, score=-0.2364331, id=1)]]
client.search({
collection_name: 'my_json_collection',
data: [0.3, -0.6, 0.1],
limit: 5,
output_fields: ['metadata'],
filter: 'metadata["category"] == "electronics" and metadata["price"] < 150',
});
curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/entities/search" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
-d '{
"collectionName": "my_json_collection",
"data": [
[0.3, -0.6, 0.1]
],
"annsField": "embedding",
"limit": 5,
"searchParams":{
"params":{"nprobe":10}
},
"outputFields": ["metadata"],
"filter": "metadata[\"brand\"] == \"BrandA\""
}'
## {"code":0,"cost":0,"data":[{"distance":-0.24793813,"id":1,"metadata":"{\"category\": \"electronics\", \"price\": 99.99, \"brand\": \"BrandA\"}"}]}
在這個範例中,Milvus 返回與查詢向量最相似的前 5 個實體,其中metadata
欄位包含一個品牌"BrandA"
。
此外,Milvus 支援進階的 JSON 過濾運算元,例如JSON_CONTAINS
,JSON_CONTAINS_ALL
, 和JSON_CONTAINS_ANY
,可以進一步增強查詢能力。如需詳細資訊,請參閱元資料過濾。
限制
索引限制:由於資料結構的複雜性,不支援 JSON 欄位的索引。
資料類型比對:如果 JSON 欄位的關鍵值是整數或浮點,則只能與其他整數或浮點關鍵值或
INT32/64
或FLOAT32/64
欄位進行比對。如果關鍵值是字串 (VARCHAR
),則只能與另一個字串關鍵值比較。命名限制:命名 JSON 鍵時,建議只使用字母、數字字元和底線,因為其他字元可能會在過濾或搜尋時造成問題。
處理字串值:對於字串值 (
VARCHAR
),Milvus 會以原樣儲存 JSON 字段字串,而不進行語意轉換。例如'a"b'
,"a'b"
,'a\\'b'
, 和"a\\"b"
會以輸入的方式儲存;但是,'a'b'
和"a"b"
會被視為無效。處理巢狀字典:JSON 欄位值內的任何巢狀字典都會視為字串。
JSON 欄位大小限制:JSON 欄位限制為 65,536 位元組。