# Magento Export Integration

Magentoは、顧客向けにカスタマイズされたショッピング体験を作成するのに役立ちます。MagentoはPHPで書かれたオープンソースのeコマースプラットフォームです。

Treasure Dataからクエリジョブの結果を直接Magento（v2）に書き込むことができます。

## 前提条件

- Treasure Dataの基本知識
- Magento 2の基本知識（Treasure Dataはv. 2.4.6をサポート）
- Bulk API Magento 2の基本知識
- JSON形式のクエリとPOST API形式の理解


## サポート内容

このインテグレーションは、次の仕様を持つAPIをサポートします。

- POST API
- Bulk API
例えば、非同期読み込みをサポート - [https://devdocs.magento.com/guides/v2.4/rest/bulk-endpoints.html](https://devdocs.magento.com/guides/v2.4/rest/bulk-endpoints.html)
- オブジェクトの配列を使用します。
例：



```json
[{"column1":"v1_1", "column2":"v2_1"},{"column1":"v1_2", "column2":"v2_2"},...]
```

## 制限事項

### トークンの有効期限

デフォルトでは、管理者トークンは4時間有効です。ジョブの実行に長時間かかる場合は、管理者ページからこれらの値を変更できます。

### パフォーマンス

セルフホスト型のMagentoインスタンスでは、次の環境例でパフォーマンスベンチマークが実行されました。

- EC2インスタンス: T2.medium
- RAM: 4GB
- ストレージ: 50 GB EBSおよびインストールされたコンポーネント
- [https://github.com/clean-docker/Magento2/blob/master/docker-compose.yml](https://github.com/clean-docker/Magento2/blob/master/docker-compose.yml) + rabbitMQ


デフォルト設定を使用した場合、次のパフォーマンスベンチマーク結果が得られました。

- 1000レコード、2カラム、26 KB → 1分
- 1500レコード、2カラム、43 KB → 1分
- 10000レコード、2カラム、279 KB → 12分
- 1000000レコード、2カラム、29.3 MB → 12時間16分


## Magentoエクスポート結果のクエリ例

POST APIリクエストのJSONフィールドは、TDクエリ結果でJSONまたはStringとして指定する必要があります。

POST APIエンドポイントのMagentoリファレンスドキュメント:

[**https://magento.redoc.ly/**](https://magento.redoc.ly/)

以下は、異なるエンドポイントのクエリの例です。

**POST APIエンドポイント:** /async/bulk/V1/products


```sql
SELECT
'{
	"id": 45638,
	"sku": "39887-speaker-XL",
	"name": "39887-speaker-XL",
	"attribute_set_id": 9,
	"price": 450,
	"status": 1,
	"visibility": 1,
	"type_id": "virtual",
	"created_at": "2016-04-05 23:04:09",
	"updated_at": "2016-04-05 23:04:09",
	"product_links": [],
	"options": [],
	"tier_prices": [],
	"custom_attributes": [{
			"attribute_code": "description",
			"value": "pPrecise Long-Sleeve Shirt in Black, Denim, or White.</p>"
		},
		{
			"attribute_code": "meta_title",
			"value": "Precise Long-Sleeve Shirt"
		},
		{
			"attribute_code": "meta_keyword",
			"value": "Precise Long-Sleeve Shirt"
		},
		{
			"attribute_code": "meta_description",
			"value": "Precise Long-Sleeve Shirt pPrecise Long-Sleeve Shirt in Black, Denim, or White.</p>"
		},
		{
			"attribute_code": "color",
			"value": "11"
		},
		{
			"attribute_code": "options_container",
			"value": "container2"
		},
	},
	{
		"attribute_code": "required_options",
		"value": "0"
	},
	{
		"attribute_code": "has_options",
		"value": "0"
	},
	{
		"attribute_code": "url_key",
		"value": "10090-white-xl"
	},
	{
		"attribute_code": "msrp_display_actual_price_type",
		"value": "0"
	},
	{
		"attribute_code": "tax_class_id",
		"value": "2"
	},
	{
		"attribute_code": "size",
		"value": "8"
	}
]
}' AS product,
TRUE AS saveOptions
```

**POST API Endpoint**: /async/bulk/V1/customers


```sql
SELECT '{
  "email":"dummyuser@example.com",
  "firstname":"test",
  "lastname":"user",
  "addresses":[
     {
        "region":{
           "region_code":"MI",
           "region":"Michigan",
           "region_id":33
        },
        "region_id":33,
        "country_id":"US",
        "street":[
           "6146 Honey Bluff Parkway"
        ],
        "telephone":"(555) 229-3326",
        "postcode":"49628-7978",
        "city":"Calder",
        "firstname":"Veronica",
        "lastname":"Costello",
        "default_shipping":true,
        "default_billing":true
     }
  ]
}' as customer,
'dummy!@@#A_pass' as password;
```

Treasure Dataから、以下のクエリを実行し、結果をMagento用のコネクションにエクスポートします：


```sql
SELECT
  '{"email":"demo@example.com","firstname":"demo Shaw","lastname":"Doe","addresses":[{"region":{"region_code":"MI","region":"Michigan","region_id":33},"region_id":33,"country_id":"US","street":["6146 Honey Bluff Parkway"],"telephone":"(555) 229-3326","postcode":"49628-7978","city":"Calder","firstname":"Veronica","lastname":"Costello","default_shipping":true,"default_billing":true}]}' AS customer,
  'Strong-Password' AS password
```

サンプルパラメータ設定：

![](/assets/image-20200825-085456.8fa499e4ff9d88e5072729089547eb4e28c5de2f15abf1a277c6b1f38d383389.989f2923.png)

## Treasure コンソールを使用してコネクションを作成する

データコネクションを設定する際、統合にアクセスするための認証情報を提供します。Treasure Dataでは、認証を設定してからソース情報を指定します。

1. Treasure コンソールを開く
2. **Integrations Hub** > **Catalog**に移動します。
3. Magentoを検索します。
4. **Create Authentication**を選択します。
![](/assets/image-20250822-140728.e8695503e3a649680a13c14c0403a32f92e1c78e18dd5e0bb34b979722769fcb.989f2923.jpeg)
![](/assets/image-20250822-140802.db237f9d42c38ad8fe9b945b173d0889274e7d4ebfae1d9a4f0bb837d56a5a7d.989f2923.jpeg)
5. 以下のダイアログが開きます。認証モードの1つを選択します。必要な認証情報を編集します。![](/assets/image-20200317-183839.4d35134146edba63454b6f351e5d060e1914144d7cacc62ad57574c59d4284a6.989f2923.png)
6. Continueを選択します。


### 認証モードオプション

#### ログイン認証情報を使用して認証する

1. **Login Credential**を選択し、管理者レベルのユーザー名とパスワードを入力します。


![](/assets/image-20200318-192714.cf2bb6ce3914c506302a659a9c7bdce4800cc19fd7f89b07162fbbcc4791eef8.989f2923.png)

#### 統合アクセストークンを使用して認証する

1. アクセストークンを取得するには、Magento管理画面で、**System** > **Integrations** > **Add New Integration**に移動します(または既存のものを開きます)。
![](/assets/image-20200318-212932.2f950528d6adc67fb720325f8320ecc9718ebe4a43ad8d655234b3479faf7fd5.989f2923.png)
2. ターゲットリソースに適切な権限を選択します。
![](/assets/image-20200318-220439.3829bc484fad0ad9c5a077a17dd590e206daff53c9d147c5574b172e88117978.989f2923.png)
3. インテグレーションをアクティベートします。
4. Access Tokenをコピーします。
![](/assets/image-20200318-220508.9f6611d1ce67884e1e1bd6615166fd4457a97993f6f95fc7b35516d5099c0731.989f2923.png)
5. Treasure Dataで、アクセストークンの名前を貼り付けます。**Base URL**には、Magento 2 REST APIエンドポイントの値を設定します。例:`http://my-magento-server/rest/`
![](/assets/image-20200318-220536.ba9ec1ed7f4cbb0d027b43fef6c3cba87e4877427e4ff71db7d954009cc4dc90.989f2923.png)
6. **Continue**を選択します。
7. Authenticationに名前を付けます。
8. **Done**を選択します。


### データコネクションでエクスポート結果を設定する

このステップでは、クエリを作成または再利用します。クエリで、データコネクションを設定します。

1. Treasure コンソールを開きます。
2. **Data Workbench** > **Queries**に移動します。
3. データのエクスポートに使用する予定のクエリを選択します。
例:



```sql
SELECT
   '{"email":"demo@example.com","firstname":"demo Shaw","lastname":"Doe","addresses":[{"region":{"region_code":"MI","region":"Michigan","region_id":33},"region_id":33,"country_id":"US","street":["6146 Honey Bluff Parkway"],"telephone":"(555) 229-3326","postcode":"49628-7978","city":"Calder","firstname":"Veronica","lastname":"Costello","default_shipping":true,"default_billing":true}]}' as customer,
   'Strong-Password' as password;
```

1. クエリエディタの上部にある**Export Results**を選択します。
Choose Integrationダイアログが開きます。
![](/assets/image-20200825-223144.990c42f1a0e18c8472eeff91dfd16817d17487a3db9f72648e41930e563576a5.989f2923.png)
2. 以下のいずれかを選択します:


- 既存のコネクションを使用する


1. **Use Existing Integration**を選択します。
2. 検索ボックスにコネクション名を入力してフィルタリングします。
3. コネクションを選択します。


- 新しいインテグレーションを作成する


1. Create New Integrationを選択します。


![](/assets/image-20200825-075856.8166112f0e5ffaca3585b9f8f16352a6c22e1c82113e3ca9ec1eb90fd3692d7e.989f2923.png)
2. Treasure コンソールを使用して接続するのステップ5-7に従います。
3. インテグレーションアクセストークンを使用して認証するのすべてのステップに従います。

### データエクスポートの定義を続ける

![](/assets/image-20200825-081511.f27fefe9bfce3cb406e60f8e53aaa9f64e0991c5791114dda8557aa8c2cfc32c.989f2923.png)

1. エクスポートのパラメータを定義します:


| **フィールド** | **必須/任意** | **説明** |
|  --- | --- | --- |
| **Post API Endpoint** | 必須 | エクスポートされたデータのコレクションを消費するbulk POST APIのエンドポイント |
| **Number of Rows per Batch** | 任意 | API投稿あたりの最大レコード数。デフォルト: 1000 |
| **JSON Columns** | 任意 | JSONとして送信する文字列カラムのカンマ区切りリスト |
| **Ignore Invalid Records** | 任意 | 有効にすると、無効なJSON形式のためにアップロードに失敗したレコードがある場合でもジョブを続行します |
| **Connect Timeout in Seconds** | 任意 | 接続操作を中止するまでの待機時間(秒)。デフォルト: 300(5分に相当)。最大: 1800 |
| **Read Timeout in Seconds** | 任意 | 読み取り操作を中止するまでの待機時間(秒)。デフォルト: 300(5分に相当)。最大: 1800 |
| **Write Timeout in Seconds** | 任意 | 書き込み操作を中止するまでの待機時間(秒)。デフォルト: 300(5分に相当)。最大: 1800 |
| **Retry Limit** | 任意 | システムが諦めるまでの再試行回数。デフォルト: 7。最大: 10 |
| **Initial retry time wait in milliseconds** | 任意 | 1回目と2回目の試行の間の時間(ミリ秒)。デフォルト: 500(0.5秒に相当)。最大: 900000 |
| **Max retry wait in milliseconds** | 任意 | 2回目以降のすべての試行の間の時間(ミリ秒)。デフォルト: 300000(5分に相当)。最大: 900000 |


### (オプション) Query Export ジョブをスケジュールする

Scheduled Jobs と Result Export を使用して、指定したターゲット宛先に出力結果を定期的に書き込むことができます。

Treasure Data のスケジューラー機能は、高可用性を実現するために定期的なクエリ実行をサポートしています。

2 つの仕様が競合するスケジュール仕様を提供する場合、より頻繁に実行するよう要求する仕様が優先され、もう一方のスケジュール仕様は無視されます。

例えば、cron スケジュールが `'0 0 1 * 1'` の場合、「月の日」の仕様と「週の曜日」が矛盾します。前者の仕様は毎月 1 日の午前 0 時 (00:00) に実行することを要求し、後者の仕様は毎週月曜日の午前 0 時 (00:00) に実行することを要求するためです。後者の仕様が優先されます。

#### Treasure コンソール を使用してジョブをスケジュールする

1. **Data Workbench > Queries** に移動します
2. 新しいクエリを作成するか、既存のクエリを選択します。
3. **Schedule** の横にある None を選択します。
![](/assets/image2021-1-15_17-28-51.f1b242f6ecc7666a0097fdf37edd1682786ec11ef80eff68c66f091bc405c371.0f87d8d4.png)
4. ドロップダウンで、次のスケジュールオプションのいずれかを選択します:
![](/assets/image2021-1-15_17-29-47.45289a1c99256f125f4d887e501e204ed61f02223fde0927af5f425a89ace0c0.0f87d8d4.png)
| ドロップダウン値 | 説明 |
|  --- | --- |
| Custom cron... | [Custom cron... の詳細](#custom-cron-details)を参照してください。 |
| @daily (midnight) | 指定されたタイムゾーンで 1 日 1 回午前 0 時 (00:00 am) に実行します。 |
| @hourly (:00) | 毎時 00 分に実行します。 |
| None | スケジュールなし。 |


#### Custom cron... の詳細

![](/assets/image2021-1-15_17-30-23.0f94a8aa5f75ea03e3fec0c25b0640cd59ee48d1804a83701e5f2372deae466c.0f87d8d4.png)

| **Cron 値** | **説明** |
|  --- | --- |
| `0 * * * *` | 1 時間に 1 回実行します。 |
| `0 0 * * *` | 1 日 1 回午前 0 時に実行します。 |
| `0 0 1 * *` | 毎月 1 日の午前 0 時に 1 回実行します。 |
| "" | スケジュールされた実行時刻のないジョブを作成します。 |



```
 *    *    *    *    *
 -    -    -    -    -
 |    |    |    |    |
 |    |    |    |    +----- day of week (0 - 6) (Sunday=0)
 |    |    |    +---------- month (1 - 12)
 |    |    +--------------- day of month (1 - 31)
 |    +-------------------- hour (0 - 23)
 +------------------------- min (0 - 59)
```

次の名前付きエントリを使用できます:

- Day of Week: sun, mon, tue, wed, thu, fri, sat.
- Month: jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec.


各フィールド間には単一のスペースが必要です。各フィールドの値は、次のもので構成できます:

div
| フィールド値  | 例  | 例の説明  |
|  --- | --- | --- |
| 各フィールドに対して上記で表示された制限内の単一の値。 |  |  |
| フィールドに基づく制限がないことを示すワイルドカード
`'*'`。 | `'0 0 1 * *'` | 毎月 1 日の午前 0 時 (00:00) に実行するようにスケジュールを設定します。 |
| 範囲 `'2-5'`
フィールドの許可される値の範囲を示します。 | `'0 0 1-10 * *'` | 毎月 1 日から 10 日までの午前 0 時 (00:00) に実行するようにスケジュールを設定します。 |
| カンマ区切りの値のリスト `'2,3,4,5'`
フィールドの許可される値のリストを示します。 | `0 0 1,11,21 * *'` | 毎月 1 日、11 日、21 日の午前 0 時 (00:00) に実行するようにスケジュールを設定します。 |
| 周期性インジケータ `'*/5'`
フィールドの有効な値の範囲に基づいて、
スケジュールが実行を許可される頻度を表現します。 | `'30 */2 1 * *'` | 毎月 1 日、00:30 から 2 時間ごとに実行するようにスケジュールを設定します。
`'0 0 */5 * *'` は、毎月 5 日から 5 日ごとに午前 0 時 (00:00) に実行するようにスケジュールを設定します。 |
| `'*'`
ワイルドカードを除く上記の
いずれかのカンマ区切りリストもサポートされています
`'2,*/5,8-10'` | `'0 0 5,*/10,25 * *'` | 毎月 5 日、10 日、20 日、25 日の午前 0 時 (00:00) に実行するようにスケジュールを設定します。 |


1. (オプション) Delay execution を有効にすることで、クエリの開始時刻を遅延させることができます。


### クエリを実行する

クエリに名前を付けて保存して実行するか、単にクエリを実行します。クエリが正常に完了すると、クエリ結果は指定された宛先に自動的にエクスポートされます。

設定エラーにより継続的に失敗するスケジュールジョブは、複数回通知された後、システム側で無効化される場合があります。

(オプション) Delay execution を有効にすることで、クエリの開始時刻を遅延させることができます。

## Audience Studio で Segment をアクティベートする

Audience Studio で activation を作成することで、segment データをターゲットプラットフォームに送信することもできます。

1. **Audience Studio** に移動します。
2. parent segment を選択します。
3. ターゲット segment を開き、右クリックして、**Create Activation** を選択します。
4. **Details** パネルで、Activation 名を入力し、前述の Configuration Parameters のセクションに従って activation を設定します。
5. **Output Mapping** パネルで activation 出力をカスタマイズします。


![](/assets/ouput.b2c7f1d909c4f98ed10f5300df858a4b19f71a3b0834df952f5fb24018a5ea78.8ebdf569.png)

- Attribute Columns
  - **Export All Columns** を選択すると、変更を加えずにすべての列をエクスポートできます。
  - **+ Add Columns** を選択して、エクスポート用の特定の列を追加します。Output Column Name には、Source 列名と同じ名前があらかじめ入力されます。Output Column Name を更新できます。**+ Add Columns** を選択し続けて、activation 出力用の新しい列を追加します。
- String Builder
  - **+ Add string** を選択して、エクスポート用の文字列を作成します。次の値から選択します:
    - String: 任意の値を選択します。テキストを使用してカスタム値を作成します。
    - Timestamp: エクスポートの日時。
    - Segment Id: segment ID 番号。
    - Segment Name: segment 名。
    - Audience Id: parent segment 番号。


1. **Schedule** を設定します。


![](/assets/snippet-output-connector-on-audience-studio-2024-08-28.a99525173709da1eb537f839019fa7876ffae95045154c8f2941b030022f792c.8ebdf569.png)

- スケジュールを定義する値を選択し、オプションでメール通知を含めます。


1. **Create** を選択します。


batch journey の activation を作成する必要がある場合は、[Creating a Batch Journey Activation](/products/customer-data-platform/journey-orchestration/batch/creating-a-batch-journey-activation) を参照してください。

## Workflowでエクスポート結果を設定する(オプション)

Treasure ワークフロー内で、このデータコネクタを使用してデータをエクスポートするように指定できます。


```yaml
timezone: UTC

_export:
  td:
    database: sample_datasets

+td-result-into-target:
  td>: queries/sample.sql
  result_connection: your_connections_name
  result_settings:
    base_url: http://base_url.com/rest
    api_endpoint: /all/async/bulk/V1/customers
    username: admin
    password: **xyz***
    #auth_method: token
    #token: **xyz***
    json_columns: customer
    ignore_invalid_records: true
    retry_count: 7
    retry_initial_wait_millis: 500
    max_retry_wait_millis: 300000
    request_connect_timeout: 300
    request_read_timeout: 300
    request_write_timeout: 300
```