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

# DataStore クエリ構築

> DataStore で fluent な method chaining を使って SQL スタイルのクエリを構築

DataStore は、最適化された SQL クエリにコンパイルされる SQL スタイルのクエリ構築メソッドを提供します。すべての操作は、結果が必要になるまで遅延実行されます。

<div id="overview">
  ## クエリメソッドの概要
</div>

| メソッド               | 対応するSQL         | 説明              |
| ------------------ | --------------- | --------------- |
| `select(*cols)`    | `SELECT cols`   | カラムを選択          |
| `filter(cond)`     | `WHERE cond`    | 行をフィルタリング       |
| `where(cond)`      | `WHERE cond`    | `filter` の別名    |
| `sort(*cols)`      | `ORDER BY cols` | 行をソート           |
| `orderby(*cols)`   | `ORDER BY cols` | `sort` の別名      |
| `limit(n)`         | `LIMIT n`       | 行数を制限           |
| `offset(n)`        | `OFFSET n`      | 行をスキップ          |
| `distinct()`       | `DISTINCT`      | 重複を除去           |
| `groupby(*cols)`   | `GROUP BY cols` | 行をグループ化         |
| `having(cond)`     | `HAVING cond`   | グループをフィルタリング    |
| `join(right, ...)` | `JOIN`          | DataStore 同士を結合 |
| `union(other)`     | `UNION`         | 結果を統合           |

***

<div id="selection">
  ## 選択範囲
</div>

<div id="select">
  ### `select`
</div>

DataStore から特定のカラムを選択します。

```python theme={null}
select(*fields: Union[str, Expression]) -> DataStore
```

**例:**

```python theme={null}
from chdb.datastore import DataStore
from pathlib import Path
Path("employees.csv").write_text("""\
name,age,city,salary,department,dept_id,status,email,manager_id,bonus
Alice,28,NYC,75000,Engineering,1,active,alice@company.com,3,5000
Bob,35,LA,85000,Engineering,1,active,bob@company.com,3,
Charlie,52,NYC,95000,Product,2,active,charlie@company.com,,10000
Diana,32,SF,70000,Design,3,active,diana@company.com,3,3000
Eve,23,LA,48000,Product,2,inactive,eve@company.com,2,
""")

ds = DataStore.from_file("employees.csv")

# カラム名で選択
result = ds.select('name', 'age', 'salary')

# 全カラムを選択
result = ds.select('*')

# 式を使って選択
result = ds.select(
    'name',
    (ds['salary'] * 12).as_('annual_salary'),
    ds['age'].as_('employee_age')
)

# pandas スタイルの等価表現
result = ds[['name', 'age', 'salary']]
```

***

<div id="filtering">
  ## フィルタリング
</div>

<div id="filter">
  ### `filter` / `where`
</div>

条件に基づいて行を絞り込みます。どちらのメソッドも同等です。

```python theme={null}
filter(condition) -> DataStore
where(condition) -> DataStore  # 別名
```

**例:**

```python theme={null}
ds = DataStore.from_file("employees.csv")

# 単一条件
result = ds.filter(ds['age'] > 30)
result = ds.where(ds['salary'] >= 50000)

# 複数条件 (AND)
result = ds.filter((ds['age'] > 30) & (ds['department'] == 'Engineering'))

# 複数条件 (OR)
result = ds.filter((ds['city'] == 'NYC') | (ds['city'] == 'LA'))

# NOT条件
result = ds.filter(~(ds['status'] == 'inactive'))

# 文字列条件
result = ds.filter(ds['name'].str.contains('John'))
result = ds.filter(ds['email'].str.endswith('@company.com'))

# NULLチェック
result = ds.filter(ds['manager_id'].notnull())
result = ds.filter(ds['bonus'].isnull())

# IN条件
result = ds.filter(ds['department'].isin(['Engineering', 'Product', 'Design']))

# BETWEEN条件
result = ds.filter(ds['salary'].between(50000, 100000))

# フィルタリングの連結 (AND)
result = (ds
    .filter(ds['age'] > 25)
    .filter(ds['salary'] > 50000)
    .filter(ds['city'] == 'NYC')
)
```

<div id="pandas-filtering">
  ### Pandas スタイルのフィルタリング
</div>

```python theme={null}
# ブールインデックス（フィルタリングに相当）
result = ds[ds['age'] > 30]
result = ds[(ds['age'] > 30) & (ds['salary'] > 50000)]

# クエリメソッド
result = ds.query('age > 30 and salary > 50000')
```

***

<div id="sorting">
  ## ソート
</div>

<div id="sort">
  ### `sort` / `orderby`
</div>

1 つ以上のカラムを基準に行をソートします。

```python theme={null}
sort(*fields, ascending=True) -> DataStore
orderby(*fields, ascending=True) -> DataStore  # 別名
```

**例:**

