> ## Documentation Index
> Fetch the complete documentation index at: https://clickhouse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# 実行エンジンの設定

> DataStore の実行エンジンを設定する - auto、chdb、または pandas

DataStore では、異なるバックエンドを使用して操作を実行できます。このガイドでは、実行エンジンの選択を設定して最適化する方法を説明します。

<div id="engines">
  ## 利用可能なエンジン
</div>

| エンジン     | 説明                            | 最適な用途               |
| -------- | ----------------------------- | ------------------- |
| `auto`   | 操作ごとに最適なエンジンを自動的に選択します        | 一般的な用途 (デフォルト)      |
| `chdb`   | すべての操作を ClickHouse SQL で実行します | 大規模なデータセット、集計       |
| `pandas` | すべての操作を pandas で実行します         | 互換性テスト、pandas 固有の機能 |

<div id="setting">
  ## エンジンの設定
</div>

<div id="global">
  ### グローバル設定
</div>

```python theme={null}
from chdb.datastore.config import config

# Option 1: Using set method
config.set_execution_engine('auto')    # Default
config.set_execution_engine('chdb')    # Force ClickHouse
config.set_execution_engine('pandas')  # Force pandas

# Option 2: Using shortcuts
config.use_auto()     # Auto-select
config.use_chdb()     # Force ClickHouse
config.use_pandas()   # Force pandas
```

<div id="checking">
  ### 現在のエンジンを確認する
</div>

```python theme={null}
print(config.execution_engine)  # 'auto', 'chdb', or 'pandas'
```

***

<div id="auto-mode">
  ## 自動モード
</div>

`auto` モード (デフォルト) では、DataStore が各操作に応じて最適なエンジンを選択します。

<div id="auto-chdb">
  ### chDB で実行される操作
</div>

* SQL 互換のフィルタリング (`filter()`, `where()`)
* カラムの選択 (`select()`)
* ソート (`sort()`, `orderby()`)
* グループ化と集約 (`groupby().agg()`)
* 結合 (`join()`, `merge()`)
* 重複の排除 (`distinct()`, `drop_duplicates()`)
* 件数の制限 (`limit()`, `head()`, `tail()`)

<div id="auto-pandas">
  ### pandas で実行される操作
</div>

* カスタムの apply 関数 (`apply(custom_func)`)
* カスタム集計を含む複雑なピボットテーブル
* SQL では表現できない操作
* 入力がすでに pandas の DataFrame である場合

<div id="auto-example">
  ### 例
</div>

```python theme={null}
from chdb import datastore as pd
from chdb.datastore.config import config

config.use_auto()  # Default

ds = pd.read_csv("data.csv")

# This uses chDB (SQL)
result = (ds
    .filter(ds['amount'] > 100)   # SQL: WHERE
    .groupby('region')            # SQL: GROUP BY
    .agg({'amount': 'sum'})       # SQL: SUM()
)

# This uses pandas (custom function)
result = ds.apply(lambda row: complex_calculation(row), axis=1)
```

***

<div id="chdb-mode">
  ## chDB モード
</div>

すべての操作を ClickHouse SQL 経由で実行するよう強制します：

```python theme={null}
config.use_chdb()
```

<div id="chdb-when">
  ### 使用すべき場合
</div>

* 大規模なデータセット (数百万行) の処理
* 高負荷な集約ワークロード
* SQL 最適化を最大限に活用したい場合
* すべての操作で一貫した動作が求められる場合

<div id="chdb-performance">
  ### パフォーマンス特性
</div>

| 操作の種類      | パフォーマンス            |
| ---------- | ------------------ |
| GroupBy/集約 | 非常に高い (最大20倍高速)    |
| 複雑なフィルタリング | 非常に高い              |
| ソート        | とても良好              |
| 単純な単一フィルター | 良好 (わずかなオーバーヘッドあり) |

<div id="chdb-limitations">
  ### 制限事項
</div>

* カスタムのPython関数はサポートされない場合があります
* pandas固有の一部機能では変換が必要です

***

<div id="pandas-mode">
  ## pandas モード
</div>

すべての操作を pandas 経由で実行します:

```python theme={null}
config.use_pandas()
```

<div id="pandas-when">
  ### 使用するケース
</div>

* pandas との互換性テスト
* pandas 固有の機能を使う場合
* pandas 関連の問題をデバッグする場合
* データがすでに pandas 形式である場合

<div id="chdb-performance">
  ### パフォーマンス特性
</div>

| 操作タイプ      | パフォーマンス   |
| ---------- | --------- |
| 単純な単一操作    | 良好        |
| カスタム関数     | 優秀        |
| 複雑な集計      | chDB より低速 |
| 大規模なデータセット | メモリ消費が大きい |

***

<div id="cross-datastore">
  ## Cross-DataStore エンジン
</div>

異なるDataStore間でカラムを組み合わせる操作用に、エンジンを設定します：

