【问题标题】:How to refresh a large database?如何刷新大型数据库?
【发布时间】:2018-12-26 11:05:07
【问题描述】:

我构建了一个 rake 任务以从 Awin 数据馈送中下载一个 zip,并通过 activerecord-import 将其导入我的产品模型。

require 'zip'
require 'httparty'
require 'active_record'
require 'activerecord-import'

namespace :affiliate_datafeed do
    desc "Import products data from Awin"
    task import_product_awin: :environment do
        url = "https://productdata.awin.com"
        dir = "db/affiliate_datafeed/awin.zip"

        File.open(dir, "wb") do |f| 
            f.write HTTParty.get(url).body
        end

        zip_file = Zip::File.open(dir)
        entry = zip_file.glob('*.csv').first
        csv_text = entry.get_input_stream.read
        products = []

        CSV.parse(csv_text, :headers=>true).each do |row|
            products << Product.new(row.to_h)
        end
        Product.import(products)
  end
end

仅当产品不存在或 last_updated 字段中有新日期时如何更新产品数据库?刷新大型数据库的最佳方法是什么?

【问题讨论】:

  • 你不能使用on_duplicate_key 方法之一吗? github.com/zdennis/activerecord-import#duplicate-key-update
  • 刷新大数据库是什么意思?模型还是模型和数据?您是否研究过reload 方法?我猜你会继续使用相同的数据源来更新数据,在这种情况下你也可以dropcreatemigrateseed 每次或.reload 也应该工作。
  • 这意味着当 Awin 刷新来自的 url 时,它会刷新我的数据库删除/更新/添加而不与未更改的交互。能否详细介绍一下reload方法?

标签: ruby database activerecord-import


【解决方案1】:

可能使用以下方法来不断检查 rake 任务中的 last_updated 或 last_modified 标头字段。

def get_date
  date = CSV.foreach('CSV_raw.csv', :headers => false).first { |r| puts r}
  $last_modified = Date.parse(date.compact[1]) # if last_updated is first row of CSV or use your http req header
end

run_once = ARGV.length > 0 # to run once & test if it works; not sure if rake taks accept args.
if not run_once
  puts "Daemon Mode"
end

if not File.read('last_update.txt').empty?
  date_in_file = Date.parse(File.read('last_update.txt'))
else
  date_in_file = Date.parse('2001-02-03')
end
if $last_modified > date_in_file
  "your db updating method"
end
unless run_once
  sleep UPDATE_INTERVAL # whatever value you want for the interval to be
end
end until run_once

【讨论】:

    猜你喜欢
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多