> For the complete documentation index, see [llms.txt](https://docs.akenza.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.akenza.io/reference/api-documentation/querying-device-data/querying-aggregations.md).

# Querying aggregations

Aggregate device data with the REST API, from a single metric to multi-stage aggregations across devices and time.

The akenza REST API can aggregate device data across many devices and over long time ranges. To read single data points of one device instead, use the [raw samples API](https://docs.akenza.io/reference/api-documentation/querying-device-data/querying-raw-samples.md).

This page guides you through the concepts of the aggregation API:

* data products
  * *goal: understand WHAT you want to query and expected output format*
* endpoint selection and body structure
  * *goal: understand HOW you want to query*
* full Postman documentation
  * *goal: have a complete API reference parseable according to OpenAPI standard*

{% hint style="warning" %}
Do not use the REST API to pull all of your data on a schedule. If your application needs every data point, use an [output connector](https://docs.akenza.io/device-management/your-data-flow/connectors.md) instead. akenza then forwards data to your application as it arrives, for example through Kafka, Azure Event Hubs, AWS Kinesis, Google Cloud Pub/Sub or an SQL database.
{% endhint %}

{% hint style="info" %}
Since November 2026, the current version of the aggregation API is `/v4/query/`. If you still use `/v3/`, switch to `/v4/` with the [migration guide](https://docs.akenza.io/reference/api-documentation/querying-device-data/querying-aggregations/migrating-aggregations-v3-to-v4.md).
{% endhint %}

## Data product: single metric, time series and calendar grouping

The aggregation API returns three types of **output data products**:

* *Single metric*: one value
  * for example, the average temperature of 10 sensors over the last 7 days
* *Time series*: several values, each with a timestamp
  * for example, the maximum daily CO2 of one sensor from October 2026 to November 2026
* *Calendar grouping*: several values grouped into calendar buckets
  * for example, the average occupancy of 20 desk sensors, grouped by day of the week

akenza computes the output from one of two **source data products**. They set the granularity of the data used for the calculation.

* Hourly aggregates (time series)
  * ✅ fastest. You can query months or years of data.
  * ✅ supports the advanced analytics pipeline (concurrent occupancy, time in range, ...)
  * ❌ the time resolution is limited to one hour
* Raw samples (JSON)
  * ✅ no limit on time resolution. It depends only on the sensor.
  * ❌ slower. You can query at most 30 days of data.
  * ❌ does not support the advanced analytics pipeline (concurrent occupancy, time in range, ...)

<figure><img src="https://2165942204-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MMKXTFIN5ZlLOjBlfC4%2Fuploads%2Fgit-blob-349733e713b62847d5f1975affc8c21acd3df69e%2Fqueryservice-source-output-dataproducts.png?alt=media" alt="The query service reads raw samples or hourly aggregates and returns raw samples, a single metric, a time series or a calendar grouping"><figcaption><p>Source and output data products</p></figcaption></figure>

{% hint style="info" %}
akenza picks the source data product for you. The choice depends on the time range, the aggregation stages and the resolution of your query. To force a source data product, set `aggregation.sourceStage.sourceDataProduct`.
{% endhint %}

## Endpoint selection and body structure

In order to write your own query, you first need to choose the right endpoint. This depends on the data product (see above) and whether you want to aggregate data across devices or keep one result per device.

| Data product                                                      | Aggregated across devices                                                                                                                                        | One result per device                                                                                                                                                                        |
| ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| *Single metric*: one value                                        | <p><code>POST /v4/query/single-metrics</code><br>Example: the average temperature of 10 sensors over the last 7 days (one value)</p>                             | <p><code>POST /v4/query/single-metrics/by-device</code><br>Example: the average temperature of <strong>each of 10 sensors</strong> over the last 7 days (10 values, one for each sensor)</p> |
| *Time series*: several values, each with a timestamp              | <p><code>POST /v4/query/time-series</code><br>Example: the maximum daily CO2 across all sensors of a floor from October 2026 to November 2026 (1 timeseries)</p> | <p><code>POST /v4/query/time-series/by-device</code><br>Example: the maximum daily CO2 of <strong>each</strong> sensor from October 2026 to November 2026 (N timeseries, one for each)</p>   |
| *Calendar grouping*: several values grouped into calendar buckets | <p><code>POST /v4/query/calendar-grouping</code><br>Example: the average occupancy of 20 desk sensors, grouped by day of the week</p>                            | <p><code>POST /v4/query/calendar-grouping/by-device</code><br>Example: the average occupancy of <strong>each</strong> of 20 desk sensors, grouped by day of the week</p>                     |

Then you need to construct your request body accordingly.

A typical body could look like this (query daily average temperature of one sensor)

```json
{
  "match": {
    "devices": {
        "deviceIds": ["023ba5bdf738e64d"]
    },
    "timestamps": {
        "from": "2026-03-31T22:00:00.000Z",
        "to": "2026-04-07T21:59:59.000Z"
    },
    "dataPointSelector": {
        "dataKey": "temperature",
        "topic": "default"
    }
  },
  "aggregation": {
    "accumulator" : "AVG",
    "interval": "P1D"
  }
}
```

A default body has three section:

* `match` selects the data: which devices, which time range, and which `topic` and `dataKey`.
* `aggregation` describes how akenza aggregates the selected data
  * it can be in "easy" mode - one accumulator and one interval - as in the example above
  * OR it can be in expert mode and will have up to three stage (see [Querying concurrent occupancy](https://docs.akenza.io/reference/api-documentation/querying-device-data/querying-aggregations/querying-concurrent-occupancy.md) for explaination)
    * `sourceStage` selects one value per device (using topic/dataKey or measurementType) from the source data
    * `devicesStage` combines the values of several devices into one value.
    * `timeStage` combines values over time. `interval` sets the bucket size as an ISO 8601 duration, for example `P1D` for one value per day.
* `flags` changes how akenza formats and filters the result

By default, akenza aggregates over time first and then across devices. Set `aggregation.groupByTimeThenDevices` to `false` to aggregate across devices first.

Note the aggregation stage can also be simplified in easy case (when only one accumulator is needed). For example:

{% hint style="info" %}
For a full example with all three stages, see [Querying concurrent occupancy](https://docs.akenza.io/reference/api-documentation/querying-device-data/querying-aggregations/querying-concurrent-occupancy.md).
{% endhint %}

## Endpoint documentation in Postman

See the Postman documentation for the complete documentation of all endpoints and schema (all accumulators, all filters, all matchers ...)

[API docs (Postman)](https://docs.api.akenza.io/#9b867445-2278-45d1-bd09-b3bee0aca660)

## Accumulators

akenza provides several aggregation methods to sum data in an interval.

* MIN
  * the reported minimum during the time range
* MAX
  * the reported maximum during the time range
* AVG
  * the average of reported values during the time range
* SUM
  * the sum of reported values during the time range
* COUNT
  * the count of reported values during the time range
* FIRST
  * the first value in the time range
* LAST (or NONE)
  * the last value in the time range
* DISTINCT\_COUNT
  * the unique value counts for string values during the time range
* MATCHED\_COUNT
  * the number of values that are true during the time range
* UNMATCHED\_COUNT
  * the number of values that are false during the time range
* COUNT\_IF
  * the number of values that match the `filter`, for example the number of desks with an occupancy of 0 %
* SHARE\_IF
  * the share of values that match the `filter`, for example the share of desks with an occupancy of 0 %
* OCCUPANCY
  * Refer to time-based occupancy in % (see below)

### Time-based occupancy %

The algorithm to calculate time-based occupancy in % is based on a bucketing algorithm (the hour is split into 12 buckets, the occupancy is determined by the number of buckets that are marked as occupied).

The resulting value is the percentage of occupied time.

The example below returns the time-based occupancy of one desk over 5 days:

```bash
POST "https://api.akenza.io/v4/query/single-metrics"
{
  "match": {
    "devices": { "deviceIds": ["$DEVICE_ID"] },
    "timestamps": {
      "from": "2026-10-12T00:00:00Z",
      "to": "2026-10-17T00:00:00Z"
    },
    "dataPointSelector": { "topic": "occupancy", "dataKey": "occupied" }
  },
  "aggregation": { "accumulator": "OCCUPANCY" }
}
EOF
```

Response:

```json
{
  "devicesQueryMode": "AGGREGATED_ACROSS_DEVICES",
  "results": [
    {
      "metric": {
        "measurementType": "akenza/spaces/occupied/boolean",
        "topic": "occupancy",
        "dataKey": "occupied",
        "akenzaDeviceIds": ["<deviceId>"]
      },
      "dataPoint": 37.65,
      "timestamp": "2026-10-12T00:00:00Z"
    }
  ]
}
```

{% hint style="info" %}
Two methods are available to compute occupancy.\
Please refer to this [Occupancy monitoring](https://docs.akenza.io/analytics-use-cases/occupancy-monitoring.md) to learn more about the "concurrent occupancy" and how it compares to time-based occupancy in %.
{% endhint %}

## FAQ

<details>

<summary>Why do I get several results for one value aggregated across devices?</summary>

akenza returns one entry in `results` per combination of `measurementType`, `topic` and `dataKey`. If the selected devices store the value under different measurement types, or under different topics and data keys, the response contains several results.

To combine measurement types into one result, set `match.dataPointSelector.mergeMeasurementTypes` to `true`:

```json
"dataPointSelector": {
    "topic": "climate",
    "dataKey": "temperature",
    "mergeMeasurementTypes": true
}
```

</details>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.akenza.io/reference/api-documentation/querying-device-data/querying-aggregations.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
