JayDee
JayDee

Reputation: 45

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. The first table contains replays which each have 10 unique players (a has many relationship). I want to render a JSON based on my search that contains the replays with their players. However, I am pulling a large number of replays (2000) -- which all have 10 players, meaning searching for 20,000 players.

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? 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.

Upvotes: 0

Views: 52

Answers (1)

Ursus
Ursus

Reputation: 30056

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

Upvotes: 2

Related Questions