简体   繁体   English

如何在Rails中加快find_or_initialize?

[英]How to speed up find_or_initialize in Rails?

in my Rails 3.2.x Application there is a table called Pdata with currently more than 1.5 million records (mysql), and its growing daily. 在我的Rails 3.2.x应用程序中,有一个名为Pdata的表,当前有150万条记录(mysql),并且每天都在增长。 This table is collecting measurement results and is updated continuously. 该表正在收集测量结果并不断更新。 Every new measurement is either a new Pdata record or does update an existing one. 每个新的度量要么是新的Pdata记录,要么是更新现有的记录。 Therefore I do 所以我做

pdata = Pdata.find_or_initialize_by_a_id_and_b_id_and_timestamp(a_id,b_id,timestamp)

where a and b are basically different models where each record belongs to and they are delivered by the measurements data. 其中a和b基本上是每个记录都属于的不同模型,它们由测量数据传递。 There are around 500 measurements per day that needs to be updated or newly created this way. 每天大约有500次测量需要以这种方式进行更新或重新创建。 Now I found out that each find_or_initialize_by call takes around 0.7s! 现在,我发现每个find_or_initialize_by调用大约需要0.7秒! Is anyone aware of a faster way to find or initialize? 有人知道更快的查找或初始化方式吗? Does anyone knows why this call takes so long? 有谁知道为什么这个电话要花这么长时间?

Thanks, Andreas 谢谢,安德烈亚斯

for this case, create an index on the table with the colums you are working for, but have in mind that the order matters, use first the column that will narrows down the number of records fastest. 对于这种情况,请在表上使用您要处理的列创建索引,但要记住顺序很重要,请首先使用该列,该列将以最快的速度缩小记录数。

create the migration an add the index with your fields: 创建迁移并在字段中添加索引:

def change
  add_index :p_datas, [:a_id, :b_id, :timestamp]
end

change the order of the columns having in mind the rule mentioned before. 考虑到前面提到的规则,请更改列的顺序。

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

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