# Downsampling

El **downsampling** es una técnica crítica en entornos SCADA y sistemas industriales que manejan grandes volúmenes de datos en tiempo real.

## Fundamentos del Downsampling

**Downsampling** consiste en agregar datos de alta resolución temporal en ventanas definidas, almacenando solo los valores agregados en un nuevo bucket.

Sus beneficios clave son:

* **Reducción del 60-90% en uso de disco**.
* **Mejora de latencia en consultas históricas** (ej: de 5 segundos a 200ms).
* Eliminación de "ruido" en datos brutos para análisis más eficientes.

### Arquitectura de Downsampling en InfluxDB 2.x

| Componente                | Descripción                                    |
| ------------------------- | ---------------------------------------------- |
| **Bucket origen**         | Datos brutos con retención corta (ej: 30 días) |
| **Bucket destino**        | Datos downsampled con retención extendida      |
| **Task Flux**             | Script programado que ejecuta la agregación    |
| **Función de agregación** | `mean()`, `sum()`, `max()`, `median()`, etc.   |

## Implementación Paso a Paso

### 1. Creación de Buckets

{% code title="bash" overflow="wrap" %}

```bash
# Bucket para datos brutos (retención: 30d)
influx bucket create -n raw_industrial_data -r 30d

# Bucket para datos downsampled (retención: infinito)
influx bucket create -n mediciones_sensores_agg -r 0
```

{% endcode %}

### 2. Script Flux para Downsampling Diario

{% code title="text" overflow="wrap" %}

```
option task = {
  name: "media_temperatura_5m",
  every: 5m
}

data = from(bucket: "mediciones_sensores")
  |> range(start: -task.every)
  |> filter(fn: (r) => r._measurement == "ambiente" and r._field == "temperatura")

data
  |> aggregateWindow(
    every: 5m,
    fn: mean,
    createEmpty: false
  )
  |> to(bucket: "mediciones_sensores_agg")
```

{% endcode %}

**Parámetros clave**:

* `createEmpty`: Evita crear puntos sin datos en ventanas vacías

## Estrategias Avanzadas

### Downsampling en Cascada

{% code title="text" overflow="wrap" %}

```
  A[Datos brutos - 1s] --> B[Downsample 1m - 7d]
  B --> C[Downsample 1h - 30d]
  C --> D[Downsample 1d - Infinito]
```

{% endcode %}

**Beneficios**:

* Reduce progresivamente la granularidad
* Permite consultas rápidas en diferentes escalas temporales


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://darioaplicano.gitbook.io/influxdb2.x/sesion-4/guion-de-la-sesion/documentacion/consultas-avanzadas-y-optimizacion/downsampling.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
