2015-12-04 46 views
0

希望获得注册在特定帐户&其各自Outlet的用户。优化rails IN查询数百万个阵列IDS

用户&插座模型没有任何关联。

出口has_and_belongs_to_many占&反之亦然

用户包含字段outlet_code这是在出口表

@account = Account.find(2546)

@outlet_ids = @ account.outlets唯一的。 map(&:id)#-----它返回这样的数组[1,2,3 .... 1032457]这是动态的

我已经使用了这个查询效率不高=> @users =我们er.where(:outlet_code => @outlet_ids)

+0

你能请描述一下你会为了达到目的,为什么你有一百万个IDS? – Shadow

+1

这个id如何计算?你可以把这里放在这里详细信息 –

+0

@outlet_ids = @ account.outlets.map(&:id)#-------它返回该帐户的所有outlet id,其数量超过10个lac记录 – User5586231

回答

2

我认为你需要的是批量延迟加载和处理。

最有效的,你可以在你的案件得到(假定,那么你以任何方式处理的集合)是使用find_each

@users = User.where(id: [1,2,3....450000]).find_each.lazy 

会回到你懒枚举的实例:

#<Enumerator::Lazy: ...> 

现在,您可以使用它并重复 - @users将按需(懒惰地)从数据库加载。

0

使用find_each与批量大小: -

@users = User.where(:id => [1,2,3....450000]).find_each(batch_size: 50 or no. of records you want to get in batch) 

我将返回的记录,如: -

#<Enumerator: #<ActiveRecord::Relation [...]> 

find_each与块: -

@users = User.where(:id => [1,2,3....450000]).find_each(batch_size: 50) do |user| 
    # your code here 
end 
# User Load (0.7ms) SELECT "users".* FROM "users" 
# ORDER BY "users"."id" ASC LIMIT 50 
# User Load (0.6ms) SELECT "users".* FROM "users" 
# WHERE ("users"."id" > 50) ORDER BY "users"."id" ASC LIMIT 50 
# USer Load (0.3ms) SELECT "users".* FROM "users" 
# WHERE ("users"."id" > 100) ORDER BY "users"."id" ASC LIMIT 50  
+0

究竟如何这个答案与已有的答案相比是新的? –

+0

谢谢,但使用batch_size&find_each使用ajax调用的概念,响应会超时,因为它需要很长时间才能返回结果。 – User5586231

+0

另外,我得到这个错误使用批处理2015/12/05 07:29:05 [错误]上游过早关闭连接时,从上游,客户端读取响应头。我使用了这个NGINX&MySql。 – User5586231