```python theme={null}
# Set cross-DataStore engine
config.set_cross_datastore_engine('auto')
config.set_cross_datastore_engine('chdb')
config.set_cross_datastore_engine('pandas')
```

<div id="auto-example">
  ### 例
</div>

```python theme={null}
ds1 = pd.read_csv("sales.csv")
ds2 = pd.read_csv("inventory.csv")

# This operation involves two DataStores
result = ds1.join(ds2, on='product_id')
# Uses cross_datastore_engine setting
```

***

<div id="selection-logic">
  ## エンジンの選択ロジック
</div>

<div id="decision-tree">
  ### 自動モードの判定フロー
</div>

```text theme={null}
Operation requested
    │
    ├─ Can be expressed in SQL?
    │      │
    │      ├─ Yes → Use chDB
    │      │
    │      └─ No → Use pandas
    │
    └─ Cross-DataStore operation?
           │
           └─ Use cross_datastore_engine setting
```

<div id="function-override">
  ### 関数レベルのオーバーライド
</div>

一部の関数では、使用する engine を明示的に設定できます。

```python theme={null}
from chdb.datastore.config import function_config

# Force specific functions to use specific engine
function_config.use_chdb('length', 'substring')
function_config.use_pandas('upper', 'lower')
```

詳しくは、[Function Config](/docs/ja/chdb/configuration/function-config)を参照してください。

***

<div id="performance-comparison">
  ## パフォーマンス比較
</div>

1,000万行におけるベンチマーク結果:

| 操作               | pandas (ms) | chdb (ms) | 高速化率   |
| ---------------- | ----------- | --------- | ------ |
| GroupBy count    | 347         | 17        | 19.93x |
| 複合操作             | 1,535       | 234       | 6.56x  |
| 複雑なパイプライン        | 2,047       | 380       | 5.39x  |
| Filter+Sort+Head | 1,537       | 350       | 4.40x  |
| GroupBy agg      | 406         | 141       | 2.88x  |
| 単一フィルター          | 276         | 526       | 0.52x  |

**主なポイント:**

* chDB は集計や複雑なパイプラインで特に高い性能を発揮します
* pandas は単純な単一操作ではわずかに高速です
* 両方の長所を活かすには `auto` モードを使用してください

***

<div id="best-practices">
  ## ベストプラクティス
</div>

<div id="start-with-auto-mode">
  ### 1. まずは自動モードから
</div>

```python theme={null}
config.use_auto()  # Let DataStore decide
```

<div id="profile-before-forcing">
  ### 2. 強制する前にプロファイリングを行う
</div>

```python theme={null}
config.enable_profiling()
# Run your workload
# Check profiler report to see where time is spent
```

<div id="force-engine-for-specific-workloads">
  ### 3. 特定のワークロードで使用するエンジンを強制する
</div>

```python theme={null}
# For heavy aggregation workloads
config.use_chdb()

# For pandas compatibility testing
config.use_pandas()
```

<div id="use-explain-to-understand-execution">
  ### 4. explain() を使って実行内容を理解する
</div>

```python theme={null}
ds = pd.read_csv("data.csv")
query = ds.filter(ds['age'] > 25).groupby('city').agg({'salary': 'sum'})

# See what SQL will be generated
query.explain()
```

***

<div id="troubleshooting">
  ## トラブルシューティング
</div>

<div id="issue-operation-slower">
  ### 問題: 動作が想定より遅い
</div>

```python theme={null}
# Check current engine
print(config.execution_engine)

# Enable debug to see what's happening
config.enable_debug()

# Try forcing specific engine
config.use_chdb()  # or config.use_pandas()
```

<div id="issue-unsupported-operation">
  ### 問題: chdb モードではサポートされていない操作
</div>

```python theme={null}
# Some pandas operations aren't supported in SQL
# Solution: use auto mode
config.use_auto()

# Or explicitly convert to pandas first
df = ds.to_df()
result = df.some_pandas_specific_operation()
```

<div id="issue-memory-issues">
  ### 問題: 大量のデータによるメモリ不足
</div>

```python theme={null}
# Use chdb engine to avoid loading all data into memory
config.use_chdb()

# Filter early to reduce data size
result = ds.filter(ds['date'] >= '2024-01-01').to_df()

# For maximum throughput on large datasets, use performance mode
# which enables parallel Parquet reading and single-SQL aggregation
config.use_performance_mode()
```

<Tip>
  **パフォーマンスモード**

  大規模な集計ワークロードを実行していて、pandas の出力互換性 (行の順序、MultiIndex、dtype の補正) を厳密に保つ必要がない場合は、[パフォーマンスモード](/docs/ja/chdb/configuration/performance-mode) の使用を検討してください。これにより、エンジンは自動的に `chdb` に設定され、pandas 互換性に伴うオーバーヘッドがすべて取り除かれます。
</Tip>
