Elasticsearch 8 中 Nested 数据类型的使用方法

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值