> ## 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 I/O operations

> Reading and writing data with DataStore - all supported formats and destinations

DataStore supports reading from and writing to various file formats and data sources.

<h2 id="reading">
  Reading Data
</h2>

<h3 id="read-csv">
  CSV Files
</h3>

```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)
```

**Examples:**

```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")
```

<h3 id="read-parquet">
  Parquet Files
</h3>

Recommended for large datasets - columnar format with better compression.

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

**Examples:**

```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")
```

<h3 id="read-json">
  JSON Files
</h3>

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

**Examples:**

```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')
```

<h3 id="read-excel">
  Excel Files
</h3>

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

**Examples:**

```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'])
```

<h3 id="read-sql">
  SQL Databases
</h3>

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

**Examples:**

```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)
```

<h3 id="read-other">
  Other Formats
</h3>

```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]
```

***

<h2 id="writing">
  Writing Data
</h2>

<h3 id="to-csv">
  to\_csv
</h3>

Export to CSV format.

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

**Examples:**

```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()
```

<h3 id="to-parquet">
  to\_parquet
</h3>

Export to Parquet format (recommended for large data).

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

**Examples:**

```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']
)
```

<h3 id="to-json">
  to\_json
</h3>

Export to JSON format.

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

**Examples:**

```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()
```

<h3 id="to-excel">
  to\_excel
</h3>

Export to Excel format.

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

**Examples:**

```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")
```

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

Export to SQL database or generate SQL string.

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

**Examples:**

```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')
```

<h3 id="to-other">
  Other Export Methods
</h3>

```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")
```

***

<h2 id="format-comparison">
  File Format Comparison
</h2>

| Format      | Read Speed | Write Speed | File Size | Schema  | Best For                    |
| ----------- | ---------- | ----------- | --------- | ------- | --------------------------- |
| **Parquet** | Fast       | Fast        | Small     | Yes     | Large datasets, analytics   |
| **CSV**     | Medium     | Fast        | Large     | No      | Compatibility, simple data  |
| **JSON**    | Slow       | Medium      | Large     | Partial | APIs, nested data           |
| **Excel**   | Slow       | Slow        | Medium    | Partial | Sharing with non-tech users |
| **Feather** | Very Fast  | Very Fast   | Medium    | Yes     | Inter-process, pandas       |

<h3 id="recommendations">
  Recommendations
</h3>

1. **For analytics workloads:** Use Parquet
   * Columnar format allows reading only needed columns
   * Excellent compression
   * Preserves data types

2. **For data exchange:** Use CSV or JSON
   * Universal compatibility
   * Human-readable

3. **For pandas interop:** Use Feather or Arrow
   * Fastest serialization
   * Type preservation

***

<h2 id="compression">
  Compression Support
</h2>

<h3 id="read-compressed">
  Reading Compressed Files
</h3>

```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')
```

<h3 id="write-compressed">
  Writing Compressed Files
</h3>

```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
```

<h3 id="compression-options">
  Compression Options
</h3>

| Compression | Speed     | Ratio     | Use Case            |
| ----------- | --------- | --------- | ------------------- |
| `snappy`    | Very Fast | Low       | Default for Parquet |
| `lz4`       | Very Fast | Low       | Speed priority      |
| `gzip`      | Medium    | High      | Compatibility       |
| `zstd`      | Fast      | Very High | Best balance        |
| `bz2`       | Slow      | Very High | Maximum compression |

***

<h2 id="streaming">
  Streaming I/O
</h2>

For very large files that don't fit in memory:

<h3 id="chunked-read">
  Chunked Reading
</h3>

```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)
```

<h3 id="clickhouse-streaming">
  Using ClickHouse Streaming
</h3>

```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)
```

***

<h2 id="remote">
  Remote Data Sources
</h2>

<h3 id="http">
  HTTP/HTTPS
</h3>

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

<h3 id="s3">
  S3
</h3>

```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"
)
```

<h3 id="cloud">
  GCS, Azure, HDFS
</h3>

See [Factory Methods](/products/chdb/datastore/factory-methods) for cloud storage options.

***

<h2 id="best-practices">
  Best Practices
</h2>

<h3 id="use-parquet-for-large-files">
  1. Use Parquet for Large Files
</h3>

```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")
```

<h3 id="select-only-needed-columns">
  2. Select Only Needed Columns
</h3>

```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']]
```

<h3 id="use-compression">
  3. Use Compression
</h3>

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

<h3 id="batch-writes">
  4. Batch Writes
</h3>

```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")
```
