

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 索引属性：稀疏
<a name="index-property-sparse"></a>

## 支持的索引类型
<a name="index-property-sparse-supported"></a>


| Option | 3.6 | 4.0 | 5.0 | 8.0 | 弹性集群 | 
| --- | --- | --- | --- | --- | --- | 
| 单字段 | 支持 | 是 | 是 | 是 | 是 | 
| 复合排序 | 支持 | 是 | 是 | 是 | 是 | 
| 多键 | 支持 | 是 | 是 | 是 | 是 | 

使用 sparse 选项可以跳过对缺少索引字段的文档进行索引，从而减小索引大小并节省内存空间。由于索引大小较小，因此使用它的查询效率更高。要使查询使用稀疏索引，必须在索引字段上使用 $exists 子句。如果您省略 $exists 子句，Amazon DocumentDB 将不会使用稀疏索引。

## 示例
<a name="index-property-sparse-examples"></a>

以下示例说明如何在以下示例文档中创建稀疏索引：

```
{
  "productId": "PROD133726",
  "sku": "SKU24224",
  "name": "Basic Printer",
  "manufacturer": "The Manufacturer",
  "tags": [ "printer", "basic", "electronics", "business" ],
  "barcodes": [ "542364671", "886330670", "437445606" ],
  "reviews": [
    {
      "review_date": ISODate('2024-01-19T21:37:10.585Z'),
      ...
    }
  ],
  "material": "Polycarbonate",
  "color": "Space Gray",
  "supplier": {
    "supplierId": "SUP4",
    "location": {
      "type": "Point",
      "coordinates": [ -71.0589, 42.3601 ]
    }
  },
  "productEmbedding": [
    -0.019320633663838058,
    0.019672111388113596
  ],
  "lastUpdated": ISODate('2025-10-20T21:37:10.585Z')
}
```

请注意，并非所有文档中都存在评论、材料和颜色字段。

单字段

在材质字段上创建一个稀疏的单字段索引：

```
db.collection.createIndex(
  {
    "material": 1
  },
  {
    "name": "material_sparse",
    "sparse": true
  }
)
```

在查找所有具有材料价值的产品时，将使用此索引：

```
db.collection.find({
  "material": {
    $exists: true
  }
})
```

化合物

在材质和颜色字段上创建稀疏复合索引：

```
db.collection.createIndex(
  {
    "material": 1,
    "color": 1
  },
  {
    "name": "material_and_color_sparse",
    "sparse": true
  }
)
```

在查找所有具有材料和颜色值任意组合的产品时，将使用此索引：

```
db.collection.find({
  "material": {
    $exists: true
  }
})

db.collection.find({
  "color": {
    $exists: true
  }
})

db.collection.find({
  $and: [
    {
      "material": {
        $exists: true
      }
    },
    {
      "color": {
        $exists:true
      }
    }
  ]
})

db.collection.find({
  $and: [
    {
      "color": {
        $exists: true
      }
    },
    {
      "material": {
        $exists:true
      }
    }
  ]
})
```

多键

在 reviews 数组上创建一个稀疏的多键索引：

```
db.collection.createIndex(
  {
    "reviews": 1
  },
  {
    "name": "reviews_sparse",
    "sparse": true
  }
)
```

在查找所有具有评论数组的产品时，将使用此索引：

```
db.collection.find({
  "reviews": {
    $exists: true
  }
})
```