본문으로 바로가기

[GCP] bigquery nodejs example

category 프로그래밍 2018. 11. 21. 18:11
728x90

GCP에서 제공하는 서비스인 bigquery를 nodejs로 작성한 예제입니다.


#bigquery library 설치

$npm install --save @google-cloud/bigquery


#테이블 생성

const BigQuery = require('@google-cloud/bigquery');
const projectId = "projectId";
const datasetId = "datasetId";
const tableId = "tableId"
const schema = "schema_1:INTEGER, schema_2:FLOAT" //table schema set

const bigquery = new BigQuery({
    projectId: projectId
});

const options = {
    schema: schema
}

bigquery
    .dataset(datasetId)
    .createTable(tableId, options)
    .the(results => {
        const table = results[0];
        console.log(`Table ${table.id} created.`);
    })
    .catch(err => {
        console.error('ERROR:', err);
    });


#query 명령

const BigQuery = require('@google-cloud/bigquery'); const bigquery = new BigQuery({     projectId: projectId }); const sqlQuery = `some query ...`; const options = { query: sqlQuery, location: 'US' };

await bigquery.query(options);


#Table truncate query

해당 테이블의 모든 데이터를 지우고자 할때 사용하는 쿼리입니다.

DELETE FROM dataset.table WHERE 1=1


#Google Cloud Storage의 csv파일 데이터를 bigquery의 table에 import

Cloud Storage Library도 설치를 합니다.

$npm install --save @google-cloud/storage


GCS의 특정 경로의 파일을 bigquery에 바로 import하는 코드입니다.

//bigquery 변수

const BigQuery = require('@google-cloud/bigquery'); const bigquery = new BigQuery({ projectId: projectId }); const datasetId = "datasetId"; const tableId = "tableId"


//Google Cloud Storage 변수

const Storage = require('@google-cloud/storage');

const storage = Storage();

const bucket = storage.bucket('bucket_name); //사용할 버킷 입력


const filePath = 'book/harry_potter_1';


const metadata = { sourceFormat: 'CSV', skipLeadingRows: 1, schema: { fields: [ {name: 'title', type: 'STRING'}, {name: 'episode', type: 'INTEGER'}, {name: 'index', type: 'INTEGER'} ] } };


bigquery .dataset(datasetId) .table(tableId) .load(bucket.file(filePath), metadata) .then(results => { const job = results[0]; console.log(`Job ${job.id} completed.`); const errors = job.status.errors; if (errors && errors.length > 0) { throw errors; } }) .catch(err => { console.error('ERROR:', err); });


추가로 여러 가지 써보며 작성하도록 하겠습니다.

감사합니다.

728x90