-
코로나19 백신 접종 현황 차트 페이지 만들기 - (3) node.js elasticsearch 모듈 설치와 사용Node.js/예제 2021. 5. 29. 13:26
1. node.js elasticsearch 모듈 설치하기
node.js에서 elasticsearch를 사용하기 위해 npm으로 모듈을 설치한다. 다음 명령어로 모듈을 설치한다
npm install @elastic/elasticsearch
모듈에 대한 상세한 정보와 사용법은 elastic 홈페이지에서 공식 문서를 통해 확인할 수 있다.(https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html)
2. getdata: elasticsearch SQL과 Query Dsl을 이용한 데이터 조회
getdata.js
const { Client } = require('@elastic/elasticsearch'); const client = new Client({ node: 'http://localhost:9200' }); exports.getDataUsingSql = async (query, size) => { const { body } = await client.sql.query({ body: { query, fetch_size: size ? size : 1000 } }); return body; }; exports.getDataQdsl = async (index, obj, type) => { const { body } = await client.search({ index, body: obj }); if (type === "agg") { return body.aggregations; } return body.hits.hits; };
elasticsearch 모듈을 활용하여 데이터를 조회하는 코드는 모든 api에서 동일한 방식으로 반복적으로 사용할 것이기 때문에 공통 모듈 코드로 분리를 해놓았다. 두 개의 함수를 생성하였는데, getDataUsingSql은 elasticsearch에서 지원하는 SQL 문법을 통해 데이터를 조회할 수 있는 함수이고, getDataQdsl은 기본적인 QueryDsl을 통해 데이터를 조회할 수 있는 함수다.
elasticsearch 모듈은 elasticsearch sql 문법을 통해 데이터를 조회할 수 있는 기능을 지원을 한다. SQL 문법을 사용한다면 Query Dsl을 사용하는 것보다 상대적으로 짧은 코드로 데이터를 조회할 수 있다는 장점이 있지만, SQL의 모든 기능이나 복잡한 집계 조건 방식을 모두 지원하지는 않기 때문에 SQL 문법에만 의존하여 사용하기에는 한계가 있다. 따라서 간단한 데이터 조회는 SQL 방식을 사용하도록 하고, SQL 문법으로 조회되지 않는 복잡한 조건이 걸린 데이터는 Query Dsl을 사용하여 데이터를 조회하는 방식을 사용하였다.
getDataUsingSql은 2개의 파라미터를 받는다. 첫 번째 파라미터 query는 SQL 쿼리문으로 된 String 값이다. 첫 번째 인자로 SQL 쿼리문을 투입한다. 두 번째 파리미터 size는 조회되는 데이터 개수를 지정한다. 사이즈를 지정하지 않으면 최대 1000개 밖에 조회가 되지 않는다. limit 키워드로 1000 이상의 수를 지정해도 1000까지 밖에 조회되지 않기 때문에 fetch_size 옵션으로 조회 수량을 늘려줘야 한다. 만약 1000개가 넘는 데이터를 조회해야 하는 경우 두 번째 파라미터에 최대 조회 개수를 지정한다. 값을 지정하지 않는 경우 디폴트값은 1000으로 지정된다.
getDataQdsl은 3개의 파라미터를 받는다. 첫 번째 파라미터 index는 조회할 인덱스, 두 번째 파라미터 obj는 Query Dsl, 세 번째 파라미터 type은 조회 데이터 유형이다. 기본적으로 결과는 hits에 저장이 되어 반환되지만 집계 데이터는 조회시 결과값이 aggregations 값에 들어있기 때문에 타입을 agg로 지정할 경우 aggregations를 반환하도록 설정하였다. 집계 데이터를 조회해야 하는 경우라면 세 번째 인자를 agg로 지정하고, 일반 데이터라면 세 번째 인자를 생략한다.
'Node.js > 예제' 카테고리의 다른 글
코로나19 백신 접종 현황 차트 페이지 만들기 - (5) highchart 라이브러리와 piechart (1) 2021.06.01 코로나19 백신 접종 현황 차트 페이지 만들기 - (4) charts 페이지 및 metric (0) 2021.05.29 코로나19 백신 접종 현황 차트 페이지 만들기 - (2) 소스 구조 및 view 코드 (0) 2021.05.29 코로나19 백신 접종 현황 차트 페이지 만들기 - (1) elasticsearch 세팅 및 데이터 업로드하기 (1) 2021.05.28 코로나19 백신 접종 현황 차트 페이지(node.js, elasticsearch) (0) 2021.05.27