# Telemetry - script API

## Function: `Telemetry.query(dataSourceName: String, query: String)`

A telemetry query is a conjunction of equality conditions. For example, `name = 'system.load.norm.15' and host='localhost'`. There are several builder methods available that help to refine the query time range, limit the number of points returned, or set a metric field.

{% hint style="warning" %}
Telemetry queries only support metric queries. If you need event queries, please enter a feature request at [support.stackstate.com](https://support.stackstate.com)
{% endhint %}

### Args

* `dataSourceName` - name of the data source.
* `query` - set of equality conditions.

### Returns

{% hint style="info" %}
The output format of the Telemetry API changed in StackState v5.0. If you are running an earlier version of StackState, see the documentation for [StackState v4.6 documentation (docs.stackstate.com/v/4.6)](https://docs.stackstate.com/v/4.6/develop/reference/scripting/script-apis/telemetry).
{% endhint %}

`StreamingScriptResult[MetricTimeSeriesResult]`

### Builder methods

* `.groupBy(fieldName: String)` - optional. Used to return grouped results from Elasticsearch. Requires `.aggregation()` to be used. If there is no aggregation, a plain metric stream will be returned.
* `aggregation(method: String, bucketSize: String)` - returns aggregated telemetry using `method` and `bucketSize`. See the [available aggregation methods](/5.1/use/metrics/add-telemetry-to-element.md#aggregation-methods).
* `start(time: Instant)` - sets the [start time](/5.1/develop/reference/scripting/script-apis/time.md) of the query, for example `-3h`.
* `end(time: Instant)` - sets the [end time](/5.1/develop/reference/scripting/script-apis/time.md) of the query, for example `-1h`.
* `window(start: Instant, end: Instant)` - sets query [time range](/5.1/develop/reference/scripting/script-apis/time.md). Use only `start` to get all telemetry up to now or only `end` to get all telemetry up to an instant in time.
* `limit(points: Int)` - limits the number of points returned, applicable to non-aggregated queries.
* `metricField(fieldName: String)` - optional, but may be required for some data sources. Sets a field that holds metric value.
* `compileQuery()` - returns the telemetry query that was created with this function and the builder methods. After this builder method no more builder methods can be called.

### Examples

* [Get metrics aggregated using Mean with bucket size 15 minutes and grouped by the field `host`](#get-metrics-aggregated-using-mean-with-bucket-size-15-minutes-and-grouped-by-the-field-host)
* [Process the `StreamingScriptResult` result data, getting the ids of the resulting timeSeries](#process-the-streamingscriptresultstreaming-script-resultmd-result-data-getting-the-ids-of-the-resulting-timeseries)
* [Get raw metric by query](#get-raw-metric-by-query)
* [Get metric aggregated using Mean with bucket size 1 minute](#get-metric-aggregated-using-mean-with-bucket-size-1-minute)
* [Query metrics starting 3 hours ago till now](#query-metrics-starting-3-hours-ago-till-now)
* [Query metrics starting beginning of the data till last hour ago](#query-metrics-starting-beginning-of-the-data-till-last-hour-ago)
* [Query metrics within time range starting 3 hours ago up to 1 hour ago](#query-metrics-within-time-range-starting-3-hours-ago-up-to-1-hour-ago)
* [Query metrics from field `value` and limits points returned](#query-metrics-from-field-value-and-limits-points-returned)

#### Get metrics aggregated using Mean with bucket size 15 minutes and grouped by the field `host`:

{% tabs %}
{% tab title="Query" %}

```
Telemetry
  .query("StackState Multi Metrics", "")
  .groupBy("host")
  .metricField("jvm_threads_current")
  .start("-15m")
  .aggregation("mean", "15m")
```

{% endtab %}

{% tab title="Example JSON output" %}

```
[{
  "_type": "MetricTimeSeriesResult",
  "query": {
    "_type": "TelemetryMetricQuery",
    "aggregation": {
      "bucketSize": 900000,
      "method": "MEAN"
    },
    "conditions": [
      {
        "key": "name",
        "value": "jvm_threads_current"
      }
    ],
    "dataSourceId": 277422153298283,
    "endTime": 1643294849765,
    "groupBy": {
      "fields": ["host"]
    },
    "includeAnnotations": false,
    "metricField": "stackstate.jvm_threads_current",
    "startTime": 1643293949765
  },
  "timeSeries": {
    "_type": "TimeSeries",
    "annotations": [],
    "id": {
      "_type": "TimeSeriesId",
      "groups": {
        "host": "sts-kafka-to-es-multi-metrics_generic-events_topology-events_state-events_sts-events"
      }
    },
    "points": [[1643293800000, 49.46666666666667]],
    "tags": []
  }
},
{
  "_type": "MetricTimeSeriesResult",
  "query": {
    "_type": "TelemetryMetricQuery",
    "aggregation": {
      "bucketSize": 900000,
      "method": "MEAN"
    },
    "conditions": [
      {
        "key": "name",
        "value": "jvm_threads_current"
      }
    ],
    "dataSourceId": 277422153298283,
    "endTime": 1643294849765,
    "groupBy": {
      "fields": ["host"]
    },
    "includeAnnotations": false,
    "metricField": "stackstate.jvm_threads_current",
    "startTime": 1643293949765
  },
  "timeSeries": {
    "_type": "TimeSeries",
    "annotations": [],
    "id": {
      "_type": "TimeSeriesId",
      "groups": {
        "host": "sts-kafka-to-es-trace-events"
      }
    },
    "points": [[1636293800000, 54.7]],
    "tags": []
  }
}]
```

{% endtab %}
{% endtabs %}

#### Process the [StreamingScriptResult](/5.1/develop/reference/scripting/streaming-script-result.md) result data, getting the ids of the resulting timeSeries

{% tabs %}
{% tab title="Query" %}

```
Telemetry
  .query("StackState Multi Metrics", "")
  .groupBy("host")
  .metricField("jvm_threads_current")
  .start("-15m")
  .aggregation("mean", "15m")
  .then { it.timeSeries.id }
```

{% endtab %}

{% tab title="Example JSON output" %}

```
[
  {
    "_type": "TimeSeriesId",
      "groups": {
        "host": "sts-kafka-to-es-multi-metrics_generic-events_topology-events_state-events_sts-events"
      }
    },
    {
      "_type": "TimeSeriesId",
        "groups": {
          "host": "sts-kafka-to-es-trace-events"
        }
    }
  }
]
```

{% endtab %}
{% endtabs %}

#### Get raw metric by query

```
Telemetry
  .query("StackState Metrics", "name='system.load.norm' and host='host1'")
  .metricField("value")
```

#### Get metric aggregated using Mean with bucket size 1 minute

```
Telemetry
  .query("StackState Metrics", "name='system.load.norm' and host='host1'")
  .metricField("value")
  .aggregation("99th percentile", "1m") // get 99th percentile of each minute
```

#### Query metrics starting 3 hours ago till now

```
Telemetry
  .query("StackState Metrics", "name='system.load.norm' and host='host1'")
  .metricField("value")
  .start("-3h") // starting from 3 hours ago
```

#### Query metrics starting beginning of the data till last hour ago

```
Telemetry
  .query("StackState Metrics", "name='system.load.norm' and host='host1'")
  .metricField("value")
  .end("-1h") // ending 1 hour ago
```

#### Query metrics within time range starting 3 hours ago up to 1 hour ago

```
Telemetry
  .query("StackState Metrics", "name='system.load.norm' and host='host1'")
  .metricField("value")
  .window("-3h", "-1h") // from 3 hours ago to 1 hour ago
```

#### Query metrics from field "value" and limits points returned

```
Telemetry
  .query("StackState Metrics", "name='system.load.norm' and host='host1'")
  .metricField("value")
  .limit(100)
```

## See also

* [Streaming script result](/5.1/develop/reference/scripting/streaming-script-result.md)


---

# 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://archivedocs.stackstate.com/5.1/develop/reference/scripting/script-apis/telemetry.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.
