Node.js
[NodeJS] ElasticSearch search 결과로 bulk 파일 만들기
SongMinu
2021. 11. 24. 17:30
728x90
elasticsearch 7.x 기준
const fs = require('fs');
const es_client = require('./client');
const is_id = true
const index_name = 'idx_text';
const query = {
size: 100,
query : {
bool : {
must : [
]
}
}
}
async function run() {
let rs = await es_client.search({
index: index_name,
type: '_doc',
body: query,
scroll: '1m'
})
let bulk = '';
while(rs.hits.hits.length > 0) {
rs.hits.hits.map( (doc) => {
if (is_id) {
bulk += JSON.stringify({index: {_index: doc._index, _type: doc._type, _id: doc._id}}) + '\n';
} else {
bulk += JSON.stringify({index: {_index: doc._index, _type: doc._type}}) + '\n';
}
bulk += JSON.stringify(doc._source) + '\n';
})
rs = await es_client.scroll({ scrollId: rs._scroll_id, scroll: '1m'});
}
fs.writeFileSync('./_bulk/' + index_name, bulk);
}
run();
is_id : bulk 데이터 만들 때 조회한 데이터에서 _id를 넣을지 말지 결정
index_name : 조회할 인덱스명
query : 인덱스에서 데이터 조회할 쿼리
데이터가 많을 수도 있기 때문에 scroll 검색 방식으로 처리하게함
bulk 데이터를 모두 만들면 해당 인덱스명으로 파일을 생성.
아주 간단한 로직으로 만든거라 좀 더 응용을 해본다면,
모듈화를 시켜서 인덱스명, 쿼리를 받아서 데이터를 생성하게끔 하는 방법..?
인자값을 인덱스명, 쿼리 말고 더 넣어서 처리할 수도 있을 것 같고...
당장은 떠오르는게 이거밖에 없네..
https://github.com/smw0807/minu_1/blob/master/node/es_functions/run_make_bulk.js
반응형