View a markdown version of this page

索引属性:稀疏 - Amazon DocumentDB

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

索引属性:稀疏

支持的索引类型

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

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

示例

以下示例显示如何在以下示例文档上创建稀疏索引:

{ "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 } })