```python theme={null}
ds = DataStore.from_file("employees.csv")

# 単一カラムの昇順
result = ds.sort('name')

# 単一カラムの降順
result = ds.sort('salary', ascending=False)

# 複数カラム
result = ds.sort('department', 'salary')

# 混合順序（ascendingパラメータにリストを使用）
result = ds.sort('department', 'salary', ascending=[True, False])

# Pandasスタイル
result = ds.sort_values('salary', ascending=False)
result = ds.sort_values(['department', 'salary'], ascending=[True, False])
```

***

<div id="limiting">
  ## 件数制限とページネーション
</div>

<div id="limit">
  ### `limit`
</div>

返される行数を制限します。

```python theme={null}
limit(n: int) -> DataStore
```

<div id="offset">
  ### `offset`
</div>

先頭の n 行をスキップします。

```python theme={null}
offset(n: int) -> DataStore
```

**例:**

```python theme={null}
ds = DataStore.from_file("employees.csv")

# 最初の10行
result = ds.limit(10)

# 最初の100行をスキップして次の50行を取得
result = ds.offset(100).limit(50)

# Pandasスタイル
result = ds.head(10)
result = ds.tail(10)
result = ds.iloc[100:150]
```

***

<div id="distinct">
  ## DISTINCT
</div>

<div id="distinct-method">
  ### `distinct`
</div>

重複した行を削除します。

```python theme={null}
distinct(subset=None, keep='first') -> DataStore
```

**例:**

```python theme={null}
from pathlib import Path
Path("events.csv").write_text("""\
user_id,event_type,timestamp
1,click,2024-01-15 10:30:00
2,view,2024-01-15 11:00:00
1,purchase,2024-01-15 11:30:00
3,click,2024-01-16 09:00:00
2,click,2024-01-16 10:00:00
""")

ds = DataStore.from_file("events.csv")

# 重複する行をすべて削除する
result = ds.distinct()

# 特定のカラムに基づいて重複を削除する
result = ds.distinct(subset=['user_id', 'event_type'])

# Pandas スタイル
result = ds.drop_duplicates()
result = ds.drop_duplicates(subset=['user_id'])
```

***

<div id="grouping">
  ## グループ化
</div>

<div id="groupby">
  ### `groupby`
</div>

1 つ以上のカラムで行をグループ化します。`LazyGroupBy` オブジェクトを返します。

```python theme={null}
groupby(*fields, sort=True, as_index=True, dropna=True) -> LazyGroupBy
```

**例:**

```python theme={null}
from pathlib import Path
Path("sales.csv").write_text("""\
region,product,category,amount,quantity,price,date,order_id
East,Widget,Electronics,5200,10,120,2024-01-15,1001
West,Gadget,Electronics,800,5,160,2024-02-20,1002
East,Gizmo,Home,6500,3,100,2024-03-10,1003
North,Widget,Electronics,4500,6,150,2024-06-18,1004
West,Gadget,Electronics,2000,8,250,2024-09-14,1005
""")

ds = DataStore.from_file("sales.csv")

# 単一カラムでグループ化
by_region = ds.groupby('region')

# 複数カラムでグループ化
by_region_product = ds.groupby('region', 'product')

# groupby後の集計
result = ds.groupby('region')['amount'].sum()
result = ds.groupby('region').agg({'amount': 'sum', 'quantity': 'mean'})

# 複数の集計
result = ds.groupby('category').agg({
    'price': ['min', 'max', 'mean'],
    'quantity': 'sum'
})

# 名前付き集計
result = ds.groupby('region').agg(
    total_amount=('amount', 'sum'),
    avg_quantity=('quantity', 'mean'),
    order_count=('order_id', 'count')
)
```

<div id="having">
  ### `having`
</div>

集計後にグループを絞り込みます。

```python theme={null}
having(condition: Union[Condition, str]) -> DataStore
```

**例:**

```python theme={null}
# total > 10000 のグループをフィルタリング
result = (ds
    .groupby('region')
    .agg({'amount': 'sum'})
    .having(ds['sum'] > 10000)
)

# SQLスタイルのhavingを使用
result = (ds
    .select('region', 'SUM(amount) as total')
    .groupby('region')
    .having('total > 10000')
)
```

***

<div id="joining">
  ## 結合
</div>

<div id="join">
  ### `join`
</div>

2つの DataStore を結合します。

```python theme={null}
join(right, on=None, how='inner', left_on=None, right_on=None) -> DataStore
```

**パラメータ:**

| Parameter  | Type      | Default    | Description                              |
| ---------- | --------- | ---------- | ---------------------------------------- |
| `right`    | DataStore | *required* | 結合対象の右側の DataStore                       |
| `on`       | str/list  | `None`     | 結合に使用するカラム                               |
| `how`      | str       | `'inner'`  | 結合の種類: 'inner', 'left', 'right', 'outer' |
| `left_on`  | str/list  | `None`     | 左側で結合に使用するカラム                            |
| `right_on` | str/list  | `None`     | 右側で結合に使用するカラム                            |

**例:**

