-
Notifications
You must be signed in to change notification settings - Fork 0
/
pgToElastic.js
52 lines (43 loc) · 1.46 KB
/
pgToElastic.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
var pg = require('pg')
var elastic = require('elasticsearch')
var QueryStream = require('pg-query-stream')
var ElasticsearchBulkIndexStream = require('elasticsearch-bulk-index-stream');
var transform = require('stream-transform');
var client = new pg.Client(process.env.PG_CONNECTION_STRING);
var elasticClient = new elastic.Client({
host: process.env.ELASTIC_HOST,
maxRetries: 10,
requestTimeout: 60000
});
var query = new QueryStream('SELECT * FROM companies ORDER BY id');
client.connect(function onPgConnect(err) {
var stream, elasticStream, transformer;
if(err) throw err;
stream = client.query(query);
elasticStream = new ElasticsearchBulkIndexStream(elasticClient, {
highWaterMark: process.env.BATCH_SIZE || 10000,
flushTimeout: 500
});
transformer = transform(function(record) {
console.log('write', record.id);
return {
index: 'companies_index',
type: 'companies-type',
id: record.id,
body: Object.assign({}, record) // prevent memory leak
};
}, {parallel: 10, highWaterMark: process.env.BATCH_SIZE || 10000 });
stream.on('error', function onPgErr(err) { console.log('error', err); });
stream.on('close', function onPgClose(){
client.end(); console.log('pg done');
});
stream
.pipe(transformer)
.pipe(elasticStream)
.on('error', function onEsErr(error) {
console.log('error', error);
})
.on('finish', function onEsFinish() {
console.log('elastic finish');
});
});