elasticsearch-document-transfer

A modern, high-performance, stream-based data transfer and export pipeline for Elasticsearch (7.x, 8.x, 9.x) and OpenSearch (1.x, 2.x).
Stream documents from a cluster to any combination of destinations simultaneously—Elasticsearch, OpenSearch, CSV, NDJSON, JSON, or custom targets (Postgres, S3, Kafka, etc.)—with native Node.js stream backpressure, per-target progress tracking, and automatic cursor cleanup.
📑 Table of Contents
- Why This Project?
- Key Features
- Installation
- Quick Start
- 1. CLI with Config File
- 2. CLI with Flags
- 3. Programmatic API
- 4. Custom Targets (Postgres, S3, etc.)
- Configuration Reference
- Rules of Thumb (Batch Size & Cursor Mode)
- Testing
- License
🌟 Why This Project?
Elasticsearch indices are immutable when modifying existing field types (e.g. changing from text to keyword, altering analyzers). Re-indexing is mandatory.
While Elasticsearch offers native _reindex and snapshots, a client-side stream pipeline is essential when:
- Direct cluster-to-cluster connection is blocked: Clusters reside in separate VPCs, behind firewalls, or in isolated networks where destination cannot reach source directly.
- No cluster admin privileges: You cannot modify
elasticsearch.yml to whitelist remote hosts (reindex.remote.whitelist) or configure S3 snapshot repositories.
- Multi-destination fan-out: You want to reindex to another cluster while simultaneously generating
.csv, .ndjson.gz, and .json exports (or streaming to Postgres/S3) in a single read pass.
- Cross-version / OpenSearch migrations: Moving data between Elasticsearch and OpenSearch, or across major versions where deprecated mapping types (
_type) cause native reindexing to fail.
🚀 Key Features
- True Stream Pipeline with Backpressure: Powered by Node.js
stream.Readable, stream.Writable, and pipeline()—never accumulates unbounded buffers in memory.
- Modern Elasticsearch & OpenSearch Support: Compatible with Elasticsearch 7.x, 8.x, 9.x, and OpenSearch 1.x / 2.x.
- Multi-Target Fan-Out (
targets array): Stream to multiple clusters, files, and custom destinations at once with synchronized backpressure and per-target summaries.
- Cursor-Based Traversal: Supports Scroll (with automatic
clearScroll cleanup) and search_after.
- Tabular CSV, NDJSON & JSON Exports:
- CSV (
csv): Dot-notation flattening (user.address.city), custom array separators, custom delimiters, and automatic column deduction or custom field mapping.
- NDJSON (
ndjson): 'bulk' (for _bulk restore), 'source' (clean JSONL), or 'document' (_index, _id, _source).
- JSON (
json): Valid streaming JSON array ([...]) with optional pretty-printing.
- Automatic Gzip Compression: Just name any file target
.csv.gz, .ndjson.gz, or .json.gz.
- Custom Targets: Write inline async hooks (
init, write / writeBatch, close) or pass any Node Writable stream directly in targets.
- Mapping Sync & Sanitizer: Automatically copies source index mappings and custom analyzers while unwrapping legacy
_type constructs.
📦 Installation
Install globally or as a project dependency:
# In your project
npm install elasticsearch-document-transfer
# Or run instantly with npx (no install needed!)
npx elasticsearch-document-transfer --help
⚡ Quick Start
1. Using CLI with a Config File
- Create a
config.json in your working directory (see config-sample.json):
{
"source": {
"node": "http://localhost:9200",
"index": "my_source_index",
"batchSize": 500
},
"targets": [
{
"type": "elasticsearch",
"node": "http://localhost:9200",
"index": "my_target_index",
"importMapping": true
},
{
"type": "ndjson",
"filePath": "output/backup.ndjson.gz",
"format": "bulk"
},
{
"type": "csv",
"filePath": "output/report.csv"
},
{
"type": "json",
"filePath": "output/data.json"
}
]
}
- Run the transfer:
npx elasticsearch-document-transfer
# or if cloned locally:
node index.js
2. Using CLI Flags (Quick Transfer)
# Export simultaneously to CSV, compressed NDJSON, and JSON in one pass
npx elasticsearch-document-transfer \
--source-node http://localhost:9200 \
--source-index users \
--target-file ./users.csv \
--target-file ./users_backup.ndjson.gz \
--target-file ./users.json \
--csv-fields "_id,name,email,address.city,roles" \
--csv-array-separator " | " \
--csv-delimiter ";"
# Export to CSV with auto-deduced columns (from index mapping or documents)
npx elasticsearch-document-transfer \
--source-node http://localhost:9200 \
--source-index users \
--target-file ./users_auto.csv.gz
# Migrate from Elasticsearch to OpenSearch
npx elasticsearch-document-transfer \
--source-node https://prod-es.internal:9200 \
--source-index products \
--target-type opensearch \
--target-node https://opensearch.internal:9200 \
--target-index products_v2
3. Programmatic API
const { transfer } = require('elasticsearch-document-transfer');
async function run() {
const result = await transfer({
source: {
node: 'https://prod-es.example.com:9200',
index: 'orders',
auth: { apiKey: process.env.ES_API_KEY },
batchSize: 1000,
cursorMode: 'scroll',
},
targets: [
{
type: 'elasticsearch',
node: 'http://localhost:9200',
index: 'orders_copy',
importMapping: true,
},
{
type: 'ndjson',
filePath: './orders_backup.ndjson.gz',
format: 'bulk',
},
{
type: 'csv',
filePath: './orders.csv',
fields: ['_id', 'total', 'customer.email', 'tags'],
},
{
type: 'json',
filePath: './orders.json',
},
],
transform: {
// Optional: modify or filter documents on the fly
fn: (doc, count) => {
if (doc._source.isTest) return null; // filter out test documents
doc._source.migratedAt = new Date().toISOString();
return doc;
},
},
});
console.log(`Transferred ${result.transferred} docs in ${result.durationMs}ms`);
console.log('Per-target summary:', result.targets);
}
run();
4. Adding Custom Targets
You can send documents to Postgres, S3, Kafka, webhooks, or any custom destination:
Option A: Inline Async Hooks (Recommended — no stream code needed)
await transfer({
source: { node: 'http://localhost:9200', index: 'orders' },
targets: [
{
type: 'custom',
name: 'postgres-orders',
batchSize: 500,
init: async () => { await pgClient.connect(); },
writeBatch: async (docs) => { await insertOrders(pgClient, docs); },
close: async () => { await pgClient.end(); },
},
],
});
Option B: Pass Any Node.js Writable Stream Directly
await transfer({
source: { node: 'http://localhost:9200', index: 'orders' },
targets: [
myS3UploadWritableStream, // backpressure and progress are tracked automatically
],
});
🛠️ Configuration Reference
| Option |
Type |
Default |
Description |
source.node |
string \| string[] |
(required) |
Source cluster URL(s) |
source.type |
'elasticsearch' \| 'opensearch' |
'elasticsearch' |
Client engine |
source.index |
string |
(required) |
Source index name |
source.query |
object |
{ match_all: {} } |
Elasticsearch Query DSL filter |
source.batchSize |
number |
500 |
Hits per page |
source.cursorMode |
'scroll' \| 'search_after' |
'scroll' |
Cursor pagination strategy ('scroll' or 'search_after') |
source.scrollTime |
string |
'2m' |
Keep-alive timeout for scroll context |
source.auth |
object |
undefined |
{ apiKey } or { username, password } |
source.tls |
object |
undefined |
{ rejectUnauthorized: false, ca: '...' } |
targets |
Array<TargetConfig> |
(required) |
List of target destinations (elasticsearch, opensearch, csv, ndjson, json, custom, or Writable) |
targets[].enabled |
boolean |
true |
Enabled by default when present; set to false to skip a target entry |
targets[].name |
string |
auto |
Display label used in live progress and summary output |
📖 Full Configuration Guide: See docs/CONFIGURATION.md for per-type target schemas (elasticsearch, opensearch, csv, ndjson, json, custom) and transform hooks.
💡 Rules of Thumb: Setting batchSize and cursorMode
Choosing batchSize
- Default (
500): Ideal baseline for standard documents (1KB–10KB).
- Decrease to
100–250: If documents contain large text blocks, nested objects, or base64 attachments (>50KB each). Prevents exceeding HTTP payload limits.
- Increase to
1,000–2,000: If documents are tiny (\<1KB) and target cluster has high write capacity.
- Goal: Aim for bulk payload batches between 5MB and 15MB (Elasticsearch's recommended sweet spot).
Choosing cursorMode
scroll (Recommended Universal Default):
- Works reliably across all Elasticsearch versions (6.x, 7.x, 8.x, 9.x) and OpenSearch (1.x, 2.x).
- Automatically applies
_doc sorting for optimal extraction throughput.
- Scroll contexts are automatically cleared (
clearScroll) on completion to avoid memory leaks.
search_after:
- Uses stateless pagination sorted by
_doc by default (custom sort supported).
- Recommended when cluster administrators restrict open scroll contexts on busy multi-tenant production clusters.
🧪 Testing
Run the automated test suite (uses Node.js built-in test runner):
npm test
npm run test:e2e
📄 License
MIT © Gaurang Pansare