データを一括ロード(CSV / ファイルから)
Oracle
-- SQL*Loader (from the shell)
sqlldr app_user/password control=customer.ctl log=load.log
-- Contents of customer.ctl:
-- LOAD DATA INFILE 'customer.csv'
-- INTO TABLE customer FIELDS TERMINATED BY ','
-- (id, name, email)
-- Alternative: with an external table
CREATE TABLE ext_customer (id NUMBER, name VARCHAR2(100))
ORGANIZATION EXTERNAL (TYPE ORACLE_LOADER DEFAULT DIRECTORY dir_csv
ACCESS PARAMETERS (FIELDS TERMINATED BY ',') LOCATION ('customer.csv'));最も一般的なツールは SQL*Loader(制御ファイルを使用)。ファイルをクエリのように読むには外部表を使用する。大容量ではダイレクトパスロード(DIRECT=TRUE)が高速。
PostgreSQL
-- Server side (file on the server; requires superuser/pg_read_server_files)
COPY customer (id, name, email) FROM '/data/customer.csv' WITH (FORMAT csv, HEADER true);
-- Client side (psql, file on the client)
\copy customer (id, name, email) FROM 'customer.csv' WITH (FORMAT csv, HEADER true)COPY はサーバー上のファイルを読み、権限が必要。psql の \copy はクライアントのファイルを読み、追加の権限は不要。CSV をロードする最速の方法。
MySQL
-- Server side
LOAD DATA INFILE '/data/customer.csv' INTO TABLE customer
FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES;
-- From a client file
LOAD DATA LOCAL INFILE 'customer.csv' INTO TABLE customer
FIELDS TERMINATED BY ',' IGNORE 1 LINES;LOAD DATA INFILE は一括ロードの最速の方法。LOCAL はクライアントのファイルを読み、サーバー(local_infile=ON)とクライアントの両方で有効にする必要がある。secure_file_priv はサーバーのパスを制限する。
SQL Server
-- T-SQL BULK INSERT
BULK INSERT customer FROM 'C:\data\customer.csv'
WITH (FORMAT='CSV', FIRSTROW=2, FIELDTERMINATOR=',', ROWTERMINATOR='0x0a');
-- bcp from the shell
bcp mydb.dbo.customer in customer.csv -c -t, -S server -TBULK INSERT は SQL Server サービスアカウントがアクセスできるパスからファイルを読む。bcp はコマンドラインツールで、-c は文字モード、-t はフィールド区切り文字。最大速度を得るには TABLOCK で最小ログ記録を狙う。
MongoDB
# Import CSV / JSON (from the shell)
mongoimport --db=shop --collection=customer --type=csv --headerline --file=customer.csv
# For a JSON array
mongoimport --db=shop --collection=customer --file=customer.json --jsonArraymongoimport は CSV/TSV/JSON をロードする。--headerline は先頭行をフィールド名として扱う。既存ドキュメントを更新するには --mode=upsert --upsertFields を使用する。大容量データでは --numInsertionWorkers で高速化できる。
Redis
# Fastest: feed commands in protocol format and pipe them
cat commands.txt | redis-cli --pipe
# Example lines in commands.txt:
# SET customer:1 "Alice"
# SET customer:2 "Bob"一括ロードには redis-cli --pipe(mass insert)を使用する。単一の接続で RESP プロトコル形式のコマンドをストリーミングするため非常に高速。代わりにパイプライニングでコマンドをまとめる方法もある。
Elasticsearch
# _bulk API (NDJSON: an action line + a source line per document)
curl -s -H 'Content-Type: application/x-ndjson' -XPOST 'localhost:9200/customer/_bulk' --data-binary @data.ndjson
# Contents of data.ndjson:
# { "index": {} }
# { "id": 1, "name": "Alice" }
# { "index": {} }
# { "id": 2, "name": "Bob" }_bulk API は NDJSON を受け付ける(ドキュメントごとにアクション行 + データ行。ファイルは \n で終わる必要がある)。CSV には Logstash、Filebeat または elasticdump を使用する。ロード中に refresh_interval を無効にすると高速化する。