omatech/laravel-bulkimporter

以简单的方式大量导入数据库表中的记录。

v1.0.2 2022-06-23 06:44 UTC

This package is auto-updated.

Last update: 2024-09-23 12:05:11 UTC


README

以非常简单的方式在表中批量插入记录,您可以通过可选参数控制批量大小。

安装

composer require omatech/laravel-bulkimporter

使用方法

初始化 BulkImporter

$bulkImporter=new BulkImporter(<TABLE_NAME>);

批量导入所有记录

$bulkImporter->import($rows);

可选地传递批量大小(默认:每批1000条记录)

$bulkImporter->import($rows, 500);

$rows应该是一个数组,键是数据库字段的名称,值可以是以下之一

  • 字符串
  • 日期(MySQL格式)
  • 数字
  • "now()" --> 自动插入当前日期。

例如

[
  0=>[
    'key'=>'1111111-33333-1111',
    'one-number'=>1111111,
    'name'=>'Name 1',
    'date1'=>'2021-10-29 01:03:20',
    'created_at'=>'now()'
  ],
  1=>[
    'key'=>'222222-5555-3333',
    'one-number'=>2222222
    'name'=>'Name 2',
    'date1'=>'2021-08-03 09:03:20',
    'created_at'=>'now()'
  ]
  ...
]

可选地,您可以使用 delete 方法从表中删除所有记录

$bulkImporter->delete();

为了便于测试,还包含了一个 count 方法

$num=$bulkImporter->count();

使用以下命令运行测试

php vendor/bin/phpunit

性能

MySQL中的批量导入是您可以做出的最重要的性能改进之一。

您可以看到性能测试的输出,包含10万条记录,并比较不同批量大小下的性能

limit=100000 size=1 batchsExecuted=100000 expected=100000 seconds=3995.7 minutes=66.6
limit=100000 size=5 batchsExecuted=20000 expected=20000 seconds=890.88 minutes=14.85
limit=100000 size=25 batchsExecuted=4000 expected=4000 seconds=206.85 minutes=3.45
limit=100000 size=125 batchsExecuted=800 expected=800 seconds=57.15 minutes=0.95
limit=100000 size=625 batchsExecuted=160 expected=160 seconds=20.96 minutes=0.35
limit=100000 size=3125 batchsExecuted=32 expected=32 seconds=10.52 minutes=0.18
limit=100000 size=15625 batchsExecuted=7 expected=7 seconds=6.88 minutes=0.11
limit=100000 size=78125 batchsExecuted=2 expected=2 seconds=6.13 minutes=0.1
limit=100000 size=100000 batchsExecuted=1 expected=1 seconds=8.6 minutes=0.14
Compare 3995.7 to 8.6, OMFG! it's 464.62 times faster

在您的 Laravel 应用程序中的示例命令

假设您已经设置了一个包含标准用户表的数据库,您可以批量加载用户数组。

当然,只有当记录数达到数千条时才有意义,但您已经明白了。

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Omatech\BulkImporter\BulkImporter;
use Illuminate\Support\Facades\Hash;

class BulkImportCommand extends Command
{
    protected $signature = 'example:bulkimport';
    protected $description = 'Test bulkimport';
    public function __construct()
    {
        parent::__construct();
    }
    public function handle()
    {
        $bulkImporter=new BulkImporter('users');
        $data=[
            ['name'=>'Agus', 'email'=>'agus@testemail.com', 'password'=>Hash::make('aguspassword'), 'created_at'=>'now()'],
            ['name'=>'Cesc', 'email'=>'cesc@testemail.com', 'password'=>Hash::make('cescpassword'), 'created_at'=>'now()'],
            ['name'=>'Javi', 'email'=>'javi@testemail.com', 'password'=>Hash::make('javipassword'), 'created_at'=>'now()'],
            ['name'=>'Christian', 'email'=>'christian@testemail.com', 'password'=>Hash::make('christianword'), 'created_at'=>'now()']
        ];
        $bulkImporter->import($data);
        return Command::SUCCESS;
    }
}