> ## Documentation Index
> Fetch the complete documentation index at: https://developer.box.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Query insights

export const Link = ({href, children, className, ...props}) => {
  const localizedHref = localizeLink(href);
  return <a href={localizedHref} className={className} {...props}>
      {children}
    </a>;
};

Query insights API lets you compute aggregated insights (sums, averages, counts, and more) over items that match a metadata-based query. The system applies the specified filters first, then performs aggregation based on the provided grouping criteria, if any.

To get insights, call the `POST https://api.box.com/2.0/query/insights` endpoint.

## Parameters

To make a call, you must pass the following parameters. The request body has two top-level fields: `query` and `metrics`. Mandatory parameters are in **bold**.

| Parameter                                                               | Type             | Description                                                                                                                                                                                                                                                                                                                                       | Example                                     |
| ----------------------------------------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- |
| **`query`**                                                             | object           | Defines the filtering conditions and grouping parameters for an insights request. Holds `predicate`, `params`, `ancestors`, and `group_by` together (not mutually exclusive).                                                                                                                                                                     | `ancestors`                                 |
| **`query.predicate`**                                                   | string           | Filters the dataset before the metric computation. The predicate syntax is similar to an SQL `WHERE` clause and can include parameterized arguments.                                                                                                                                                                                              | `enterprise_12345678:book:amount >= :value` |
| `query.params`                                                          | object           | Must include a key for each placeholder, where the key matches the placeholder name without the `:` prefix. Value types must match the field types used in the predicate. **Required only if the predicate contains parameter placeholders** (for example, `:param`).                                                                             | `{ "value": 100 }`                          |
| `query.ancestors`                                                       | array of objects | Filters results based on item ancestry. Each object needs an `id` and `type` (such as `folder`). Returns items contained within any of the specified ancestors. The user must have access to all provided ancestors, otherwise the request is rejected. If empty or omitted, insights are computed across all accessible items (root context, 0). | `[{ "id": "123", "type": "folder" }]`       |
| `query.group_by`                                                        | array of objects | Specifies how data is grouped. Each entry defines a grouping field and an optional bucket limit. Only a single group-by field is currently supported. Grouping is applied after filters and before metric computation. Grouping on high-cardinality fields can error; keep cardinality below 10,000.                                              |                                             |
| `[{ "field": "enterprise_12345678:book:category", "bucket_limit": 5 }]` |                  |                                                                                                                                                                                                                                                                                                                                                   |                                             |
| `query.group_by[].field`                                                | string           | Fully qualified field name to group by. Supported fields include metadata and item properties (see [supported field types](guides/metadata/fields/index)).                                                                                                                                                                                        | `enterprise_12345678:book:category`         |
| `query.group_by[].bucket_limit`                                         | integer          | Maximum number of buckets to return for the grouping. Defaults to 5, maximum allowed value is 10.                                                                                                                                                                                                                                                 | `5`                                         |
| **`metrics`**                                                           | object (map)     | A set of named metrics to compute. Each entry maps a user-defined alias to a metric operation applied to a field. Metrics are evaluated after filters (and grouping, if specified). Maximum 10 metrics in a request.                                                                                                                              | See examples below.                         |
| `metrics.<alias>.type`                                                  | string           | Aggregation function to apply. Supported values: `sum`, `avg`, `min`, `max`, `count`.                                                                                                                                                                                                                                                             | `count`                                     |
| `metrics.<alias>.field`                                                 | string           | Fully qualified field name on which the metric is computed.                                                                                                                                                                                                                                                                                       | `enterprise_12345678:product:category`      |

### Metric names

Each key in the `metrics` object is an alias defined by you for the metric.

**Naming convention**

* Must be a non-empty string
* Must be unique within the request
* Maximum length: 256 characters
* Allowed characters: letters (a–z, A–Z), digits (0–9), and special characters `_`, `-`, and `.`
* Must not start with a digit or special character
* Whitespace and other special characters are not allowed

**Behavior**

* If `group_by` is not specified, metrics are computed over the entire filtered dataset (ungrouped aggregation).
* If `metrics` is an empty object ({}), a default `totalResultCount` count metric is returned over the filtered dataset (see Total document count example).

## Examples

### Total contract value

Get total contract value and counts for top 3 contract types created in June 2025.

**Request:**

```json theme={null}
{
    "query": {
      "predicate": "EXISTS(:templateArg) AND box:item:created_at >= :dateArg1 AND box:item:created_at < :dateArg2",
      "params": {
        "templateArg": "enterprise_12345678:sales",
        "dateArg1": "2025-06-01T00:00:00-07:00",
        "dateArg2": "2025-07-01T00:00:00-07:00"
      },
      "ancestors": [
        {
          "id": "123",
          "type": "folder"
        }
      ],
      "group_by": [
        {
          "field": "enterprise_12345678:sales:contractType",
          "bucket_limit": 3
        }
      ]
    },
    "metrics": {
      "totalContractValue": {
        "type": "sum",
        "field": "enterprise_12345678:sales:contractValue"
      },
      "countContractType": {
        "type": "count",
        "field": "enterprise_12345678:sales:contractType"
      }
    }
  }
```

**Response:**

