> ## 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のI/O操作

> DataStoreでのデータの読み書き - 対応するすべてのフォーマットと宛先

DataStoreは、さまざまなファイルフォーマットやデータソースの読み込みと書き出しに対応しています。

<div id="reading">
  ## データの読み込み
</div>

<div id="read-csv">
  ### CSVファイル
</div>

```python theme={null}
read_csv(filepath_or_buffer, sep=',', header='infer', names=None, 
         usecols=None, dtype=None, nrows=None, skiprows=None,
         compression=None, encoding=None, **kwargs)
```

**例:**

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

# Basic CSV read
ds = pd.read_csv("data.csv")

# With options
ds = pd.read_csv(
    "data.csv",
    sep=";",                    # Custom delimiter
    header=0,                   # Header row index
    names=['a', 'b', 'c'],      # Custom column names
    usecols=['a', 'b'],         # Only read specific columns
    dtype={'a': 'Int64'},       # Specify dtypes
    nrows=1000,                 # Read only first 1000 rows
    skiprows=1,                 # Skip first row
    compression='gzip',         # Compressed file
    encoding='utf-8'            # Encoding
)

# From URL
ds = pd.read_csv("https://example.com/data.csv")
```

<div id="read-parquet">
  ### Parquet ファイル
</div>

大規模なデータセットに適しており、圧縮効率に優れた列指向フォーマットです。

```python theme={null}
read_parquet(path, columns=None, **kwargs)
```

**例:**

```python theme={null}
# Basic Parquet read
ds = pd.read_parquet("data.parquet")

# Read specific columns only (efficient - only reads needed data)
ds = pd.read_parquet("data.parquet", columns=['col1', 'col2', 'col3'])

# From S3
ds = pd.read_parquet("s3://bucket/data.parquet")
```

<div id="read-json">
  ### JSONファイル
</div>

```python theme={null}
read_json(path_or_buf, orient=None, lines=False, **kwargs)
```

**例:**

```python theme={null}
# Standard JSON
ds = pd.read_json("data.json")

# JSON Lines (newline-delimited)
ds = pd.read_json("data.jsonl", lines=True)

# JSON with specific orientation
ds = pd.read_json("data.json", orient='records')
```

<div id="read-excel">
  ### Excelファイル
</div>

```python theme={null}
read_excel(io, sheet_name=0, header=0, names=None, **kwargs)
```

**例:**

```python theme={null}
# Read first sheet
ds = pd.read_excel("data.xlsx")

# Read specific sheet
ds = pd.read_excel("data.xlsx", sheet_name="Sheet1")
ds = pd.read_excel("data.xlsx", sheet_name=2)  # Third sheet

# Read multiple sheets (returns dict)
sheets = pd.read_excel("data.xlsx", sheet_name=['Sheet1', 'Sheet2'])
```

<div id="read-sql">
  ### SQL データベース
</div>

```python theme={null}
read_sql(sql, con, **kwargs)
```

**例:**

```python theme={null}
# Read from SQL query
ds = pd.read_sql("SELECT * FROM users", connection)
ds = pd.read_sql("SELECT * FROM orders WHERE date > '2024-01-01'", connection)
```

<div id="read-other">
  ### その他のフォーマット
</div>

```python theme={null}
# Feather (Arrow)
ds = pd.read_feather("data.feather")

# ORC
ds = pd.read_orc("data.orc")

# Pickle
ds = pd.read_pickle("data.pkl")

# Fixed-width formatted
ds = pd.read_fwf("data.txt", widths=[10, 20, 15])

# HTML tables
ds = pd.read_html("https://example.com/table.html")[0]
```

***

<div id="writing">
  ## データの書き込み
</div>

<div id="to-csv">
  ### to\_csv
</div>

CSVフォーマットでエクスポートします。

```python theme={null}
to_csv(path_or_buf=None, sep=',', na_rep='', header=True, 
       index=True, mode='w', compression=None, **kwargs)
```

**例:**

```python theme={null}
ds = pd.read_parquet("data.parquet")

# Basic export
ds.to_csv("output.csv")

# With options
ds.to_csv(
    "output.csv",
    sep=";",                    # Custom delimiter
    index=False,                # Don't include index
    header=True,                # Include header
    na_rep='NULL',              # Represent NaN as 'NULL'
    compression='gzip'          # Compress output
)

