-
Notifications
You must be signed in to change notification settings - Fork 20
/
elasticsearch-import.js
71 lines (65 loc) · 1.47 KB
/
elasticsearch-import.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
const db = require('./utils/db.js');
const elasticsearch = require('elasticsearch');
const client = new elasticsearch.Client({
host: 'localhost:9200'
});
db( db => {
const cursor = db.collection( 'AddressSimple' ).find({});
getNext( cursor, () => {
/* Check to see if there is any more left in the batch */
if ( batch.length > 0 ) {
insertDocs( batch, () => {
batch = [];
console.log( 'Completed' );
db.close();
});
} else {
console.log( 'Completed' );
db.close();
}
});
});
let batch = [];
let count = 0;
getNext = ( cursor, callback ) => {
cursor.nextObject( (err, doc) => {
if ( err || !doc ) {
callback();
return;
}
if ( batch.length < 1000 ) {
batch.push( doc );
getNext( cursor, callback );
} else {
insertDocs( batch, () => {
batch = [];
getNext( cursor, callback );
});
}
});
}
insertDocs = ( docs, callback ) => {
const batchData = [];
let left = docs.length;
docs.forEach( ( doc, i ) => {
delete doc._id;
batchData.push({
index: {
_index: "address",
_type: "singleAddress",
}
});
batchData.push( doc );
});
client.bulk({
body: batchData
}, ( err, resp, status ) => {
count+= docs.length;
if ( count % 1000 === 0 ) {
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write( `${count} records imported` );
}
callback();
});
}