python - Pymongo/MongoDB : create index or ensure

我不明白 pymongo 中 create_indexensure_index 之间的区别。在 MongoDB indexes page ,它说

you can create an index by calling the ensureIndex()

但是在 pymongo 中有两个不同的命令 create_indexensure_index ,创建索引的文档有:

Unlike create_index(), which attempts to create an index unconditionally, ensure_index() takes advantage of some caching within the driver such that it only attempts to create indexes that might not already exist. When an index is created (or ensured) by PyMongo it is “remembered” for ttl seconds. Repeated calls to ensure_index() within that time limit will be lightweight - they will not attempt to actually create the index.

我是否理解 ensure_index 将创建一个永久索引,或者我需要为此使用 create_index 吗?

最佳答案

@andreas-jung 是正确的,因为 ensure_index()create_index() 的包装器,我认为这句话引起了混淆:

When an index is created (or ensured) by PyMongo it is “remembered” for ttl seconds.

不是索引是临时的或“暂时的”,而是在指定的秒数内,调用 ensure_index() 尝试再次创建相同的索引将 not 没有任何效果,并且会在下面not调用 create_index(),但是在“缓存”过期后,调用 ensure_index() code> 在下面再次调用 create_index()

我完全理解您的困惑,因为坦率地说,PyMongo 的文档并不能很好地解释这是如何工作的,但是如果您转到 Ruby docs ,解释清楚一点:

  • (String) ensure_index(spec, opts = {})

Calls create_index and sets a flag to not do so again for another X minutes. this time can be specified as an option when initializing a Mongo::DB object as options[:cache_time] Any changes to an index will be propogated through regardless of cache time (e.g., a change of index direction)

The parameters and options for this methods are the same as those for Collection#create_index.

Examples:

Call sequence:

Time t: @posts.ensure_index([['subject', Mongo::ASCENDING]) -- calls create_index and sets the 5 minute cache

Time t+2min : @posts.ensure_index([['subject', Mongo::ASCENDING]) -- doesn't do anything

Time t+3min : @posts.ensure_index([['something_else', Mongo::ASCENDING]) -- calls create_index and sets 5 minute cache

Time t+10min : @posts.ensure_index([['subject', Mongo::ASCENDING]) -- calls create_index and resets the 5 minute counter

我并不是说驱动程序的工作方式完全相同,只是为了便于说明,恕我直言,他们的解释要好一些。

关于python - Pymongo/MongoDB : create index or ensure index?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5912661/

相关文章:

java - MongoDB中不区分大小写的排序

c# - 支持和反对从 SQL Server 迁移到 MongoDB 的原因

mongodb - 如何发现 mongodb 数据库结构

mongodb - 修改和重放 MongoDB oplog

python - 哪个 Python API 应该与 Mongodb 和 Django 一起使用

mongodb - mongodb insert 命令中是否有 "upsert"选项?

node.js - 如何使用 Node.js 在 MongoDB 中使用 cursor.forEac

mongodb - 对 MongoDB $in 查询的响应顺序?

node.js - Mongoose 填充与对象嵌套

javascript - 在 JavaScript 中将 ObjectID (Mongodb) 转换