官方文档:https://www.mongodb.com/zh-cn/docs/v8.0/core/index-hidden/
从MongoDB5.0开始引入了隐藏索引这个特性
隐藏索引对查询规划器不可见,且不能用于支持查询。
使用场景:
通过向规划器隐藏索引,您可以评估在不实际删除索引的情况下删除索引的潜在影响。如有不利影响,您可以取消隐藏该索引,而不必重新创建删除的索引。
行为
限制
实验
插入测试数据
rs01 [direct: primary] test> db.addresses.insertOne({"borough":"abcd"})
rs01 [direct: primary] test> db.addresses.insertOne({"borough":"defg"})
rs01 [direct: primary] test> db.addresses.find()
[
{ _id: ObjectId('680c6e3818c8de83cf964033'), borough: 'abcd' },
{ _id: ObjectId('680c6e3e18c8de83cf964034'), borough: 'defg' }
]
创建一个隐藏索引
rs01 [direct: primary] test> db.addresses.createIndex(
{ borough: 1 },
{ hidden: true }
);
查看索引清单
rs01 [direct: primary] test> db.addresses.getIndexes()
[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{ v: 2, key: { borough: 1 }, name: 'borough_1', hidden: true }
]
查询测试
rs01 [direct: primary] test> db.addresses.find({"borough":"abcd"}).explain()['queryPlanner']['winningPlan']
{
stage: 'COLLSCAN',
filter: { borough: { '$eq': 'abcd' } },
direction: 'forward'
}
取消索引的hidden属性
rs01 [direct: primary] test> db.addresses.unhideIndex( "borough_1" );
{
hidden_old: true,
hidden_new: false,
ok: 1,
'$clusterTime': {
clusterTime: Timestamp({ t: 1745644936, i: 1 }),
signature: {
hash: Binary.createFromBase64('AAAAAAAAAAAAAAAAAAAAAAAAAAA=', 0),
keyId: Long('0')
}
},
operationTime: Timestamp({ t: 1745644936, i: 1 })
}
查看索引清单
rs01 [direct: primary] test> db.addresses.getIndexes()
[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{ v: 2, key: { borough: 1 }, name: 'borough_1' }
]
再次查询测试
rs01 [direct: primary] test> db.addresses.find({"borough":"abcd"}).explain()['queryPlanner']['winningPlan']
{
stage: 'FETCH',
inputStage: {
stage: 'IXSCAN',
keyPattern: { borough: 1 },
indexName: 'borough_1',
isMultiKey: false,
multiKeyPaths: { borough: [] },
isUnique: false,
isSparse: false,
isPartial: false,
indexVersion: 2,
direction: 'forward',
indexBounds: { borough: [ '["abcd", "abcd"]' ] }
}
}
可以看到执行计划变成了 IXSCAN 可以利用到索引了。
TIPS:
隐藏一个索引,可以使用索引名的写法,也可以使用具体的列的写法:
db.restaurants.hideIndex( { borough: 1, ratings: 1 } ); // Specify the index key specification document 列出相关列的写法
db.restaurants.hideIndex( "borough_1_ratings_1" ); // Specify the index name 指定索引名的写法
对于一个已存在的索引,将它改为hidden属性。
db.addresses.hideIndex( "borough_1" ); 或者 db.addresses.hideIndex( { borough: 1 } );
本文系外文翻译,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系外文翻译,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有