```json theme={null}
{
  "insights": [
    {
      "key": [ "ContractType1" ],
      "type": "group",
      "metrics": {
        "totalContractValue": {
          "type": "sum",
          "values": {
            "sum": 180000
          }
        },
        "countContractType": {
          "type": "count",
          "values": {
            "count": 245
          }
        }
      }
    },
    {
      "key": [ "ContractType4" ],
      "type": "group",
      "metrics": {
        "totalContractValue": {
          "type": "sum",
          "values": {
            "sum": 100000
          }
        },
        "countContractType": {
          "type": "count",
          "values": {
            "count": 185
          }
        }
      }
    },
    {
      "key": [ "ContractType2" ],
      "type": "group",
      "metrics": {
        "totalContractValue": {
          "type": "sum",
          "values": {
            "sum": 200000
          }
        },
        "countContractType": {
          "type": "count",
          "values": {
            "count": 150
          }
        }
      }
    },
    {
      "key": [],
      "type": "other",
      "metrics": {
        "totalCountBeyondTopGroups": {
          "type": "count",
          "values": {
            "count": 165
          }
        }
      }
    }
  ]
}
```

### Overall average, minimum, maximum contract value

Get overall average, minimum, and maximum contract value for contracts created in June 2025.

**Request:**

```json theme={null}
{
    "query": {
      "predicate": "EXISTS(:templateArg) AND box:item:created_at >= :dateArg1 AND box:item:created_at < :dateArg2",
      "params": {
        "templateArg": "enterprise_12345678:sales",
        "dateArg1": "2025-06-01T00:00:00-07:00",
        "dateArg2": "2025-07-01T00:00:00-07:00"
      },
      "ancestors": [
        {
          "id": "123",
          "type": "folder"
        }
      ]
    },
    "metrics": {
      "avgContractValue": {
        "type": "avg",
        "field": "enterprise_12345678:sales:contractValue"
      },
      "minContractValue": {
        "type": "min",
        "field": "enterprise_12345678:sales:contractValue"
      },
      "maxContractValue": {
        "type": "max",
        "field": "enterprise_12345678:sales:contractValue"
      }
    }
  }
```

**Response:**

```json theme={null}
{
    "insights": [
      {
        "key": [],
        "type": "overall",
        "metrics": {
          "avgContractValue": {
            "type": "avg",
            "values": {
              "avg": 45055.50
            }
          },
          "minContractValue": {
            "type": "min",
            "values": {
              "min": 22000
            }
          },
          "maxContractValue": {
            "type": "max",
            "values": {
              "max": 75000
            }
          }
        }
      }
    ]
  }
```

### Total document count

Get total document count only by passing an empty metrics object.

**Request:**

```json theme={null}
{
    "query": {
      "predicate": "EXISTS(:templateArg)",
      "params": {
        "templateArg": "enterprise_12345678:sales"
      },
      "ancestors": [
        {
          "id": "123",
          "type": "folder"
        }
      ]
    },
    "metrics": {}
  }
```

**Response:**

```json theme={null}
{
    "insights": [
      {
        "key": [],
        "type": "overall",
        "metrics": {
          "totalResultCount": {
            "type": "count",
            "values": {
              "count": 12345
            }
          }
        }
      }
    ]
  }
```

## Response fields

| Field              | Type             | Description                                                                                                                                                                                                                    | Example                                                           |
| ------------------ | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------- |
| `insights`         | array            | The calculated results of the request. Each entry corrensponds to a specific result type and contains the associated grouping keys (if applicable) and calculated metrics.                                                     | See below.                                                        |
| `insights.key`     | array of objects | The grouping key values for the entry. Structure depends on the entry type.                                                                                                                                                    | See below.                                                        |
| `insights.key`     | array of strings | One value for each `group_by` field.                                                                                                                                                                                           | `["Shoe"]`                                                        |
| `insights.type`    | string           | The type of insight entry. One of `group`, `overall`, or `other`.                                                                                                                                                              | `group`                                                           |
| `insights.metrics` | object           | A map of the calculated metric results. Each key is a user-defined metric alias. Each value contains the metric type and its calculated values. The count metric for the other type is in the `totalCountBeyondTopGroups` key. | `"metrics": {"totalPrice": {"type": "sum","values": {"sum": 50}}` |

### Insight entry types

| Type      | Description                                                                                                                                        |
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `group`   | Metrics for a specific group defined by `group_by`. `key` contains one value per `group_by` field, for example \["Shoe"] for category = `"Shoe"`.  |
| `overall` | Metrics calculated across the entire dataset (no grouping). `key` is always an empty array `[]`.                                                   |
| `other`   | Aggregated count for results outside the top returned groups. An empty array `[]` represents all remaining groups not included in the top results. |

## Bucket ordering

For requests with `group_by`, bucket ordering is implicit and always descending by item count (the number of documents in each bucket). The largest buckets are returned first. This ordering cannot be customized.

For the **Enum** and **Taxonomy** fields, deleted options can temporarily appear in top groups while the deletion job is in progress. Such groups have their keys shown as `[DELETED]`.

## Error codes

The list below is not exhaustive, additional error codes and details can be introduced as the API evolves.

| Error Code | Error Type              | Error Message                                                                                                                                                           |
| ---------- | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `400`      | `BAD_REQUEST`           | Expected JSON with type string or *Failed to parse query: Unexpected end of input* message. Returned when the query cannot be parsed or an unexpected JSON is provided. |
| `401`      | `UNAUTHORIZED`          | The access token provided is invalid. Returned when an invalid or expired access token is used.                                                                         |
| `403`      | `FORBIDDEN`             | Query is restricted for this enterprise/scope.                                                                                                                          |
| `404`      | `INSTANCE_NOT_FOUND`    | The templates you referenced were not found.                                                                                                                            |
| `429`      | `RATE_LIMIT_EXCEEDED`   | `EnterpriseId` is being rate limited.                                                                                                                                   |
| `500`      | `INTERNAL_SERVER_ERROR` | Internal server error.                                                                                                                                                  |
