2

在测试了用于批量插入的 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')

我尝试将 set 设置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
)

有谁知道它为什么以这种方式工作?我在文档中找不到任何内容。

4

1 回答 1

1

所以,目前,我发现了一些修改过的第 3 方解决方案 https://gist.github.com/abratashov/155bcd0ea2e02940cc6157e6970e7a2b

它创建批次(默认为 1000 个)并执行一个巨大的BULK INSERT.

Rails 6 也支持批量插入

于 2019-08-19T17:20:14.700 回答