카테고리 없음

Big query

namu445 2022. 6. 24. 14:27

페타바이트에 달하는 큰 데이터에 대해 SQL쿼리를 수행하고 빠르게 분석할 수 있게 해주는 GCP 서비스 Data Warehouse라고도 한다.

 

BigQuery란 무엇인가요?  |  Google Cloud

의견 보내기 BigQuery란 무엇인가요? BigQuery는 머신러닝, 지리정보 분석, 비즈니스 인텔리전스와 같은 기본 제공 기능으로 데이터를 관리하고 분석할 수 있게 해주는 완전 관리형 엔터프라이즈 데

cloud.google.com

 

  • 이번에는 TypeORM을 이용해서 GCP Big Query로 트리거를 작성해서 사용하는 방법을 연습힙니다

GCP에서 테이블을 생성하고 트리거에 따라 저장된 데이터를 조회했다.

트리거 기본 설정

import { Connection, EntitySubscriberInterface, EventSubscriber } from 'typeorm';

import { Product } from './product.entity';

@EventSubscriber()
export class ProductSubscriber implements EntitySubscriberInterface<Product> {
  // Product Entity가 트리거 대상
  constructor(connection: Connection) {
    connection.subscribers.push(this); //this는 ProductSubscriber
  }
  listenTo() {
    return Product;
  }

  //트리거 예시, event에는 Entity 정보 등이 들어있다
  afterInsert(event: InsertEvent<Product>): void | Promise<any> {}

  beforeInsert(event: InsertEvent<Product>): void | Promise<any> {}

  afterUpdate(event: UpdateEvent<Product>): void | Promise<any> {}
}

 

주의

  • 핵심 비즈니스 로직의 기능을 트리거로 작성해서는 안된다. => 중요 테이블의 원본 데이터(값)이 변경되는 기능
  • 코드파악 난이도가 올라간다. => 유지 보수에 더 신경써야한다
  • 트리거는 원본 데이터로 통게를 작성하거나 로그를 남기는 등 파생결과를 남기기위해 사용하는 것이 좋다.

Install

yarn add @google-cloud/bigquery

트리거에 Big Query를 적용했을 때

import { Connection, EntitySubscriberInterface, EventSubscriber, InsertEvent } from 'typeorm';
import { BigQuery } from '@google-cloud/bigquery';
import dotenv/config

import { Product } from './product.entity';

@EventSubscriber()
export class ProductSubscriber implements EntitySubscriberInterface<Product> {
  // Product Entity가 트리거 대상
  constructor(connection: Connection) {
    connection.subscribers.push(this); //this는 ProductSubscriber
  }
  listenTo() {
    // 연결 대기
    return Product;
  }

  afterInsert(event: InsertEvent<Product>): void | Promise<any> {
    console.log(event);

    // 키파일과 ID는 GCP에서 확인한다
    const bigQuery = new BigQuery({
      keyFilename: '',
      projectId: '',
    });

    bigQuery //데이터 셋과 테이블 이름은 GCP에서 생성한 이름과 같아야한다.
      .dataset(process.env.GCP_BIGQUERY_DATASET)
      .table(process.env.GCP_BIGQUERY_TABLE)
      .insert([
        {
          // 속성은 entity, GCP 테이블 스키마와 같아야한다.
          id: event.entity.id,
          name: event.entity.name,
        },
      ]);
  }
}