# Embulk Bulk Import From Google Sheets

この記事では、embulk-input-google_spreadsheets入力プラグインを使用して、Google SheetsからTreasure Dataにデータをインポートする方法について説明します。

以下のトピックに進みます:

このコンテンツは古いため、今後更新されません。Treasure Dataでは、ネイティブの[Google Sheetsインテグレーション](/int/google-sheets-import-integration)の使用を推奨しています。

## 前提条件

- Treasure Dataの基礎知識
- [Embulk](http://www.embulk.org/docs/)の基礎知識
- EmbulkはJavaアプリケーションです。Javaがインストールされていることを確認してください。
- [Installing Bulk Data Import](/products/customer-data-platform/integration-hub/batch/import/bulk-data-import#installing-bulk-data-import)の手順に従ってください。
- [Embulkおよびembulk-output-tdプラグイン](http://www.embulk.org/docs/)がマシンにインストールされていること。


## embulk-input-google_spreadsheetsプラグインのインストール

embulk-input-google_spreadsheetsプラグインをインストールするには、次のコマンドを実行します:


```bash
embulk gem install embulk-input-google_spreadsheets
```

## 必要なGoogle API認証情報の取得

EmbulkがGoogle Sheets APIに接続するには、さまざまな認証オプションが利用可能です。この例では、JSONキーファイルを必要とする`authorized_user`メソッドを使用します。キーファイルはGoogle APIコンソールから取得できます。このキーファイルには、Google Sheets APIへの接続を許可する認証情報が含まれています。Embulkプラグインの実行に必要な3つのフィールドがあります。


```
* client_id
* client_secret
* refresh_token
```

既存のGoogle APIプロジェクトからキーファイルをダウンロードする必要があります。プロジェクトを作成していない場合は、Googleが提供するこのウィザードを使用してプロジェクトを作成し、Google Sheets APIを有効にすることができます。[Google Sheets APIウィザード](https://console.developers.google.com/flows/enableapi?apiid=sheets.googleapis.com)

Credentials > Create Credentials > OAuth ClientID > Web Applicationに移動します。名前を入力して「Create」をクリックします。次の画面にクライアントIDとクライアントシークレットが表示されます。JSONキーファイルに必要なため、これらをコピーしてください。これらの手順を完了すると、`client_id`と`client_secret`が提供されます。

## Google OAuth 2.0 PlaygroundリダイレクトURIの追加

Google OAuth 2.0 Playgroundからリフレッシュトークンを取得する必要があります。作成した認証情報の承認済みリダイレクトURIに、OAuth 2.0 PlaygroundリダイレクトURI([https://developers.google.com/oauthplayground](https://developers.google.com/oauthplayground))を追加する必要があります。

1. Google OAuth 2.0 Playgroundで使用する認証情報を編集するには、鉛筆アイコンを選択します。


![](/assets/image-20191021-195257.838c1f343dcbda0b041055d8fb826b79bda29a1aaf9532a3803b12b198e1f27c.0563afda.png)

1. Authorized Redirect URIフィールドに、Auth PlaygroundのURL: [https://developers.google.com/oauthplayground](https://developers.google.com/oauthplayground)を入力します。Enterキーを押して、「保存」を選択します。


![](/assets/image-20191021-195308.303d1022fa20fcb5e9430c1d0f3effb5e779b3da62e3adc880d16509e0675e81.0563afda.png)

必要な残りの認証情報はリフレッシュトークンです。リフレッシュトークンを取得する1つの方法は、[Google OAuth 2.0 Playground](https://developers.google.com/oauthplayground/)で利用可能なGoogle OAuth 2.0 Playgroundを使用することです。

右上の歯車アイコンを選択し、「Use your own OAuth credentials」を選択してください。OAuth Client IDとOAuth Client secretフィールドに、Google APIコンソールから取得した認証情報を挿入します。

左側のAPIリストから、Google Sheets API v4を選択します。次に、Step 2. - Exchange authorization code for tokensに進みます。「Exchange authorization code for tokens」ボタンを押すと、Refresh TokenとAccess Tokenフィールドが入力されます。リフレッシュトークンフィールドの値は、Embulkが必要とするJSONキーファイルに記録する必要がある値です。JSONキーファイルのすべてのコンポーネントが収集されたら、Embulkの設定を開始する準備が整いました。JSONキーファイルの形式は次のとおりです:


```json
{
    "client_id": "xxxxxxxxxx",
    "client_secret": "xxxxxxxxxx",
    "refresh_token": "xxxxxxxxxx"
}
```

## Embulk設定ファイルの作成

お気に入りのテキストエディターを使用して、入力(Google Sheets)と出力(TD)のパラメーターを定義するEmbulk設定ファイルを作成します。

以下の例では、必要なJSONキーファイルがインラインで使用されています。追加のパラメーターの詳細や他の例については、[Embulk Input Google Sheets](https://github.com/medjed/embulk-input-google_spreadsheets)を参照してください。

プラグインの実行に必要なフィールドは、spreadsheets_urlとworksheet_titleです。インポートしようとしているシートの関連する詳細を編集してください。出力セクションにも同様に適用され、Treasure Dataに出力されます。

この例では、設定ファイルで使用されている詳細に一致する関連テーブルをTreasure Dataですでに作成していることを前提としています。例えば、databaseはデータ用に作成されたデータベース、tableはそのデータベース内でデータを受信するテーブルです。


```yaml
in:
    type: google_spreadsheets
    auth_method: authorized_user
    json_keyfile:
        content: |
            {
                "client_id": "xxxxxxxxxx",
                "client_secret": "xxxxxxxxxx",
                "refresh_token": "xxxxxxxxxx"
            }
    spreadsheets_url: https://docs.google.com/spreadsheets/d/1xP_ZBA-Or4sJ63Zj99-JreuAFGn7Y2gcUKd1vtwSqwM/edit#gid=0
    worksheet_title: title
    start_row: starting row
    default_timezone: timezone to be used
    null_string: '\N'
    default_typecast: strict
    columns:
        - {name: color, type: string}
        - {name: size, type: string}
        - {name: type, type: string}
out:
    type: td
    apikey: xxxxxxxxxxxx
    endpoint: api.treasuredata.com
    database: dbname
    table: tblname
    time_column: datecolumn
    mode: replace
    #デフォルトでは、定義されていない場合、mode: appendが使用されます。このモードでは、インポートされたレコードがターゲットテーブルに追加されます。
    #mode: replaceは、既存のターゲットテーブルを置き換えます
    default_timestamp_format: '%d/%m/%Y'
```

load.ymlに「auto_create_table: true」パラメーターを追加して、存在しないテーブルが自動的に作成されるようにします。

これは、.ymlファイルのauto_create_tableパラメーターの例です。


```yaml
out:
  type: td
  apikey: your apikey
  endpoint: api.treasuredata.com
  database: dbname
  table: tblname
  time_column: created_at
  auto_create_table: true
  mode: append
```

ロードジョブを実行する前に、TDでデータベースとテーブルを作成する必要があります。または、1) データベースを追加する必要がある場合、または2) .ymlファイルにauto_create_tableパラメーターを追加せずにテーブルを追加する必要がある場合は、次のTDコマンドを実行します:


```
$ td database:create dbname
$ td table:create dbname tblname
```

[Treasure コンソール](https://console.treasuredata.com/app/databases)を使用してデータベースとテーブルを作成することもできます。

## ロードジョブの実行

次のコマンドを実行して、インポートジョブを発行します:


```
embulk run load.yml
```

インポートジョブの実行時間は、インポートするデータのサイズによって異なります。ジョブが完了すると、Embulk設定ファイルで使用されたTDデータベースとテーブルにデータが反映されます。