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

# Cómo consultar archivos Parquet

> Aprende a consultar archivos Parquet con chDB.

Gran parte de los datos del mundo está almacenada en buckets de Amazon S3.
En esta guía, aprenderemos a consultar esos datos con chDB.

<div id="setup">
  ## Configuración
</div>

Primero, creemos un entorno virtual:

```bash theme={null}
python -m venv .venv
source .venv/bin/activate
```

Ahora vamos a instalar chDB.
Asegúrate de tener la versión 2.0.2 o una posterior:

```bash theme={null}
pip install "chdb>=2.0.2"
```

Ahora vamos a instalar IPython:

```bash theme={null}
pip install ipython
```

Vamos a usar `ipython` para ejecutar los comandos del resto de la guía, que puedes iniciar con:

```bash theme={null}
ipython
```

También puedes usar el código en un script de Python o en tu notebook favorito.

<div id="exploring-parquet-metadata">
  ## Explorar los metadatos de Parquet
</div>

Vamos a explorar un archivo Parquet del conjunto de datos de [reseñas de Amazon](/docs/es/get-started/sample-datasets/amazon-reviews).
Pero antes, instalemos `chDB`:

```python theme={null}
import chdb
```

Al consultar archivos Parquet, podemos usar el formato de entrada [`ParquetMetadata`](/docs/es/reference/formats/Parquet/ParquetMetadata) para que devuelva los metadatos de Parquet en lugar del contenido del archivo.
Usemos la cláusula `DESCRIBE` para ver los campos que devuelve este formato:

```python theme={null}
query = """
DESCRIBE s3(
  'https://datasets-documentation.s3.eu-west-3.amazonaws.com/amazon_reviews/amazon_reviews_2015.snappy.parquet', 
  ParquetMetadata
)
SETTINGS describe_compact_output=1
"""

chdb.query(query, 'TabSeparated')
```

```text theme={null}
num_columns     UInt64
num_rows        UInt64
num_row_groups  UInt64
format_version  String
metadata_size   UInt64
total_uncompressed_size UInt64
total_compressed_size   UInt64
columns Array(Tuple(name String, path String, max_definition_level UInt64, max_repetition_level UInt64, physical_type String, logical_type String, compression String, total_uncompressed_size UInt64, total_compressed_size UInt64, space_saved String, encodings Array(String)))
row_groups      Array(Tuple(num_columns UInt64, num_rows UInt64, total_uncompressed_size UInt64, total_compressed_size UInt64, columns Array(Tuple(name String, path String, total_compressed_size UInt64, total_uncompressed_size UInt64, have_statistics Bool, statistics Tuple(num_values Nullable(UInt64), null_count Nullable(UInt64), distinct_count Nullable(UInt64), min Nullable(String), max Nullable(String))))))
```

Veamos ahora los metadatos de este archivo.
`columns` y `row_groups` contienen arrays de tuplas con muchas propiedades, así que por ahora los omitiremos.

```python theme={null}
query = """
SELECT * EXCEPT(columns, row_groups)
FROM s3(
  'https://datasets-documentation.s3.eu-west-3.amazonaws.com/amazon_reviews/amazon_reviews_2015.snappy.parquet', 
  ParquetMetadata
)
"""

chdb.query(query, 'Vertical')
```

```text theme={null}
Row 1:
──────
num_columns:             15
num_rows:                41905631
num_row_groups:          42
format_version:          2.6
metadata_size:           79730
total_uncompressed_size: 14615827169
total_compressed_size:   9272262304
```

A partir de esta salida, vemos que este archivo Parquet tiene más de 40 millones de filas, distribuidas en 42 grupos de filas, con 15 columnas de datos por fila.
Un grupo de filas es una partición horizontal lógica de los datos en filas.
Cada grupo de filas tiene metadatos asociados, y las herramientas de consulta pueden aprovechar esos metadatos para consultar el archivo de forma eficiente.

Veamos uno de los grupos de filas:

```python theme={null}
query = """
WITH rowGroups AS (
    SELECT rg
    FROM s3(
    'https://datasets-documentation.s3.eu-west-3.amazonaws.com/amazon_reviews/amazon_reviews_2015.snappy.parquet',
    ParquetMetadata
    )
    ARRAY JOIN row_groups AS rg
    LIMIT 1
)
SELECT tupleElement(c, 'name') AS name, tupleElement(c, 'total_compressed_size') AS total_compressed_size, 
       tupleElement(c, 'total_uncompressed_size') AS total_uncompressed_size,
       tupleElement(tupleElement(c, 'statistics'), 'min') AS min,
       tupleElement(tupleElement(c, 'statistics'), 'max') AS max
FROM rowGroups
ARRAY JOIN tupleElement(rg, 'columns') AS c
"""

chdb.query(query, 'DataFrame')
```

```text theme={null}
                 name  total_compressed_size  total_uncompressed_size                                                min                                                max
0         review_date                    493                      646                                              16455                                              16472
1         marketplace                     66                       64                                                 US                                                 US
2         customer_id                5207967                  7997207                                              10049                                           53096413
3           review_id               14748425                 17991290                                     R10004U8OQDOGE                                      RZZZUTBAV1RYI
4          product_id                8003456                 13969668                                         0000032050                                         BT00DDVMVQ
5      product_parent                5758251                  7974737                                                645                                          999999730
6       product_title               41068525                 63355320  ! Small S 1pc Black 1pc Navy (Blue) Replacemen...                            🌴 Vacation On The Beach
7    product_category                   1726                     1815                                            Apparel                                       Pet Products
8         star_rating                 369036                   374046                                                  1                                                  5
9       helpful_votes                 538940                  1022990                                                  0                                               3440
10        total_votes                 610902                  1080520                                                  0                                               3619
11               vine                  11426                   125999                                                  0                                                  1
12  verified_purchase                 102634                   125999                                                  0                                                  1
13    review_headline               16538189                 27634740                                                     🤹🏽‍♂️🎤Great product. Practice makes perfect. D...
14        review_body              145886383                232457911                                                                                              🚅 +🐧=💥 😀
```

<div id="querying-parquet-files">
  ## Consultar archivos Parquet
</div>

A continuación, consultemos el contenido del archivo.
Podemos hacerlo ajustando la consulta anterior para quitar `ParquetMetadata` y luego, por ejemplo, calcular el `star_rating` más frecuente entre todas las reseñas:

```python theme={null}
query = """
SELECT star_rating, count() AS count, formatReadableQuantity(count)
FROM s3(
  'https://datasets-documentation.s3.eu-west-3.amazonaws.com/amazon_reviews/amazon_reviews_2015.snappy.parquet'
)
GROUP BY ALL
ORDER BY star_rating
"""

chdb.query(query, 'DataFrame')
```

```text theme={null}
   star_rating     count formatReadableQuantity(count())
0            1   3253070                    3.25 million
1            2   1865322                    1.87 million
2            3   3130345                    3.13 million
3            4   6578230                    6.58 million
4            5  27078664                   27.08 million
```

Curiosamente, hay más reseñas de 5 estrellas que del resto de valoraciones juntas.
Parece que a la gente le gustan los productos de Amazon o, si no, simplemente no deja ninguna valoración.
