隐藏索引
隐藏索引对查询规划器不可见,并且不能用于支持查询。查询规划器
通过从规划器中隐藏索引,您可以评估删除索引可能产生的潜在影响,而无需实际删除索引。如果影响是负面的,您可以选择取消隐藏索引,而不是重新创建已删除的索引。
行为
除了在规划器中隐藏之外,隐藏的索引表现得像未隐藏的索引。例如
如果隐藏的索引是 唯一索引,则索引仍然对其文档应用唯一约束。
如果隐藏的索引是 TTL索引,则索引仍然使文档过期。
隐藏的索引包含在
listIndexes
和db.collection.getIndexes()
的结果中。隐藏的索引在集合的写操作上更新,并继续消耗磁盘空间和内存。因此,它们包含在各种统计操作中,例如
db.collection.stats()
和$indexStats
。隐藏一个未隐藏的索引或取消隐藏一个隐藏的索引会重置其
$indexStats
。隐藏一个已隐藏的索引或取消隐藏一个已取消隐藏的索引不会重置$indexStats
。
限制
要隐藏索引,必须将 featureCompatibilityVersion 设置为
5.0
或更高。不能隐藏
_id
索引。您不能使用
cursor.hint()
对隐藏的索引进行操作。
示例
创建隐藏索引
要创建一个 隐藏
索引,请使用 db.collection.createIndex()
方法,并将 hidden 选项设置为 true
。
注意
要使用 db.collection.createIndex()
中的 hidden
选项,您必须将 featureCompatibilityVersion 设置为 5.0
或更高版本。
例如,以下操作在 borough
字段上创建一个隐藏的升序索引
db.addresses.createIndex( { borough: 1 }, { hidden: true } );
要验证,请在 addresses
集合上运行 db.collection.getIndexes()
db.addresses.getIndexes()
操作返回以下信息
[ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_" }, { "v" : 2, "key" : { "borough" : 1 }, "name" : "borough_1", "hidden" : true } ]
只有当值为 true
时,才会返回索引选项 hidden
。
隐藏现有索引
注意
要隐藏索引,必须将 featureCompatibilityVersion 设置为
5.0
或更高。不能隐藏
_id
索引。
要隐藏现有的索引,您可以使用 collMod
命令或mongosh
辅助工具 db.collection.hideIndex()
。
例如,创建一个不隐藏的索引
db.restaurants.createIndex( { borough: 1, ratings: 1 } );
要隐藏索引,您可以指定以下内容
将索引键规范文档传递给
db.collection.hideIndex()
方法db.restaurants.hideIndex( { borough: 1, ratings: 1 } ); // Specify the index key specification document 将索引名称传递给
db.collection.hideIndex()
方法db.restaurants.hideIndex( "borough_1_ratings_1" ); // Specify the index name
要验证,请在 restaurants
集合上运行 db.collection.getIndexes()
db.restaurants.getIndexes()
操作返回以下信息
[ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_" }, { "v" : 2, "key" : { "borough" : 1, "ratings" : 1 }, "name" : "borough_1_ratings_1", "hidden" : true } ]
只有当值为 true
时,才会返回索引选项 hidden
。
取消隐藏现有索引
要取消隐藏隐藏的索引,您可以使用 collMod
命令或 mongosh
辅助工具 db.collection.unhideIndex()
。您可以指定以下内容
将索引键规范文档传递给
db.collection.unhideIndex()
方法db.restaurants.unhideIndex( { borough: 1, city: 1 } ); // Specify the index key specification document 将索引名称传递给
db.collection.unhideIndex()
方法db.restaurants.unhideIndex( "borough_1_ratings_1" ); // Specify the index name
要验证,请在 restaurants
集合上运行 db.collection.getIndexes()
db.restaurants.getIndexes()
操作返回以下信息
[ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_" }, { "v" : 2, "key" : { "borough" : 1, "ratings" : 1 }, "name" : "borough_1_ratings_1" } ]
索引选项 hidden
不再作为 borough_1_ratings_1
索引的一部分出现,因为只有当值为 true
时才返回该字段。
由于隐藏的索引会完全维护,取消隐藏后索引立即可供使用。