View a markdown version of this page

索引屬性:sparse - Amazon DocumentDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

索引屬性:sparse

支援的索引類型

選項 3.6 4.0 5.0 8.0 彈性叢集
單一欄位
compound
多金鑰

使用稀疏選項略過缺少索引欄位的索引文件,減少索引大小並節省記憶體空間。由於索引大小較小,因此使用它的查詢會更有效率。若要讓查詢使用稀疏索引,您必須在索引欄位上使用 $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 } } ] })

多金鑰

在檢閱陣列上建立稀疏的多金鑰索引:

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

尋找具有檢閱陣列的所有產品時,將會使用此索引:

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