简体   繁体   English

Ruby on Rails Postgres /活动记录搜索优化

[英]Ruby on Rails Postgres/Active Record Search Optimization

So it's possible that there may not be a way to fix this but I thought I would ask: 因此,可能没有办法解决此问题,但我想我会问:

I have a Postgresql DB set up. 我有一个Postgresql数据库设置。 The first table contains replays which each have 10 unique players (a has many relationship). 第一个表包含重播,每个重播都有10个唯一的播放器(一个有很多关系)。 I want to render a JSON based on my search that contains the replays with their players. 我想基于我的搜索呈现一个JSON,其中包含其播放器的重放。 However, I am pulling a large number of replays (2000) -- which all have 10 players, meaning searching for 20,000 players. 但是,我要进行大量的重播(2000)-全部都有10位玩家,这意味着要搜索20,000位玩家。

This what the index search currently looks like: 索引搜索当前如下所示:

def index
  @replays = Replay.where(map_id: params['map_id'].to_i)
  @replays = @replays.reverse
  render json: @replays[0..2000].to_json(include: [:players])
end

The search takes this long: 搜索需要这么长时间:

Completed 200 OK in 639596ms (Views: 42.1ms | ActiveRecord: 329252.3ms)

Is there a better way I can search and render the JSON that won't take this long? 有没有更好的方法可以搜索和呈现不会花费这么长时间的JSON? It's worth noting that just searching for 2k replays, 20k players, or even a single specific replay with players takes only a couple seconds (the first search itself also takes only a couple of seconds) so I assume it's a volume issue. 值得注意的是,仅搜索2k重放,20k播放器,甚至与播放器进行单个特定重放都只需要几秒钟(第一次搜索本身也只需要几秒钟),因此我认为这是一个音量问题。

Try to eager load your replays 尝试渴望加载您的重放

replays = Replay.last_two_thousands_by_map_id(params[:map_id])

render json: replays.to_json(include: [:players])

# replay.rb model
def self.last_two_thousands_by_map_id(map_id)
  includes(:players).where(map_id: map_id).order(id: :desc).limit(2000)
end

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

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