---
title: "Insights API"
description: "Run trends, funnel, retention, segmentation, user-flow, top-K and map queries programmatically with a private key."
---

> Documentation Index
> Fetch the complete documentation index at: https://docs.pug.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# Insights API

Run analytics queries against the engine behind the dashboard's charts, overview KPIs and saved tiles. Browsers on other origins are blocked, so call it from a server.

**Service:** `shared.insights.v1.InsightsService`  
**Auth:** a private key (`prv_...`) in `x-api-key`, or a dashboard JWT in `Authorization: Bearer`. See [Authentication](/get-started/authentication).

Tables use proto names. Requests may use them or lowerCamelCase; responses always use lowerCamelCase (`eventKind`, `isOthers`), with int64 values as strings.

## Methods

### `Query`

```
POST /shared.insights.v1.InsightsService/Query
```

Runs one insight and returns a typed result whose shape depends on `spec.insight_type` (see [Insight types](#insight-types)).

#### Request: `QueryRequest`

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `spec` | `InsightQuerySpec` | Yes | The query specification (insight type, events, breakdowns, filters). |
| `time_range` | `TimeRange` | Yes | `from` (inclusive) and `to` (exclusive) as RFC 3339 timestamps; `from` must be before `to`. |
| `granularity` | `Granularity` | Yes | Time bucket size. See [Granularities](#granularities). |

Buckets align to the project's reporting timezone; a `timezone` field on the request is ignored.

#### Response: `QueryResponse`

The response carries exactly one of the following fields, selected by `spec.insight_type`:

| Field | Type | Populated when |
|-------|------|----------------|
| `trends` | `TrendsResult` | `INSIGHT_TYPE_TRENDS` |
| `segmentation` | `SegmentationResult` | `INSIGHT_TYPE_SEGMENTATION` |
| `funnel` | `FunnelResult` | `INSIGHT_TYPE_FUNNEL` |
| `retention` | `RetentionResult` | `INSIGHT_TYPE_RETENTION` |
| `user_flow` | `UserFlowResult` | `INSIGHT_TYPE_USER_FLOW` |
| `top_k` | `TopKResult` | `INSIGHT_TYPE_TOP_K`, `INSIGHT_TYPE_MAP` |

### `SegmentUsers`

```
POST /shared.insights.v1.InsightsService/SegmentUsers
```

Returns, a page at a time in ascending order, the raw `distinctId`s of users who performed any of the given events in a time range, so one person can appear under both an anonymous ID and an external ID. Cookieless and bot-tagged traffic is always left out.

| Field | Type | Description |
|-------|------|-------------|
| `time_range` | `TimeRange` | Required. |
| `events` | `EventQuery[]` | Required, at least one. |
| `filter_groups` | `FilterGroup[]` | Optional top-level filters. |
| `filter_groups_operator` | `LogicalOperator` | How groups are combined (default `AND`). |
| `page_size` | `int32` | 0-1000; 0 means 100. |
| `page_token` | `string` | The previous response's `nextPageToken`. |

Response: `{ "distinctIds": [...], "nextPageToken": "..." }`. The token is set only when a page is full, so the last page can be empty.

### `GetFilterSchema`

```
POST /shared.insights.v1.InsightsService/GetFilterSchema
```

Lists the project's event kinds and property keys (`events`, `auto_property_keys`, `custom_property_keys`, `profile_property_keys`), each with a count and last-seen time, and each key with its observed `value_type`. Results are cached for up to 5 minutes.

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `event_kind` | `string` | No | Limit the auto and custom keys to one event kind. |
| `allowed_types` | `PropertyValueType[]` | No | Keep only keys of these types. |

### `GetPropertyValues`

```
POST /shared.insights.v1.InsightsService/GetPropertyValues
```

Returns up to 100 distinct values of one property: an event property's from the last 30 days, or a profile trait's. Results are cached for 10 minutes, or an hour when there are fewer than 100.

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `property_key` | `string` | Yes | The property, such as `$country` or `plan`. An auto-property key must start with `$`. |
| `source` | `PropertySource` | Yes | `PROPERTY_SOURCE_AUTO`, `PROPERTY_SOURCE_CUSTOM` or `PROPERTY_SOURCE_PROFILE`. `PROPERTY_SOURCE_UNSPECIFIED` fails with `internal`. |
| `event_kind` | `string` | No | Only values seen on this event kind. Omit to scan all events. |

Response: `{ "values": string[] }`.

```json
{ "propertyKey": "$country", "source": "PROPERTY_SOURCE_AUTO" }
```

## Insight types

`InsightQuerySpec.insight_type` selects the computation and the response field.

| Enum value | Description |
|------------|-------------|
| `INSIGHT_TYPE_TRENDS` | Time-series event counts or aggregations. One `TrendSeries` per `(event, breakdown)` combination. |
| `INSIGHT_TYPE_SEGMENTATION` | Single scalar over the full time range, no time axis. With several events, one value covers events matching any of them, using the first event's aggregation. |
| `INSIGHT_TYPE_FUNNEL` | Multi-step conversion funnel. Steps are the `events` array in order. Each series carries per-step counts, plus per-step timing when `include_step_timing` is true. |
| `INSIGHT_TYPE_RETENTION` | Cohort retention matrix. `events[0]` is the starting event; `events[1]` (optional) is the return event. Cohorts are bucketed by the query granularity. |
| `INSIGHT_TYPE_USER_FLOW` | Sankey graph of transitions between events or property values. Requires a [`user_flow`](#userflowquery) sub-spec; no `events` field. |
| `INSIGHT_TYPE_TOP_K` | Ranking: the top K values of a dimension by a metric, plus a trailing `$others` bucket. Requires a `top_k` sub-spec; no `events` field, no time axis. See [`TopKQuery`](#topkquery). |
| `INSIGHT_TYPE_MAP` | Choropleth: one metric per country, the dimension fixed to `$country`. Requires a `map` sub-spec; no `events` field, no time axis. Results arrive in `top_k`. See [`MapQuery`](#mapquery). |

### Insight type constraints

Breaking any of these fails with `invalid_argument`:

- **`INSIGHT_TYPE_FUNNEL`**: 1-20 events. Takes `breakdowns`, `conversion_window` and `include_step_timing`.
- **`INSIGHT_TYPE_RETENTION`**: 1 or 2 events (`events[0]` = start, `events[1]` = return).
- **`INSIGHT_TYPE_SEGMENTATION`**: no `breakdowns`.
- **`INSIGHT_TYPE_USER_FLOW`**: requires `user_flow`; `events`, `session`, `breakdowns` and `breakdown_limit` must be empty.
- **`INSIGHT_TYPE_TOP_K`**: requires `top_k`; `events`, `session`, `breakdowns` and `breakdown_limit` must be empty. Scope events through `top_k.scope`.
- **`INSIGHT_TYPE_MAP`**: requires `map`; `events`, `session`, `breakdowns` and `breakdown_limit` must be empty. Scope events through `map.scope`.
- **Numeric aggregations** (`AGGREGATION_TYPE_SUM`, `AVG`, `MIN`, `MAX`): trends and segmentation only.

## Granularities

`QueryRequest.granularity` controls the time-bucket width and imposes a maximum query range.

| Enum value | Bucket width | Maximum time range |
|------------|-------------|-------------------|
| `GRANULARITY_MINUTE` | 1 minute | 6 hours |
| `GRANULARITY_HOUR` | 1 hour | 14 days |
| `GRANULARITY_DAY` | 1 day | 365 days |
| `GRANULARITY_WEEK` | 1 week | ~4 years (1461 days) |
| `GRANULARITY_MONTH` | 1 month | ~10 years (3652 days) |

## `InsightQuerySpec` fields

| Field | Type | Description |
|-------|------|-------------|
| `insight_type` | `InsightType` | Required. Selects the computation and response shape. |
| `events` | `EventQuery[]` | Event series for trends, segmentation, funnel and retention. Each selects one event kind, with optional filters and an aggregation. |
| `breakdowns` | `Breakdown[]` | Group results by up to 5 distinct properties (`{ property: string }`). Funnel and retention take each user's value from their earliest matching event. |
| `breakdown_limit` | `int32` | Breakdown values to keep, 0-100; 0 means 10. The rest merge into one series whose breakdown values are all `$others` (series carry no `is_others` flag). Requires at least one breakdown. |
| `filter_groups` | `FilterGroup[]` | Top-level property filters. Multiple groups are combined by `filter_groups_operator`. |
| `filter_groups_operator` | `LogicalOperator` | How filter groups are combined. Defaults to `LOGICAL_OPERATOR_AND`. |
| `conversion_window` | `Duration` | Funnel only. Maximum time from the first step to the last, per user: whole seconds, at least `1s`. Absent means the whole time range. |
| `include_step_timing` | `bool` | Funnel only. When true, each non-entry step includes `StepTiming` (avg, median, p95, 8-bucket histogram). |
| `session` | `SessionQuery` | Trends and segmentation only. Measures sessions instead of events; `events` must be empty. See [Session metrics](#session-metrics). |
| `user_flow` | `UserFlowQuery` | User flow only. See [`UserFlowQuery`](#userflowquery). |
| `top_k` | `TopKQuery` | Top-K only. Configures the ranking (dimension, metric, limit). See [`TopKQuery`](#topkquery). |
| `map` | `MapQuery` | Map only. Configures the per-country metric (scope, metric, metric property). See [`MapQuery`](#mapquery). |
| `include_cookieless` | `bool` | Count [cookieless visitors](/api/events#cookieless-events) in user-based results. Defaults to `false` - see below. |
| `include_bots` | `bool` | Count traffic tagged as a bot at ingest. Defaults to `false` - see [Bot traffic is excluded](#bot-traffic-is-excluded). |

### Cookieless visitors are excluded from user counts

By default, cookieless visitors are left out of:

- **`UNIQUE_USERS` and `PER_USER_AVG`**, numerator and denominator alike, wherever those metrics appear: trends, segmentation, [top K](#topkquery), [map](#mapquery).
- **Person-based insights**: funnel, retention, user flow, and `DIMENSION_USER` top K, whichever metric is selected.

Event totals, numeric aggregations and all session metrics always count every visitor. With `include_cookieless: true` cookieless visitors count above too, as a new user each day, since their IDs rotate daily.

### Bot traffic is excluded

Ingest tags a web-SDK event `$bot` when its user agent is a known crawler, its network is a datacenter's, or it reports headless Chrome's default 800x600 screen. Tagged events are left out of **every** insight and metric by default, event totals included. Session metrics and user flow judge a session whole, so one tagged event drops its session. Events sent with a private key are never tagged. Set `include_bots: true` to count them.

### `EventQuery`

| Field | Type | Description |
|-------|------|-------------|
| `event` | `EventFilter` | Event kind (empty means any) and optional per-event property filters, all of which must match. |
| `aggregation` | `AggregationType` | Defaults to `AGGREGATION_TYPE_TOTAL`. Funnel and retention ignore the counting types and reject the numeric ones. |
| `aggregation_property` | `string` | Required for `SUM`, `AVG`, `MIN`, `MAX`. Property name to aggregate (e.g. `revenue`). |

### Aggregation types

| Enum value | Description |
|------------|-------------|
| `AGGREGATION_TYPE_TOTAL` | Total event occurrences. |
| `AGGREGATION_TYPE_UNIQUE_USERS` | Count of distinct users. |
| `AGGREGATION_TYPE_PER_USER_AVG` | Average events per user. |
| `AGGREGATION_TYPE_SUM` | Sum of a numeric property. Requires `aggregation_property`. |
| `AGGREGATION_TYPE_AVG` | Mean of a numeric property. Requires `aggregation_property`. |
| `AGGREGATION_TYPE_MIN` | Minimum of a numeric property. Requires `aggregation_property`. |
| `AGGREGATION_TYPE_MAX` | Maximum of a numeric property. Requires `aggregation_property`. |

### `TopKQuery`

Ranks the values of one dimension by a metric. It has **no time axis**: `granularity` only selects which [time-range cap](#granularities) applies, so send the coarsest one whose cap admits your window.

| Field | Type | Description |
|-------|------|-------------|
| `dimension` | `Dimension` | Required. What is being ranked - see below. |
| `property` | `string` | The property to rank values of. Required when `dimension` is `DIMENSION_PROPERTY`, and rejected otherwise. Same `$`-prefix encoding as `Breakdown.property`. |
| `scope` | `EventFilter` | Optional event scope (kind and/or per-event filters). Empty means all events participate. This replaces `events`, which top K may not set. |
| `metric` | `AggregationType` | Metric to rank by. Defaults to `AGGREGATION_TYPE_TOTAL`. |
| `metric_property` | `string` | Property to aggregate. Required for `SUM`, `AVG`, `MIN`, `MAX`; ignored otherwise. |
| `limit` | `int32` | Rows to return before `$others`, 0-100; 0 means 10. |
| `omit_others` | `bool` | Drop the trailing synthetic `$others` bucket and return only the top `limit` rows. Defaults to `false`. |

| `Dimension` | Ranks |
|---|---|
| `DIMENSION_PROPERTY` | Values of an event property, auto or custom, named by `property`. |
| `DIMENSION_EVENT_KIND` | Event kinds: "top events". |
| `DIMENSION_USER` | Users. `dimension_value` is the canonical profile ID, or the raw `distinctId` when none resolves. `UNIQUE_USERS` and `PER_USER_AVG` are rejected. |

`TopKResult` holds `rows`, ordered metric-descending, with the `$others` bucket last when anything overflows. Each `TopKRow` carries `dimension_value`, `value`, `is_others`, and, for resolved `DIMENSION_USER` rows only, a `profile` (`id`, `external_id`, `properties`).

Identify the overflow bucket by **`is_others`**, not by matching `"$others"`, which can be a real property value or event kind. The same holds for `UserFlowNode`.

### `MapQuery`

Measures one metric per `$country` for a choropleth; there is no `dimension`, `property` or `limit` to set. Like top K it has **no time axis**, so `granularity` only selects which [time-range cap](#granularities) applies.

| Field | Type | Description |
|-------|------|-------------|
| `scope` | `EventFilter` | Optional event scope (kind and/or per-event filters). Empty means all events participate. This replaces `events`, which map may not set. |
| `metric` | `AggregationType` | Metric to measure per country. Defaults to `AGGREGATION_TYPE_TOTAL`. |
| `metric_property` | `string` | Property to aggregate. Required for `SUM`, `AVG`, `MIN`, `MAX`; rejected for the counting metrics. |

Results arrive in `QueryResponse.top_k`, ordered metric-descending, with the country code in `dimension_value` and no `$others` bucket.

> **Map rows do not sum to your project total**
>
> Every returned key is an assigned **ISO 3166-1 alpha-2** code. Rows that aren't one are dropped: traffic the geo lookup couldn't resolve, and any other value a client wrote to `$country` (`"USA"`, `"unknown"`, unassigned codes like `"ZZ"`). Compute percentages against the row set, not against a separate total.
>
> Ranking happens **before** that filter, against an internal cap of 250 countries, so a project flooded with junk `$country` values can push real countries out of the result.

### `UserFlowQuery`

Configures the user-flow graph: each session's events in time order, one step per event.

| Field | Type | Description |
|-------|------|-------------|
| `node_kind` | `NodeKind` | `NODE_KIND_EVENT_KIND` (the default) names nodes by event kind; `NODE_KIND_PROPERTY` by the value of `node_property`. |
| `node_property` | `string` | Required with `NODE_KIND_PROPERTY`. |
| `group_by` | `GroupBy` | `GROUP_BY_SESSION`, the only value and the default. |
| `scope` | `EventFilter` | Which events can become nodes. A session with none emits no transitions. |
| `max_hops` | `int32` | Steps per session, 1-10; 0 means 5. |
| `max_nodes` | `int32` | Nodes kept per step, 2-50, before the rest merge into that step's `$others` node; 0 means 20. |
| `max_links` | `int32` | Links returned, 1-500, dropping the lowest-value ones; 0 means 250. |

`UserFlowResult` holds `nodes` (`id`, `is_others`, `depth`, `label`) and `links` (`source`, `target`, `value`). A node's `id` is an opaque key, unique per depth and label; `depth` is its 0-based step, and every link joins depth d to d+1.

## Filter model

Filters are `FilterGroup` objects in `spec.filter_groups`. Each group's `operator` combines its `PropertyFilter`s, and `spec.filter_groups_operator` combines the groups.

### `FilterGroup`

```json
{
  "filters": [
    { "property": "plan", "operator": "FILTER_OPERATOR_EQUALS", "value": "pro" },
    { "property": "$country", "operator": "FILTER_OPERATOR_IN", "values": ["US", "CA"] }
  ],
  "operator": "LOGICAL_OPERATOR_AND"
}
```

A group needs at least one filter. A `PropertyFilter` takes `property`, `operator`, `value` or `values`, and `source`: `PROPERTY_SOURCE_PROFILE` matches events by their user's profile traits, and any other source matches the event's own property, auto if `property` starts with `$`, else custom.

### Filter operators (`FilterOperator`)

| Enum value | Value fields used | Description |
|------------|------------------|-------------|
| `FILTER_OPERATOR_EQUALS` | `value` | Exact match. |
| `FILTER_OPERATOR_NOT_EQUALS` | `value` | Excludes exact match. |
| `FILTER_OPERATOR_CONTAINS` | `value` | Case-sensitive substring match. |
| `FILTER_OPERATOR_NOT_CONTAINS` | `value` | Excludes substring match. |
| `FILTER_OPERATOR_IS_SET` | - | Property exists. |
| `FILTER_OPERATOR_IS_NOT_SET` | - | Property is absent. |
| `FILTER_OPERATOR_LTE` | `value` (numeric) | Less than or equal. |
| `FILTER_OPERATOR_GTE` | `value` (numeric) | Greater than or equal. |
| `FILTER_OPERATOR_LT` | `value` (numeric) | Strictly less than. |
| `FILTER_OPERATOR_GT` | `value` (numeric) | Strictly greater than. |
| `FILTER_OPERATOR_IN` | `values` | Match any of a list. |
| `FILTER_OPERATOR_NOT_IN` | `values` | Exclude all of a list. |
| `FILTER_OPERATOR_BETWEEN` | `values[0]`, `values[1]` (numeric, ordered) | Inclusive range. |
| `FILTER_OPERATOR_NOT_BETWEEN` | `values[0]`, `values[1]` (numeric, ordered) | Outside range. |

Set only the fields in that column: a missing one fails with `invalid_argument`, and so can an extra one. On event properties, an empty string counts as not set; `NOT_EQUALS`, `NOT_CONTAINS` and `NOT_IN` also match events without the property; and the numeric operators never match a non-numeric value.

### Logical operators (`LogicalOperator`)

| Enum value | Description |
|------------|-------------|
| `LOGICAL_OPERATOR_AND` | All conditions must match (default). |
| `LOGICAL_OPERATOR_OR` | At least one condition must match. |

A filter's `property` matches `^\$?[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)*$`. Auto-properties use their `$` key, such as `$country`; [Auto-properties](/reference/auto-properties) lists them. A dotted name is a literal event-property key, or, with `PROPERTY_SOURCE_PROFILE`, a path into a nested trait.

## Session metrics

When `spec.session` is set, the query measures sessions instead of individual events, and `spec.events` must be empty. Sessions are selected by start time and measured over all their in-scope events, even past the end of the window.

| Enum value | Description | Restrictions |
|------------|-------------|--------------|
| `SESSION_METRIC_SESSIONS` | Count of distinct sessions started in the window. | Trends or segmentation. |
| `SESSION_METRIC_AVG_DURATION` | Average session duration in seconds (last event - first event). | Trends or segmentation. |
| `SESSION_METRIC_BOUNCE_RATE` | Percentage of sessions with exactly one event (after optional scope filter). | Trends or segmentation. |
| `SESSION_METRIC_AVG_EVENTS_PER_SESSION` | Average number of scoped events per session; with a `page_view` scope, pages per session. | Trends or segmentation. |
| `SESSION_METRIC_ENTRY` | Count sessions by their first matching event's breakdown value (entry page). | Trends + exactly one breakdown. |
| `SESSION_METRIC_EXIT` | Count sessions by their last matching event's breakdown value (exit page). | Trends + exactly one breakdown. |

`SessionQuery.scope` (optional `EventFilter`) restricts which events participate in the metric. An empty scope considers all events in the session.

## Worked example: TRENDS query

A daily time series of unique users who fired `page_view`, broken down by `$country`, over the last 30 days.

```http
POST /shared.insights.v1.InsightsService/Query
Content-Type: application/json
Connect-Protocol-Version: 1
x-api-key: prv_...
```

```json
{
  "spec": {
    "insightType": "INSIGHT_TYPE_TRENDS",
    "events": [
      {
        "event": { "kind": "page_view" },
        "aggregation": "AGGREGATION_TYPE_UNIQUE_USERS"
      }
    ],
    "breakdowns": [
      { "property": "$country" }
    ],
    "breakdownLimit": 10
  },
  "timeRange": {
    "from": "2026-05-06T00:00:00Z",
    "to": "2026-06-05T00:00:00Z"
  },
  "granularity": "GRANULARITY_DAY"
}
```

Response sketch:

```json
{
  "trends": {
    "series": [
      {
        "eventKind": "page_view",
        "breakdown": { "$country": "US" },
        "points": [
          { "time": "2026-05-06T00:00:00Z", "value": 412 },
          { "time": "2026-05-07T00:00:00Z", "value": 389 }
        ]
      },
      {
        "eventKind": "page_view",
        "breakdown": { "$country": "GB" },
        "points": [
          { "time": "2026-05-06T00:00:00Z", "value": 104 },
          { "time": "2026-05-07T00:00:00Z", "value": 97 }
        ]
      }
    ]
  }
}
```

Each `series` entry is one `(event_kind, breakdown)` pair. `points` run in ascending time order, and a bucket with no data may be missing rather than zero.

## Worked example: FUNNEL query

```http
POST /shared.insights.v1.InsightsService/Query
Content-Type: application/json
Connect-Protocol-Version: 1
x-api-key: prv_...
```

```json
{
  "spec": {
    "insightType": "INSIGHT_TYPE_FUNNEL",
    "events": [
      { "event": { "kind": "signup_started" } },
      { "event": { "kind": "signup_completed" } },
      { "event": { "kind": "purchase" } }
    ],
    "conversionWindow": "604800s"
  },
  "timeRange": {
    "from": "2026-05-01T00:00:00Z",
    "to": "2026-06-01T00:00:00Z"
  },
  "granularity": "GRANULARITY_DAY"
}
```

Response sketch:

```json
{
  "funnel": {
    "series": [
      {
        "steps": [
          { "eventKind": "signup_started",   "total": 1000 },
          { "eventKind": "signup_completed", "total": 650 },
          { "eventKind": "purchase",         "total": 120 }
        ]
      }
    ]
  }
}
```

With `includeStepTiming: true`, each non-entry step gains a `timing` object:

```json
{
  "eventKind": "signup_completed",
  "total": 650,
  "timing": {
    "avg": "180s",
    "median": "95s",
    "p95": "1200s",
    "distribution": [
      { "label": "0-30s",  "upperBound": "30s",  "count": "78" },
      { "label": "30s-2m", "upperBound": "120s", "count": "210" }
    ]
  }
}
```

A full `distribution` always has the same 8 buckets in a fixed order, and the last, `24h+`, has no `upperBound`. A step nobody converted to has every timing field at zero.

## Performance notes

Query time grows with the time range at fine granularities, with breakdown cardinality (cap it with `breakdown_limit`), and with funnel steps. Most queries are cached for 60 seconds, so repeating one with the same parameters may not include events ingested since.

## Related

- [API reference](/api): base URL, auth, error codes
- [Auto-properties](/reference/auto-properties): filterable `$`-prefixed properties
- [RPC services](/reference/rpc-services): full method index

Source: https://docs.pug.sh/api/insights/index.mdx
