Nested 数据类型的使用方法,包括完整的示例和最佳实践
1. Nested 数据类型简介
在 Elasticsearch 8 中,nested 类型用于处理对象数组,确保数组中的每个对象都能被独立索引和查询,解决了对象数组扁平化的问题。
为什么需要 Nested?
-
普通对象数组会被扁平化,失去对象内部字段的关联性
-
Nested 保持数组中每个对象的独立性
-
支持对嵌套对象进行精确查询和聚合
2. 创建包含 Nested 字段的索引
基本映射定义:
json
PUT /ecommerce_products
{
"mappings": {
"properties": {
"name": {
"type": "text"
},
"description": {
"type": "text"
},
"price": {
"type": "float"
},
"variants": {
"type": "nested", // 定义 nested 类型
"properties": {
"color": {
"type": "keyword"
},
"size": {
"type": "keyword"
},
"stock": {
"type": "integer"
},
"price": {
"type": "float"
}
}
},
"reviews": {
"type": "nested", // 另一个 nested 字段示例
"properties": {
"user": {
"type": "keyword"
},
"rating": {
"type": "integer"
},
"comment": {
"type": "text"
},
"created_at": {
"type": "date"
}
}
}
}
}
}
3. 插入包含 Nested 数据的文档
json
POST /ecommerce_products/_doc/1
{
"name": "Premium T-Shirt",
"description": "High quality cotton t-shirt",
"price": 29.99,
"variants": [
{
"color": "red",
"size": "M",
"stock": 50,
"price": 29.99
},
{
"color": "blue",
"size": "L",
"stock": 25,
"price": 29.99
},
{
"color": "red",
"size": "S",
"stock": 0,
"price": 29.99
}
],
"reviews": [
{
"user": "user123",
"rating": 5,
"comment": "Excellent quality!",
"created_at": "2023-10-01T10:00:00Z"
},
{
"user": "user456",
"rating": 4,
"comment": "Goo

最低0.47元/天 解锁文章
9112

被折叠的 条评论
为什么被折叠?



