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); });
추가로 여러 가지 써보며 작성하도록 하겠습니다.
감사합니다.
'프로그래밍' 카테고리의 다른 글
[GCP] Load balancing with firewall rules (0) | 2018.12.14 |
---|---|
[Mysql] date parse STR_TO_DATE / 문자열 날짜로 변환 (0) | 2018.12.12 |
[javascript] 숫자 소수점 자리수 선택, 자르기 toFixed() (0) | 2018.03.30 |
[Mysql] CONCAT 함수 / 문자열 연결, 합치기 (0) | 2018.03.19 |
[Mysql] REPLACE 함수 / 문자열 변경 (2) | 2018.03.19 |