Home > Net >  where query causing a timeout in rails
where query causing a timeout in rails

Time:11-16

I have this query in my rails application where I get the name of the Books.

Book.where(:name => @name_list).pluck(:name)

Basically it find the Book whose name is present in the @name_list and then return an array of their names if present. But since there are a huge number of books present in the database, the request is getting timed out when I call this particular endpoint.

Please let me know if there is any way we can make this faster so that endpoint will work. Also will the query speed increase if we add this name column as an index into the Books table ?

add_index :books, :name

CodePudding user response:

I think this is something you're looking for, it's best if you process the data in batches to prevent memory bloat, or process this large amount of data at once.

In Rails 3.2, how to "pluck_in_batches" for a very large table

CodePudding user response:

You asked it an index on books.name will increase the performance of query filtering books by a given list of names.

The answer is yes. This is exactly the textbook use-case for database indexes. The bigger the table is, the bigger the performance benefit will be. For huge tables, it is not unlikely that queries using the index will be a magnitude faster.

I highly suggest adding such an index with the method you already named in your question and try again:

add_index :books, :name
  • Related