> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-mintlify-fbfa8bee.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Unity Catalog

> このガイドでは、ClickHouse と Unity Catalog を使用して、S3バケット内のデータをクエリする手順を説明します。

export const galaxyOnClick = eventName => () => {
  try {
    if (typeof window !== "undefined" && window.galaxy && eventName) {
      window.galaxy.track(eventName, {
        interaction: "click"
      });
    }
  } catch (e) {}
};

export const BetaBadge = ({link, galaxyTrack, galaxyEvent}) => {
  if (link) {
    return <a href={link} target="_blank" rel="noopener noreferrer" className="betaBadge" onClick={galaxyTrack && galaxyEvent ? galaxyOnClick(galaxyEvent) : undefined}>
                <Icon />
                <span>ベータ</span>
            </a>;
  }
  return <div className="betaBadge">
            <Icon />
            <span>
                ベータ機能です。 
                <u>
                    <a href="/docs/beta-and-experimental-features#beta-features">
                        詳しくはこちら。
                    </a>
                </u>
            </span>
        </div>;
};

ClickHouse は、複数のカタログ (Unity、Glue、Polaris など) とのインテグレーションをサポートしています。このガイドでは、ClickHouse と [Unity Catalog](https://www.databricks.com/product/unity-catalog) を使用して、Databricks で管理されているデータをクエリする手順を説明します。

Databricks は、その lakehouse で複数のデータフォーマットをサポートしています。ClickHouse を使用すると、Unity Catalog のテーブルを Delta と Iceberg の両方の形式でクエリできます。

<Note>
  この機能は実験的であるため、以下を使用して有効にする必要があります。
  `SET allow_experimental_database_unity_catalog = 1;`
</Note>

<div id="configuring-unity-in-databricks">
  ## Databricks で Unity を設定する
</div>

ClickHouse が Unity Catalog と連携できるようにするには、外部リーダーによるアクセスを許可するよう Unity Catalog が設定されていることを確認する必要があります。これを行うには、[「Unity Catalog への外部データアクセスを有効にする」](https://docs.databricks.com/aws/en/external-access/admin)ガイドに従ってください。

カタログの設定が完了したら、ClickHouse 用の認証情報を生成する必要があります。Unity との連携方法に応じて、使用する方法は 2 つあります。

* Iceberg クライアントの場合は、[サービスプリンシパル](https://docs.databricks.com/aws/en/dev-tools/auth/oauth-m2m)として認証を使用します。

* Delta クライアントの場合は、Personal Access Token ([PAT](https://docs.databricks.com/aws/en/dev-tools/auth/pat)) を使用します。

<div id="required-pat-token-permissions">
  ### 必要な PAT トークンの権限
</div>

読み取りアクセスに PAT を使用する場合、トークンには ClickHouse が Unity Catalog のメタデータを一覧取得および読み取りできる権限が必要です。PAT には少なくとも、`EXTERNAL USE SCHEMA` の[権限](https://docs.databricks.com/aws/en/external-access/admin#grant-a-principal-unity-catalog-privileges)に加え、テーブルに対する `SELECT` 権限、親カタログに対する `USE CATALOG`、および親スキーマに対する `USE SCHEMA` が付与されていることを確認してください。

<div id="creating-a-connection-between-unity-catalog-and-clickhouse">
  ## Unity Catalog と ClickHouse 間の接続を作成する
</div>

Unity Catalog の設定と認証の準備が完了したら、ClickHouse と Unity Catalog 間の接続を確立します。

<div id="read-delta">
  ### Deltaを読み取る
</div>

```sql theme={null}
CREATE DATABASE unity
ENGINE = DataLakeCatalog('https://<workspace-id>.cloud.databricks.com/api/2.1/unity-catalog')
SETTINGS warehouse = 'CATALOG_NAME', catalog_credential = '<PAT>', catalog_type = 'unity'
```

<div id="read-iceberg">
  ### Iceberg を読み取る
</div>

管理対象の Iceberg テーブルにアクセスするには：

```sql theme={null}
CREATE DATABASE unity
ENGINE = DataLakeCatalog('https://<workspace-id>.cloud.databricks.com/api/2.1/unity-catalog/iceberg-rest')
SETTINGS catalog_type = 'rest', catalog_credential = '<client-id>:<client-secret>', warehouse = 'workspace', 
oauth_server_uri = 'https://<workspace-id>.cloud.databricks.com/oidc/v1/token', auth_scope = 'all-apis,sql'
```

<div id="querying-unity-catalog-tables-using-clickhouse">
  ## ClickHouse を使用して Unity Catalog のテーブルをクエリする
</div>

接続の準備ができたので、Unity Catalog 経由でクエリを実行できます。たとえば、次のようになります。

```sql theme={null}
USE unity;

SHOW TABLES;
```

```response theme={null}
┌─name───────────────────────────────────────────────┐
│ clickbench.delta_hits                              │
│ demo.fake_user                                     │
│ information_schema.catalog_privileges              │
│ information_schema.catalog_tags                    │
│ information_schema.catalogs                        │
│ information_schema.check_constraints               │
│ information_schema.column_masks                    │
│ information_schema.column_tags                     │
│ information_schema.columns                         │
│ information_schema.constraint_column_usage         │
│ information_schema.constraint_table_usage          │
│ information_schema.information_schema_catalog_name │
│ information_schema.key_column_usage                │
│ information_schema.parameters                      │
│ information_schema.referential_constraints         │
│ information_schema.routine_columns                 │
│ information_schema.routine_privileges              │
│ information_schema.routines                        │
│ information_schema.row_filters                     │
│ information_schema.schema_privileges               │
│ information_schema.schema_tags                     │
│ information_schema.schemata                        │
│ information_schema.table_constraints               │
│ information_schema.table_privileges                │
│ information_schema.table_tags                      │
│ information_schema.tables                          │
│ information_schema.views                           │
│ information_schema.volume_privileges               │
│ information_schema.volume_tags                     │
│ information_schema.volumes                         │
│ uniform.delta_hits                                 │
└────────────────────────────────────────────────────┘
```

```sql theme={null}
SHOW TABLES
```

```response theme={null}
┌─name───────────────┐
│ uniform.delta_hits │
└────────────────────┘
```

テーブルに対してクエリを実行するには:

```sql theme={null}
SELECT count(*) FROM `uniform.delta_hits`
```

<Info>
  **バッククォートが必要**

  ClickHouse は複数のネームスペースをサポートしていないため、バッククォートが必要です。
</Info>

テーブルの DDL を確認するには:

```sql theme={null}
SHOW CREATE TABLE `uniform.delta_hits`

CREATE TABLE unity_uniform.`uniform.delta_hits`
(
    `WatchID` Int64,
    `JavaEnable` Int32,
    `Title` String,
    `GoodEvent` Int32,
    `EventTime` DateTime64(6, 'UTC'),
    `EventDate` Date,
    `CounterID` Int32,
    `ClientIP` Int32,
    ...
    `FromTag` String,
    `HasGCLID` Int32,
    `RefererHash` Int64,
    `URLHash` Int64,
    `CLID` Int32
)
ENGINE = Iceberg('s3://<path>);

```

<div id="loading-data-from-your-data-lake-into-clickhouse">
  ## データレイクからClickHouseにデータを読み込む
</div>

DatabricksからClickHouseにデータを読み込む必要がある場合は、まずローカルのClickHouseテーブルを作成します。

```sql theme={null}
CREATE TABLE hits
(
    `WatchID` Int64,
    `JavaEnable` Int32,
    `Title` String,
    `GoodEvent` Int32,
    `EventTime` DateTime64(6, 'UTC'),
    `EventDate` Date,
    `CounterID` Int32,
    `ClientIP` Int32,
    ...
    `FromTag` String,
    `HasGCLID` Int32,
    `RefererHash` Int64,
    `URLHash` Int64,
    `CLID` Int32
)
PRIMARY KEY (CounterID, EventDate, UserID, EventTime, WatchID);
```

次に、`INSERT INTO SELECT` を使って Unity Catalog のテーブルからデータを読み込みます:

```sql theme={null}
INSERT INTO hits SELECT * FROM unity_uniform.`uniform.delta_hits`;
```
