为什么“ activerecord-import”不执行批量插入?

时间:2019-08-16 20:16:55

标签: ruby-on-rails activerecord bulkinsert activerecord-import

在测试activerecord-import库的批量插入之后,我发现它执行的不是一个庞大的INSERT,而是很多小的INSERTs

Xml.import(
  insert_values,
  ignore: true,
  validate: false,
  batch_size: 1000
)

# => 

INSERT INTO `xmls` (`path`,`import_id`,`status`,`last_modified`,`created_at`,`updated_at`) VALUES ('test-folder/0_0.xml',114,10,'2019-08-16 20:02:20','2019-08-16 20:02:20','2019-08-16 20:02:20')
INSERT INTO `xmls` (`path`,`import_id`,`status`,`last_modified`,`created_at`,`updated_at`) VALUES ('test-folder/0_1.xml',114,10,'2019-08-16 20:02:20','2019-08-16 20:02:20','2019-08-16 20:02:20')
#...
INSERT INTO `xmls` (`path`,`import_id`,`status`,`last_modified`,`created_at`,`updated_at`) VALUES ('test-folder/0_2.xml',114,10,'2019-08-16 20:02:20','2019-08-16 20:02:20','2019-08-16 20:02:20')

我尝试将insert_values设置为XML.new的数组,也将其设置为纯数组:

cols = [:path, :import_id, :status, :last_modified]

insert_values = [
    [ 0] [
        [0] "test-folder/0_0.xml",
        [1] 115,
        [2] 10,
        [3] Sat, 17 Aug 2019 05:37:02 EDT -04:00
    ],
    [ 1] [
        [0] "test-folder/0_1.xml",
        [1] 115,
        [2] 10,
        [3] Sat, 17 Aug 2019 05:37:02 EDT -04:00
    ],
#...
]

Xml.import(
  cols,
  insert_values,
  ignore: true,
  validate: false,
  batch_size: 1000
)

有人知道它为什么如此工作吗?我在文档中找不到任何内容。

1 个答案:

答案 0 :(得分:1)

因此,目前,我发现了经过修改的第三方解决方案https://gist.github.com/abratashov/155bcd0ea2e02940cc6157e6970e7a2b

它创建批次(默认情况下为1000)并执行巨大的BULK INSERT

Also Rails 6 supports bulk insert