# To string
csv_string = ds.to_csv()
```

<div id="to-parquet">
  ### to\_parquet
</div>

Parquetフォーマットにエクスポートします (大量のデータに推奨) 。

```python theme={null}
to_parquet(path, engine='pyarrow', compression='snappy', **kwargs)
```

**例:**

```python theme={null}
# Basic export
ds.to_parquet("output.parquet")

# With compression options
ds.to_parquet("output.parquet", compression='gzip')
ds.to_parquet("output.parquet", compression='zstd')

# Partitioned output
ds.to_parquet(
    "output/",
    partition_cols=['year', 'month']
)
```

<div id="to-json">
  ### to\_json
</div>

JSONフォーマットでエクスポートします。

```python theme={null}
to_json(path_or_buf=None, orient='records', lines=False, **kwargs)
```

**例:**

```python theme={null}
# Standard JSON (array of records)
ds.to_json("output.json", orient='records')

# JSON Lines (one JSON object per line)
ds.to_json("output.jsonl", lines=True)

# Different orientations
ds.to_json("output.json", orient='split')    # {columns, data, index}
ds.to_json("output.json", orient='records')  # [{col: val}, ...]
ds.to_json("output.json", orient='columns')  # {col: {idx: val}}

# To string
json_string = ds.to_json()
```

<div id="to-excel">
  ### to\_excel
</div>

Excelフォーマットにエクスポートします。

```python theme={null}
to_excel(excel_writer, sheet_name='Sheet1', index=True, **kwargs)
```

**例:**

```python theme={null}
# Single sheet
ds.to_excel("output.xlsx")
ds.to_excel("output.xlsx", sheet_name="Data", index=False)

# Multiple sheets
with pd.ExcelWriter("output.xlsx") as writer:
    ds1.to_excel(writer, sheet_name="Sales")
    ds2.to_excel(writer, sheet_name="Inventory")
```

<div id="to-sql-method">
  ### to\_sql
</div>

SQLデータベースへエクスポートするか、SQL文字列を生成します。

```python theme={null}
to_sql(name=None, con=None, schema=None, if_exists='fail', **kwargs)
```

**例:**

```python theme={null}
# Generate SQL query (no execution)
sql = ds.to_sql()
print(sql)
# SELECT ...
# FROM ...
# WHERE ...

# Write to database
ds.to_sql("table_name", connection, if_exists='replace')
```

<div id="to-other">
  ### その他のエクスポート方法
</div>

```python theme={null}
# To pandas DataFrame
df = ds.to_df()
df = ds.to_pandas()

# To Arrow Table
table = ds.to_arrow()

# To NumPy array
arr = ds.to_numpy()

# To dictionary
d = ds.to_dict()
d = ds.to_dict(orient='records')  # List of dicts
d = ds.to_dict(orient='list')     # Dict of lists

# To records (list of tuples)
records = ds.to_records()

# To string
s = ds.to_string()
s = ds.to_string(max_rows=100)

# To Markdown
md = ds.to_markdown()

# To HTML
html = ds.to_html()

# To LaTeX
latex = ds.to_latex()

# To clipboard
ds.to_clipboard()

# To pickle
ds.to_pickle("output.pkl")

# To feather
ds.to_feather("output.feather")
```

***

<div id="format-comparison">
  ## ファイルフォーマットの比較
</div>

| フォーマット      | 読み取り速度 | 書き込み速度 | ファイルサイズ | スキーマ | 最適な用途          |
| ----------- | ------ | ------ | ------- | ---- | -------------- |
| **Parquet** | 高速     | 高速     | 小       | あり   | 大規模データセット、分析用途 |
| **CSV**     | 中程度    | 高速     | 大       | なし   | 互換性、シンプルなデータ   |
| **JSON**    | 低速     | 中程度    | 大       | 一部   | API、ネストされたデータ  |
| **Excel**   | 低速     | 低速     | 中程度     | 一部   | 非技術系ユーザーとの共有   |
| **Feather** | 非常に高速  | 非常に高速  | 中程度     | あり   | プロセス間連携、pandas |

<div id="recommendations">
  ### 推奨事項
</div>

1. **分析ワークロード向け:** Parquet を使用
   * 列指向フォーマットのため、必要なカラムだけを読み取れます
   * 高い圧縮率
   * データ型を保持できます

2. **データ交換向け:** CSV または JSON を使用
   * 幅広い互換性
   * 人間が読める形式

3. **pandas との相互運用向け:** Feather または Arrow を使用
   * 最速のシリアライゼーション
   * 型を保持できます

***

<div id="compression">
  ## 圧縮対応
</div>

<div id="read-compressed">
  ### 圧縮ファイルの読み込み
</div>

```python theme={null}
# Auto-detect from extension
ds = pd.read_csv("data.csv.gz")
ds = pd.read_csv("data.csv.bz2")
ds = pd.read_csv("data.csv.xz")
ds = pd.read_csv("data.csv.zst")

