DBAtlas · Atlas de operaciones de bases de datos

Carga masiva de datos (CSV / desde archivo)

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'));

La herramienta más habitual es SQL*Loader (con un control file). Para leer el archivo como una consulta, use una external table. Para grandes volúmenes, la carga direct path (DIRECT=TRUE) es rápida.

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 lee un archivo en el servidor y requiere privilegios; psql \copy lee un archivo del cliente y no necesita privilegios adicionales. Es la forma más rápida de cargar 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 es la forma más rápida de carga masiva. LOCAL lee un archivo del cliente y debe estar habilitado tanto en el servidor (local_infile=ON) como en el cliente. secure_file_priv restringe la ruta del servidor.

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 -T

BULK INSERT lee el archivo desde una ruta accesible para la cuenta de servicio de SQL Server. bcp es una herramienta de línea de comandos; -c es el modo carácter, -t el terminador de campo. Para la máxima velocidad, busque un registro mínimo (minimal logging) con 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 --jsonArray

mongoimport carga CSV/TSV/JSON; --headerline trata la primera línea como nombres de campo. Para actualizar documentos existentes, use --mode=upsert --upsertFields. Para grandes volúmenes, --numInsertionWorkers lo acelera.

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"

Para la carga masiva, use redis-cli --pipe (mass insert); es muy rápido porque envía los comandos en formato de protocolo RESP por una única conexión. Como alternativa, los comandos se agrupan con pipelining.

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" }

La API _bulk recibe NDJSON (una línea de acción + una línea de datos por documento; el archivo debe terminar con \n). Para CSV, use Logstash, Filebeat o elasticdump. Desactivar refresh_interval durante la carga la acelera.

Abrir en DBAtlas →