> ## 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>;
};

The Box query insights API lets you calculate summary numbers from your Box content. You can filter items, group results, and compute metrics such as counts, sums, averages, minimums, and maximums.

To get insights, send a `POST` request to `https://api.box.com/2.0/query/insights`.

## Parameters

To make a call, you must pass the following parameters. Mandatory parameters are in **bold**.

| Parameter                     | Type    | Description                                                                                                                                                                                                                                                                      | Example                                                                 |
| ----------------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| **`query`**                   | object  | Defines what items to include and how to group them. Filters are applied first, then grouping, then metric calculation.                                                                                                                                                          | See nested `query.*` parameters                                         |
| **`query.predicate`**         | string  | A filter for your dataset, in SQL-like syntax. Use `:parameter` placeholders for values. See supported operators for [metadata template fields](/guides/metadata/fields/index) and [item properties](/guides/metadata/queries/item-fields).                                      | `enterprise_12345678:book:amount >= :value`                             |
| `query.params`                | object  | Values for each `:placeholder` in the predicate. Required only when the predicate uses placeholders. Each key matches the placeholder name without `:`. Value types must match the predicate fields.                                                                             | `{ "value": 100 }`                                                      |
| `query.ancestors`             | array   | Limits results to items inside specific folders or other ancestors. Each object needs an `id` and `type` (such as `folder`). You need read access to every ancestor listed. If omitted, insights are calculated across all items you can access.                                 | `[{ "id": "123", "type": "folder" }]`                                   |
| `query.group_by`              | array   | How to group results before calculating metrics. Each object defines a field and an optional bucket limit. Only one `group-by` field is supported. Grouping happens after filtering and before metric calculation. Avoid grouping on fields with more than 10,000 unique values. | `[{ "field": "enterprise_12345678:book:category", "bucket_limit": 5 }]` |
| `query.group_by.field`        | string  | The field to group by. Can be a metadata field or an item property. See [supported field types](/guides/metadata/fields/index).                                                                                                                                                  | `enterprise_12345678:book:category`                                     |
| `query.group_by.bucket_limit` | integer | Maximum number of top groups to return. Default is 5. Maximum is 10.                                                                                                                                                                                                             | `5`                                                                     |
| **`metrics`**                 | object  | The metrics you want calculated. Each key is a name you choose. Each value defines the calculation type and field. Metrics are calculated after filtering and grouping.                                                                                                          | See examples below.                                                     |
| `metrics.type`                | string  | The calculation to run. Supported values: `sum`, `avg`, `min`, `max`, `count`.                                                                                                                                                                                                   | `count`                                                                 |
| `metrics.field`               | string  | The field to calculate the metric on.                                                                                                                                                                                                                                            | `enterprise_12345678:product:category`                                  |

### Metric names

Each key in the `metrics` object is a name you choose for that metric.

**Naming rules**

* Must be a non-empty string
* Must be unique in the request
* Maximum length: 256 characters
* Allowed characters: letters, digits, `_`, `-`, and `.`
* Must not start with a digit or special character
* Whitespace and other special characters are not allowed

**Behavior**

If you do not use `group_by`, metrics are calculated across all matching items.

**Limits**

You can define up to 10 metrics per request.

## 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, 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.

**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. Each item is one insight entry with a key, type, and metrics.                                                                                | See below.                                                        |
| `insights.key`               | array  | The grouping values for this entry. Meaning depends on the entry type.                                                                                               | `["Shoe"]`                                                        |
| `insights.key` for `group`   | array  | One value for each `group_by` field.                                                                                                                                 | `["Shoe"]`                                                        |
| `insights.key` for `overall` | array  | Always empty. Means no grouping was used.                                                                                                                            | `[]`                                                              |
| `insights.key` for `other`   | array  | Empty when representing all groups outside the top results.                                                                                                          | All other categories when Shoes and Hats are top groups.          |
| `insights.type`              | string | The kind of result. One of `group`, `overall`, or `other`.                                                                                                           | `group`                                                           |
| `insights.metrics`           | object | The calculated metric values. Keys match the names you defined in the request. For `other` entries, the count of remaining groups is in `totalCountBeyondTopGroups`. | `"metrics": {"totalPrice": {"type": "sum","values": {"sum": 50}}` |

## Error codes

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. |
| `401`      | `UNAUTHORIZED`          | The access token provided is invalid.                                               |
| `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.                                                              |
