简体   繁体   English

用游标遍历对象后将其保留在内存中

[英]Keeping Mongoid objects in memory after iterating over them with cursor

I'm iterating over objects using the same cursor a few times, so I'm assuming that keeping the objects in memory would be faster. 我使用相同的游标遍历对象几次,因此我假设将对象保留在内存中会更快。

I tried to put all the objects in an array before I used them with objects = cursor.to_a , but the the call blocks any further calculations while it waits for the data to download and is ultimately slower. 在将所有对象与objects = cursor.to_a使用之前,我尝试将所有对象放入数组中,但是该调用在等待数据下载时会阻止任何进一步的计算,最终会变慢。

Another way I thought of is to append the documents in an array as I'm doing the calculations, then use the array to do further calculations. 我想到的另一种方法是在进行计算时将文档追加到数组中,然后使用数组进行进一步的计算。 Though this is pretty unclean and hard to maintain. 虽然这很不干净而且很难维护。

Is there any code out there that already does this? 是否有任何代码已经做到了?

So there's already a method that does this in Mongoid. 因此,已经有一种方法可以在Mongoid中执行此操作。 It caches per-query and per iteration, so it really only keeps the data in memory when you query for it, so it doesn't block. 它缓存每个查询和每个迭代,因此它实际上仅在查询时将数据保留在内存中,因此不会阻塞。

It's just a function on the cursor and you can call it like this: 它只是光标上的一个函数,您可以这样调用它:

Model.where(:name => "John").cache

More info here: http://mongoid.org/docs/extras.html 此处提供更多信息:http://mongoid.org/docs/extras.html

Try to use identity_map , more details you can find in the doc: http://mongoid.org/docs/installation/configuration.html 尝试使用identity_map ,您可以在文档中找到更多详细信息: http : //mongoid.org/docs/installation/configuration.html

identity_map_enabled (false): When set to true Mongoid will store documents loaded from the database in the identity map by their ids, so subsequent dataabase queries for the same document in the same unit of work do not hit the database. identity_map_enabled(false):设置为true时,Mongoid将通过ID将从数据库加载的文档按其ID存储在身份映射中,因此在同一工作单元中对同一文档的后续数据库查询不会访问数据库。 This is only for relation queries at the moment. 目前仅用于关系查询。 See the identity map documentation for more info. 有关更多信息,请参见身份映射文档。

Another alternative: Store only the id part in the array. 另一种选择:仅将id部分存储在数组中。 Mongo::Cursor is not a hash in itself but something similar to a pointer of the result set as far as I can understand. 据我所知, Mongo::Cursor本身不是哈希,而是类似于结果集的指针。 More on that here: Mongo Docs 此处的更多信息: Mongo Docs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM