简体   繁体   中英

deleting millions of records in rails

Our RoR 4 app has millions of records which needs to be deleted on a regular basis. Currently the deletion happens as a backgound job:

 while fruit.apples.count > 0
      # create the sql query to delete 1000 feeds from the channel
      sql = "DELETE FROM apples WHERE fruit_id=#{fruit_id} LIMIT 1000"
      # execute the sql query
      ActiveRecord::Base.connection.execute(sql)
      # wait a bit before the next delete
      sleep 0.1
 end

because I am doing a count every few seconds, it has spiked the mysql server's cpu time. So was wondering if I could delete a million records using delete_all/destroy_all or are there any better way of achieving this.

You can use TRUNCATE instead of DELETE. TRUNCATE deletes the whole table and recreates an empty table. So this is much faster. TRUNCATE also resets the value of AUTO INCREMENT field in the table

TRUNCATE TABLE yourTable;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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