```python theme={null}
from pathlib import Path
Path("departments.csv").write_text("""\
dept_id,department_name
1,Engineering
2,Product
3,Design
""")

employees = DataStore.from_file("employees.csv")
departments = DataStore.from_file("departments.csv")

# 単一カラムでの内部結合
result = employees.join(departments, on='dept_id')

# 左結合
result = employees.join(departments, on='dept_id', how='left')

# 異なるカラム名での結合
result = employees.join(
    departments,
    left_on='department_id',
    right_on='id',
    how='inner'
)

# Pandas スタイルのマージ
from chdb import datastore as pd
result = pd.merge(employees, departments, on='dept_id')
result = pd.merge(employees, departments, left_on='department_id', right_on='id')
```

<div id="union">
  ### `union`
</div>

2つのDataStoreの結果を結合します。

```python theme={null}
union(other, all=False) -> DataStore
```

**例:**

```python theme={null}
from pathlib import Path
Path("sales_2023.csv").write_text("""\
region,product,amount,date
East,Widget,1200,2023-06-15
West,Gadget,800,2023-09-20
North,Gizmo,600,2023-11-10
""")
Path("sales_2024.csv").write_text("""\
region,product,amount,date
East,Widget,1500,2024-03-10
North,Gizmo,900,2024-07-22
West,Gadget,1100,2024-05-05
""")

ds1 = DataStore.from_file("sales_2023.csv")
ds2 = DataStore.from_file("sales_2024.csv")

# UNION（重複を削除）
result = ds1.union(ds2)

# UNION ALL（重複を保持）
result = ds1.union(ds2, all=True)

# Pandas スタイル
from chdb import datastore as pd
result = pd.concat([ds1, ds2])
```

***

<div id="conditional">
  ## 条件式
</div>

<div id="when">
  ### `when`
</div>

CASE WHEN 式を作成します。

```python theme={null}
when(condition, value) -> CaseWhenBuilder
```

**例:**

```python theme={null}
ds = DataStore.from_file("employees.csv")

# シンプルなcase-when
result = ds.select(
    'name',
    ds.when(ds['salary'] > 100000, 'High')
      .when(ds['salary'] > 50000, 'Medium')
      .otherwise('Low')
      .as_('salary_tier')
)

# カラムへの代入
ds['salary_tier'] = (
    ds.when(ds['salary'] > 100000, 'High')
      .when(ds['salary'] > 50000, 'Medium')
      .otherwise('Low')
)
```

***

<div id="raw-sql">
  ## Raw SQL
</div>

<div id="run-sql">
  ### `run_sql` / `sql`
</div>

Raw SQLクエリを実行します。

```python theme={null}
run_sql(query: str) -> DataStore
sql(query: str) -> DataStore  # 別名
```

**例:**

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

# Raw SQLを実行する
result = DataStore().sql("""
    SELECT 
        department,
        COUNT(*) as count,
        AVG(salary) as avg_salary
    FROM file('employees.csv', 'CSVWithNames')
    WHERE status = 'active'
    GROUP BY department
    HAVING count > 5
    ORDER BY avg_salary DESC
    LIMIT 10
""")

# 既存のDataStoreに対してSQLを実行する
ds = DataStore.from_file("employees.csv")
result = ds.sql("SELECT * FROM __table__ WHERE age > 30")
```

<div id="to-sql">
  ### `to_sql`
</div>

実行せずに、生成された SQL を表示します。

```python theme={null}
to_sql(**kwargs) -> str
```

**例:**

```python theme={null}
ds = DataStore.from_file("employees.csv")

query = (ds
    .filter(ds['age'] > 30)
    .groupby('department')
    .agg({'salary': 'mean'})
    .sort('mean', ascending=False)
)

print(query.to_sql())
# 出力:
# SELECT department, AVG(salary) AS mean
# FROM file('employees.csv', 'CSVWithNames')
# WHERE age > 30
# GROUP BY department
# ORDER BY mean DESC
```

***

<div id="chaining">
  ## メソッドチェイニング
</div>

すべてのクエリメソッドで、メソッドチェイニングを利用できます:

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

ds = DataStore.from_file("sales.csv")

result = (ds
    .select('region', 'product', 'amount', 'date')
    .filter(ds['date'] >= '2024-01-01')
    .filter(ds['amount'] > 100)
    .groupby('region', 'product')
    .agg({
        'amount': ['sum', 'mean'],
        'date': 'count'
    })
    .having(ds['sum'] > 10000)
    .sort('sum', ascending=False)
    .limit(20)
)

# SQLを表示
print(result.to_sql())

# 実行
df = result.to_df()
```

***

<div id="aliasing">
  ## 別名
</div>

<div id="as">
  ### `as_`
</div>

カラムまたはサブクエリに別名を付けます。

```python theme={null}
as_(alias: str) -> DataStore
```

**例:**

```python theme={null}
# カラムの別名
result = ds.select(
    ds['name'].as_('employee_name'),
    (ds['salary'] * 12).as_('annual_salary')
)

# サブクエリの別名
subquery = ds.filter(ds['age'] > 30).as_('senior_employees')
```
