> ## 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.

# Operaciones de E/S de DataStore

> Lectura y escritura de datos con DataStore: todos los formatos y destinos compatibles

DataStore permite leer y escribir en varios formatos de archivo y fuentes de datos.

<div id="reading">
  ## Lectura de datos
</div>

<div id="read-csv">
  ### Archivos 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)
```

**Ejemplos:**

```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">
  ### Archivos Parquet
</div>

Recomendado para conjuntos de datos grandes: formato columnar con una mejor compresión.

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

**Ejemplos:**

```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">
  ### Archivos JSON
</div>

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

**Ejemplos:**

```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">
  ### Archivos Excel
</div>

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

**Ejemplos:**

```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">
  ### Bases de datos SQL
</div>

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

**Ejemplos:**

```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">
  ### Otros formatos
</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">
  ## Escribir datos
</div>

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

Exporta al formato CSV.

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

**Ejemplos:**

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

Exporta en formato Parquet (recomendado para grandes volúmenes de datos).

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

**Ejemplos:**

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

Exportar en formato JSON.

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

**Ejemplos:**

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

Exporta en formato Excel.

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

**Ejemplos:**

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

Exportar a una base de datos SQL o generar una sentencia SQL.

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

**Ejemplos:**

```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">
  ### Otros métodos de exportación
</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">
  ## Comparación de formatos de archivo
</div>

| Formato     | Velocidad de lectura | Velocidad de escritura | Tamaño de archivo | Esquema | Ideal para                            |
| ----------- | -------------------- | ---------------------- | ----------------- | ------- | ------------------------------------- |
| **Parquet** | Rápida               | Rápida                 | Pequeño           | Sí      | Conjuntos de datos grandes, analítica |
| **CSV**     | Media                | Rápida                 | Grande            | No      | Compatibilidad, datos simples         |
| **JSON**    | Lenta                | Media                  | Grande            | Parcial | APIs, datos anidados                  |
| **Excel**   | Lenta                | Lenta                  | Mediano           | Parcial | Compartir con usuarios no técnicos    |
| **Feather** | Muy rápida           | Muy rápida             | Mediano           | Sí      | Entre procesos, pandas                |

<div id="recommendations">
  ### Recomendaciones
</div>

1. **Para cargas de trabajo de analítica:** Use Parquet
   * El formato columnar permite leer solo las columnas necesarias
   * Excelente compresión
   * Conserva los tipos de datos

2. **Para el intercambio de datos:** Use CSV o JSON
   * Compatibilidad universal
   * Legible para humanos

3. **Para la interoperabilidad con pandas:** Use Feather o Arrow
   * Serialización más rápida
   * Conserva los tipos

***

<div id="compression">
  ## Compatibilidad con compresión
</div>

<div id="read-compressed">
  ### Lectura de archivos comprimidos
</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">
  ### Escribir archivos comprimidos
</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">
  ### Opciones de compresión
</div>

| Compresión | Velocidad  | Ratio    | Caso de uso                 |
| ---------- | ---------- | -------- | --------------------------- |
| `snappy`   | Muy rápida | Baja     | Predeterminada para Parquet |
| `lz4`      | Muy rápida | Baja     | Prioridad a la velocidad    |
| `gzip`     | Media      | Alta     | Compatibilidad              |
| `zstd`     | Rápida     | Muy alta | Mejor equilibrio            |
| `bz2`      | Lenta      | Muy alta | Compresión máxima           |

***

<div id="streaming">
  ## E/S en streaming
</div>

Para archivos muy grandes que no caben en memoria:

<div id="chunked-read">
  ### Lectura en fragmentos
</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">
  ### Cómo usar 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">
  ## Fuentes de datos remotas
</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>

Consulta [Métodos de fábrica](/docs/es/chdb/datastore/factory-methods) para conocer las opciones de almacenamiento en la nube.

***

<div id="best-practices">
  ## Buenas prácticas
</div>

<div id="use-parquet-for-large-files">
  ### 1. Usa Parquet para archivos grandes
</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. Seleccione solo las columnas necesarias
</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. Utilice compresión
</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. Inserciones por lotes
</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")
```