# Explicit compression
ds = pd.read_csv("data.csv", compression='gzip')
```

<div id="write-compressed">
  ### 圧縮ファイルへの書き込み
</div>

```python theme={null}
# CSV with compression
ds.to_csv("output.csv.gz", compression='gzip')
ds.to_csv("output.csv.bz2", compression='bz2')

# Parquet (always compressed)
ds.to_parquet("output.parquet", compression='snappy')  # Default
ds.to_parquet("output.parquet", compression='gzip')
ds.to_parquet("output.parquet", compression='zstd')    # Best ratio
ds.to_parquet("output.parquet", compression='lz4')     # Fastest
```

<div id="compression-options">
  ### 圧縮オプション
</div>

| 圧縮方式     | 速度    | 圧縮率   | 用途             |
| -------- | ----- | ----- | -------------- |
| `snappy` | 非常に高速 | 低     | Parquet のデフォルト |
| `lz4`    | 非常に高速 | 低     | 速度優先           |
| `gzip`   | 中程度   | 高     | 互換性重視          |
| `zstd`   | 高速    | 非常に高い | バランス重視         |
| `bz2`    | 低速    | 非常に高い | 最大圧縮率重視        |

***

<div id="streaming">
  ## ストリーミング I/O
</div>

メモリに収まりきらない非常に大きなファイルの場合:

<div id="chunked-read">
  ### chunk単位での読み取り
</div>

```python theme={null}
# Read in chunks
for chunk in pd.read_csv("large.csv", chunksize=100000):
    # Process each chunk
    process(chunk)

# Using iterator
reader = pd.read_csv("large.csv", iterator=True)
chunk = reader.get_chunk(10000)
```

<div id="clickhouse-streaming">
  ### ClickHouse Streaming の利用
</div>

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

# Stream from file without loading all into memory
ds = DataStore.from_file("huge.parquet")

# Operations are lazy - only computes what's needed
result = ds.filter(ds['amount'] > 1000).head(100)
```

***

<div id="remote">
  ## リモートデータソース
</div>

<div id="http">
  ### HTTP/HTTPS
</div>

```python theme={null}
# Read from URL
ds = pd.read_csv("https://example.com/data.csv")
ds = pd.read_parquet("https://example.com/data.parquet")
```

<div id="s3">
  ### S3
</div>

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

# Anonymous access
ds = DataStore.uri("s3://bucket/data.parquet?nosign=true")

# With credentials
ds = DataStore.from_s3(
    "s3://bucket/data.parquet",
    access_key_id="KEY",
    secret_access_key="SECRET"
)
```

<div id="cloud">
  ### GCS、Azure、HDFS
</div>

クラウドストレージのオプションについては、[Factory Methods](/docs/ja/chdb/datastore/factory-methods)を参照してください。

***

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

<div id="use-parquet-for-large-files">
  ### 1. 大容量ファイルにはParquetを使用する
</div>

```python theme={null}
# Convert CSV to Parquet for better performance
ds = pd.read_csv("large.csv")
ds.to_parquet("large.parquet")

# Future reads are much faster
ds = pd.read_parquet("large.parquet")
```

<div id="select-only-needed-columns">
  ### 2. 必要なカラムのみを選択する
</div>

```python theme={null}
# Efficient - only reads col1 and col2
ds = pd.read_parquet("data.parquet", columns=['col1', 'col2'])

# Inefficient - reads all columns then filters
ds = pd.read_parquet("data.parquet")[['col1', 'col2']]
```

<div id="use-compression">
  ### 3. 圧縮を利用する
</div>

```python theme={null}
# Smaller file size, usually faster due to less I/O
ds.to_parquet("output.parquet", compression='zstd')
```

<div id="batch-writes">
  ### 4. バッチ書き込み
</div>

```python theme={null}
# Write once, not in a loop
result = process_all_data(ds)
result.to_parquet("output.parquet")

# NOT this (inefficient)
for chunk in chunks:
    chunk.to_parquet(f"output_{i}.parquet")
```
