`Aggregate` queries process the result set to return calculated results. Use `aggregate` queries for groups of objects or the entire result set.

:::accordion{title="Additional information"}
To run an `Aggregate` query, specify the following:

- A target collection to search

- One or more aggregated properties, such as:

  - A meta property
  - An object property
  - The `groupedBy` property

- Select at least one sub-property for each selected property

For details, see [Aggregate](../apis/graphql-aggregate.md).
:::

## Retrieve the `count` meta property

Return the number of objects matched by the query.

:::code-group{sync="languages"}
```python title="Python" {2}
jeopardy = client.collections.use("JeopardyQuestion")
response = jeopardy.aggregate.over_all(total_count=True)

print(response.total_count)
```

```typescript title="JavaScript/TypeScript"
const jeopardy = client.collections.use('JeopardyQuestion');
```

```go title="Go" {5-7}
response, err := client.GraphQL().Aggregate().
  WithClassName("JeopardyQuestion").
  WithFields(graphql.Field{
    Name: "meta",
    Fields: []graphql.Field{
      {Name: "count"},
    },
  }).
  Do(ctx)
```

```java title="Java" {4}
CollectionHandle<Map<String, Object>> jeopardy =
    client.collections.use("JeopardyQuestion");
var response = jeopardy.aggregate.overAll(
    a -> a.includeTotalCount(true)
);

System.out.println(response.totalCount());
```

```csharp title="C#" {3}
var jeopardy = client.Collections.Use("JeopardyQuestion");
var response = await jeopardy.Aggregate.OverAll(
    totalCount: true
);

Console.WriteLine(response.TotalCount);
```

```graphql title="GraphQL"
{
  Aggregate {
    JeopardyQuestion {
      meta {
        count
      }
    }
  }
}
```
:::

:::accordion{title="Example response"}
The output is like this:

```json
{
  "data": {
    "Aggregate": {
      "JeopardyQuestion": [
        {
          "meta": {
            "count": 10000
          }
        }
      ]
    }
  }
}
```
:::

## Aggregate `text` properties

This example counts occurrence frequencies:

:::code-group{sync="languages"}
```python title="Python" {5-9}
from weaviate.classes.query import Metrics

jeopardy = client.collections.use("JeopardyQuestion")
response = jeopardy.aggregate.over_all(
    return_metrics=Metrics("answer").text(
        top_occurrences_count=True,
        top_occurrences_value=True,
        min_occurrences=5  # Threshold minimum count
    )
)

print(response.properties["answer"].top_occurrences)
```

```typescript title="JavaScript/TypeScript"
const jeopardy = client.collections.use('JeopardyQuestion');
```

```go title="Go"
response, err := client.GraphQL().Aggregate().
  WithClassName("JeopardyQuestion").
  WithFields(graphql.Field{
    Name: "answer",
    Fields: []graphql.Field{
      {Name: "count"},
      {Name: "type"},
      {Name: "topOccurrences",
        Fields: []graphql.Field{
          {Name: "occurs"},
          {Name: "value"},
        },
      },
    },
  }).
  Do(ctx)
```

```java title="Java" {4-6}
CollectionHandle<Map<String, Object>> jeopardy =
    client.collections.use("JeopardyQuestion");
var response = jeopardy.aggregate.overAll(
    a -> a.metrics(Aggregate.text("answer",
        m -> m.topOccurrencesValue().topOccurrencesCount().minOccurrences(5) // Threshold minimum count
    ))
);
// TODOπ[g-despot] How to get topOccurences here
System.out.println(response.properties().get("answer"));
```

```csharp title="C#" {3-12}
var jeopardy = client.Collections.Use("JeopardyQuestion");
var response = await jeopardy.Aggregate.OverAll(
    returnMetrics:
    [
        Metrics
            .ForProperty("answer")
            .Text(
                topOccurrencesCount: true,
                topOccurrencesValue: true,
                minOccurrences: 5 // Threshold minimum count
            ),
    ]
);

var answerMetrics = response.Properties["answer"] as Aggregate.Text;
if (answerMetrics != null)
{
    Console.WriteLine(JsonSerializer.Serialize(answerMetrics.TopOccurrences));
}
```

```graphql title="GraphQL" {4-11}
{
  Aggregate {
    JeopardyQuestion {
      answer {
        count
        type
        topOccurrences {
          occurs
          value
        }
      }
    }
  }
}
```
:::

:::accordion{title="Example response"}
The output is like this:

```json
{
  "data": {
    "Aggregate": {
      "JeopardyQuestion": [
        {
          "answer": {
            "count": 10000,
            "topOccurrences": [
              {
                "occurs": 19,
                "value": "Australia"
              },
              {
                "occurs": 18,
                "value": "Hawaii"
              },
              {
                "occurs": 16,
                "value": "Boston"
              },
              {
                "occurs": 15,
                "value": "French"
              },
              {
                "occurs": 15,
                "value": "India"
              }
            ],
            "type": "text"
          }
        }
      ]
    }
  }
}
```
:::

## Aggregate `int` properties

This example shows aggregation with integers.

:::code-group{sync="languages"}
```python title="Python" {5-6}
from weaviate.classes.query import Metrics

jeopardy = client.collections.use("JeopardyQuestion")
response = jeopardy.aggregate.over_all(
    # Use `.number` for floats (`NUMBER` datatype in Weaviate)
    return_metrics=Metrics("points").integer(sum_=True, maximum=True, minimum=True),
)

print(response.properties["points"].sum_)
print(response.properties["points"].minimum)
print(response.properties["points"].maximum)
```

```typescript title="JavaScript/TypeScript"
const jeopardy = client.collections.use('JeopardyQuestion');
```

```go title="Go" {5-7}
response, err := client.GraphQL().Aggregate().
  WithClassName("JeopardyQuestion").
  WithFields(graphql.Field{
    Name: "points",
    Fields: []graphql.Field{
      {Name: "count"},
      {Name: "sum"},
    },
  }).
  Do(ctx)
```

```java title="Java" {4-5}
CollectionHandle<Map<String, Object>> jeopardy =
    client.collections.use("JeopardyQuestion");
var response = jeopardy.aggregate.overAll(
    // Use .number for floats (NUMBER datatype in Weaviate)
    a -> a.metrics(Aggregate.integer("points", m -> m.sum().max().min()))
);

// TODOπ[g-despot] How to get sum, min and max here
System.out.println(response.properties().get("points"));
System.out.println(response.properties().get("points"));
System.out.println(response.properties().get("points"));
```

```csharp title="C#" {3-7}
var jeopardy = client.Collections.Use("JeopardyQuestion");
var response = await jeopardy.Aggregate.OverAll(
    // Use .Number for floats (NUMBER datatype in Weaviate)
    returnMetrics:
    [
        Metrics.ForProperty("points").Integer(sum: true, maximum: true, minimum: true),
    ]
);

var pointsMetrics = response.Properties["points"] as Aggregate.Integer;
if (pointsMetrics != null)
{
    Console.WriteLine($"Sum: {pointsMetrics.Sum}");
    Console.WriteLine($"Max: {pointsMetrics.Maximum}");
    Console.WriteLine($"Min: {pointsMetrics.Minimum}");
}
```

```graphql title="GraphQL" {4-7}
{
  Aggregate {
    JeopardyQuestion {
      points {
        count
        sum
      }
    }
  }
}
```
:::

:::accordion{title="Example response"}
The output is like this:

```json
{
  "data": {
    "Aggregate": {
      "JeopardyQuestion": [
        {
          "points": {
            "count": 10000,
            "sum": 6324100
          }
        }
      ]
    }
  }
}
```
:::

## Aggregate `groupedBy` properties

To group your results, use `groupBy` in the query.

To retrieve aggregate data for each group, use the `groupedBy` properties.

:::code-group{sync="languages"}
```python title="Python" {5}
from weaviate.classes.aggregate import GroupByAggregate

jeopardy = client.collections.use("JeopardyQuestion")
response = jeopardy.aggregate.over_all(
    group_by=GroupByAggregate(prop="round")
)

# print rounds names and the count for each
for group in response.groups:
    print(f"Value: {group.grouped_by.value} Count: {group.total_count}")
```

```typescript title="JavaScript/TypeScript"
const jeopardy = client.collections.use('JeopardyQuestion');
```

```go title="Go" {3-17}
response, err := client.GraphQL().Aggregate().
  WithClassName("JeopardyQuestion").
  WithGroupBy("round").
  WithFields(
    graphql.Field{
      Name: "groupedBy",
      Fields: []graphql.Field{
        {Name: "value"},
      },
    },
    graphql.Field{
      Name: "meta",
      Fields: []graphql.Field{
        {Name: "count"},
      },
    },
  ).
  Do(ctx)
```

```java title="Java" {4}
CollectionHandle<Map<String, Object>> jeopardy =
    client.collections.use("JeopardyQuestion");
var response = jeopardy.aggregate.overAll(
    GroupBy.property("round")
);

// print rounds names and the count for each
for (var group : response.groups()) {
  System.out.printf("Value: %s Count: %d\n", group.groupedBy().value(),
      group.totalCount());
}
```

```csharp title="C#" {3}
var jeopardy = client.Collections.Use("JeopardyQuestion");
var response = await jeopardy.Aggregate.OverAll(
    groupBy: new Aggregate.GroupBy("round")
);

// print rounds names and the count for each
foreach (var group in response.Groups)
{
    Console.WriteLine($"Value: {group.GroupedBy.Value} Count: {group.TotalCount}");
}
```

```graphql title="GraphQL" {3-6}
{
  Aggregate {
    JeopardyQuestion(groupBy: "round") {
      groupedBy {
        value
      }
      meta {
        count
      }
    }
  }
}
```
:::

:::accordion{title="Example response"}
The output is like this:

```json
{
  "data": {
    "Aggregate": {
      "JeopardyQuestion": [
        {
          "groupedBy": {
            "value": "Double Jeopardy!"
          },
          "meta": {
            "count": 5193
          }
        },
        {
          "groupedBy": {
            "value": "Jeopardy!"
          },
          "meta": {
            "count": 4522
          }
        },
        {
          "groupedBy": {
            "value": "Final Jeopardy!"
          },
          "meta": {
            "count": 285
          }
        }
      ]
    }
  }
}
```
:::

:::callout{intent="note" title="`groupBy` limitations"}
- `groupBy` only works with `near<Media>` operators.
- The `groupBy` `path` is limited to one property or cross-reference. Nested paths are not supported.
:::

## Aggregate with a `similarity search`

You can use `Aggregate` with a [similarity search](similarity.md) operator (one of the `Near` operators).

<!-- Make sure to [limit your search results](../apis/graphql-aggregate.md#limiting-the-search-space).<br/> -->

Use `objectLimit` to specify the maximum number of objects to aggregate.

:::code-group{sync="languages"}
```python title="Python" {6}
from weaviate.classes.query import Metrics

jeopardy = client.collections.use("JeopardyQuestion")
response = jeopardy.aggregate.near_text(
    query="animals in space",
    object_limit=10,
    return_metrics=Metrics("points").number(sum_=True),
)

print(response.properties["points"].sum_)
```

```typescript title="JavaScript/TypeScript"
const jeopardy = client.collections.use('JeopardyQuestion');
```

```go title="Go" {5}
response, err := client.GraphQL().Aggregate().
  WithClassName("JeopardyQuestion").
  WithNearText(client.GraphQL().NearTextArgBuilder().
    WithConcepts([]string{"animals in space"})).
  WithObjectLimit(10).
  WithFields(graphql.Field{
    Name: "points",
    Fields: []graphql.Field{
      {Name: "sum"},
    },
  }).
  Do(ctx)
```

```java title="Java" {4}
CollectionHandle<Map<String, Object>> jeopardy =
    client.collections.use("JeopardyQuestion");
var response = jeopardy.aggregate.nearText("animals in space", a -> a
    .distance(0)
    , n -> n.includeTotalCount(false)
        .metrics(Aggregate.number("points", m -> m.sum())));

System.out.println(response.properties().get("points"));
```

```csharp title="C#" {4}
var jeopardy = client.Collections.Use("JeopardyQuestion");
var response = await jeopardy.Aggregate.NearText(
    "animals in space",
    limit: 10,
    returnMetrics: [Metrics.ForProperty("points").Number(sum: true)]
);

var pointsMetrics = response.Properties["points"] as Aggregate.Number;
Console.WriteLine(JsonSerializer.Serialize(pointsMetrics));
```

```graphql title="GraphQL" {7}
{
  Aggregate {
    JeopardyQuestion(
      nearText: {
        concepts: ["animals in space"]
      }
      objectLimit: 10
    ) {
      points {
        sum
      }
    }
  }
}
```
:::

:::accordion{title="Example response"}
The output is like this:

```json
{
  "data": {
    "Aggregate": {
      "JeopardyQuestion": [
        {
          "points": {
            "sum": 4600
          }
        }
      ]
    }
  }
}
```
:::

### Set a similarity `distance`

You can use `Aggregate` with a [similarity search](similarity.md) operator (one of the `Near` operators).

<!-- Make sure to [limit your search results](../apis/graphql-aggregate.md#limiting-the-search-space).<br/> -->

Use `distance` to specify how similar the objects should be.

<!-- If you use `Aggregate` with a [similarity search](similarity.md) operator (one of the `nearXXX` operators), [limit your search results](../apis/graphql-aggregate.md#limiting-the-search-space). To specify how similar the objects should be, use the `distance` operator. -->

:::code-group{sync="languages"}
```python title="Python" {6}
from weaviate.classes.query import Metrics

jeopardy = client.collections.use("JeopardyQuestion")
response = jeopardy.aggregate.near_text(
    query="animals in space",
    distance=0.19,
    return_metrics=Metrics("points").number(sum_=True),
)

print(response.properties["points"].sum_)
```

```typescript title="JavaScript/TypeScript"
const jeopardy = client.collections.use('JeopardyQuestion');
```

```go title="Go" {5}
response, err := client.GraphQL().Aggregate().
  WithClassName("JeopardyQuestion").
  WithNearText(client.GraphQL().NearTextArgBuilder().
    WithConcepts([]string{"animals in space"}).
    WithDistance(0.19)).
  WithFields(graphql.Field{
    Name: "points",
    Fields: []graphql.Field{
      {Name: "sum"},
    },
  }).
  Do(ctx)
```

```java title="Java" {5}
CollectionHandle<Map<String, Object>> jeopardy =
    client.collections.use("JeopardyQuestion");
var response = jeopardy.aggregate.nearText("animals in space",
    a -> a.objectLimit(10)
        //.distance(0.19f)
        .metrics(Aggregate.number("points", m -> m.sum())));

System.out.println(response.properties().get("points"));
```

```csharp title="C#" {4}
var jeopardy = client.Collections.Use("JeopardyQuestion");
var response = await jeopardy.Aggregate.NearText(
    ["animals in space"],
    distance: 0.19,
    returnMetrics: [Metrics.ForProperty("points").Number(sum: true)]
);

var pointsMetrics = response.Properties["points"] as Aggregate.Number;
Console.WriteLine(JsonSerializer.Serialize(pointsMetrics));
```

```graphql title="GraphQL" {4-7}
{
  Aggregate {
    JeopardyQuestion(
      nearText: {
        concepts: ["animals in space"]
        distance: 0.19
      }
    ) {
      points {
        sum
      }
    }
  }
}
```
:::

:::accordion{title="Example response"}
The output is like this:

```json
{
  "data": {
    "Aggregate": {
      "JeopardyQuestion": [
        {
          "points": {
            "sum": 2500
          }
        }
      ]
    }
  }
}
```
:::

## Aggregate with a `hybrid search`

You can use `Aggregate` with a [hybrid search](hybrid.md) operator.

:::code-group{sync="languages"}
```python title="Python" {7}
from weaviate.classes.query import Metrics, BM25Operator

jeopardy = client.collections.use("JeopardyQuestion")
response = jeopardy.aggregate.hybrid(
    query="animals in space",
    bm25_operator=BM25Operator.and_(),  # Additional parameters available, such as `bm25_operator`, `filter` etc.
    object_limit=10,
    return_metrics=Metrics("points").number(sum_=True),
)

print(response.properties["points"].sum_)
```

```typescript title="JavaScript/TypeScript"
const jeopardy = client.collections.use("JeopardyQuestion")

const response = await jeopardy.aggregate.hybrid("animals in space", {
    objectLimit: 10,
    returnMetrics: jeopardy.metrics.aggregate("points").number(["sum"])
})

console.log(response.properties['points'].sum)
```

```go title="Go" {5}
response, err := client.GraphQL().Aggregate().
  WithClassName("JeopardyQuestion").
  WithNearText(client.GraphQL().NearTextArgBuilder().
    WithConcepts([]string{"animals in space"})).
  WithObjectLimit(10).
  WithFields(graphql.Field{
    Name: "points",
    Fields: []graphql.Field{
      {Name: "sum"},
    },
  }).
  Do(ctx)
```

```java title="Java" {7}
CollectionHandle<Map<String, Object>> jeopardy =
    client.collections.use("JeopardyQuestion");
var response = jeopardy.aggregate.hybrid("animals in space", a -> a
    // TODO[g-despot] what about bm25Operator?
    // .bm25Operator(...) // Additional parameters available, such as
    // `bm25_operator`, `filter` etc.
    .objectLimit(10)
    .metrics(Aggregate.number("points", m -> m.sum())));

System.out.println(response.properties().get("points"));
```

```csharp title="C#" {5}
var jeopardy = client.Collections.Use("JeopardyQuestion");
var response = await jeopardy.Aggregate.Hybrid(
    "animals in space",
    // Additional parameters are available, such as `bm25Operator`, `filters`, etc.
    objectLimit: 10,
    returnMetrics: [Metrics.ForProperty("points").Number(sum: true)]
);

var pointsMetrics = response.Properties["points"] as Aggregate.Number;
Console.WriteLine(JsonSerializer.Serialize(pointsMetrics));
```

```graphql title="GraphQL" {11}
{
  Aggregate {
    JeopardyQuestion(
      hybrid: {
        query: "animals in space"
        bm25SearchOperator: {
          operator: Or
          minimumOrTokensMatch: 2
        }
      }
      objectLimit: 10
    ) {
      points {
        sum
      }
    }
  }
}
```
:::

:::accordion{title="Example response"}
The output is like this:

```json
{
  "data": {
    "Aggregate": {
      "JeopardyQuestion": [
        {
          "points": {
            "sum": 6700
          }
        }
      ]
    }
  }
}
```
:::

## Filter results

For more specific results, use a `filter` to narrow your search.

:::code-group{sync="languages"}
```python title="Python" {1,5}
from weaviate.classes.query import Filter

jeopardy = client.collections.use("JeopardyQuestion")
response = jeopardy.aggregate.over_all(
    filters=Filter.by_property("round").equal("Final Jeopardy!"),
)

print(response.total_count)
```

```typescript title="JavaScript/TypeScript"
const jeopardy = client.collections.use('JeopardyQuestion');
```

```go title="Go" {5-8}
// Add this line to imports: "github.com/weaviate/weaviate-go-client/v5/weaviate/filters"

response, err := client.GraphQL().Aggregate().
  WithClassName("JeopardyQuestion").
  WithWhere(filters.Where().
    WithPath([]string{"round"}).
    WithOperator(filters.Equal).
    WithValueString("Final Jeopardy!")).
  WithFields(graphql.Field{
    Name: "meta",
    Fields: []graphql.Field{
      {Name: "count"},
    },
  }).
  Do(ctx)
```

```java title="Java" {5}
// TODO[g-despot] Why is where not available on overAll()?
CollectionHandle<Map<String, Object>> jeopardy =
    client.collections.use("JeopardyQuestion");
var response = jeopardy.aggregate.overAll(a -> a
    // .filters(Filter.property("round").eq("Final Jeopardy!"))
    .includeTotalCount(true));

System.out.println(response.totalCount());
```

```csharp title="C#" {3}
var jeopardy = client.Collections.Use("JeopardyQuestion");
var response = await jeopardy.Aggregate.OverAll(
    filters: Filter.Property("round").IsEqual("Final Jeopardy!"),
    totalCount: true
);

Console.WriteLine(response.TotalCount);
```

```graphql title="GraphQL" {3-7}
{
  Aggregate {
    JeopardyQuestion(where: {
      path: ["round"]
      operator: Equal
      valueText: "Final Jeopardy!"
    }) {
      meta {
        count
      }
    }
  }
}
```
:::

:::accordion{title="Example response"}
The output is like this:

```json
{
  "data": {
    "Aggregate": {
      "JeopardyQuestion": [
        {
          "meta": {
            "count": 285
          }
        }
      ]
    }
  }
}
```
:::

## Related pages

- [Connect to Weaviate](../connect-to-weaviate/index.md)
- [API References: GraphQL: Aggregate](../apis/graphql-aggregate.md)

## Questions and feedback

Have a question or feedback? Here's how to reach us.

::::card-grid
:::card{title="Community Forum" href="https://forum.weaviate.io/c/support" icon="messages-square"}
Ask questions and connect with other developers on our **Community forum**.
:::

:::card{title="Support" href="/guides/support-overview" icon="life-buoy"}
Weaviate Cloud user or customer? Find the right channel on the **Support page**.
:::
::::

## Related pages

- [Agents](./agents-index.md)
- [AI-assisted Weaviate code generation](./ai-assisted-vibe-coding-index.md)
- [APIs](./apis-index.md)
- [Authorization and authentication](./authorization-and-authentication-index.md)
- [Benchmarks](./benchmarks-index.md)
- [Best practices](./best-practices-index.md)
- [Client libraries](./clients-index.md)
- [Client Libraries / SDKs](./client-libraries-index.md)
- [Cloud](./cloud-index.md)
- [Cloud account management](./cloud-account-management-index.md)

# Agent Instructions

This portal answers questions programmatically. To receive a synthesized,
source-cited answer instead of crawling page by page, append the `?ask=`
query parameter to any page URL on this site:

    /guides/quickstart?ask=how+do+I+authenticate

Optional parameters:

- `&goal=<what-you-are-trying-to-do>` steers the answer toward your
  objective (e.g. `&goal=write+a+python+client`).
- `&version=<label>` scopes the answer to a mounted version when the
  portal publishes more than one.

The response is `text/markdown`: the answer followed by a `# Sources` list
of the portal pages it was grounded in. Status codes are the contract:

- `200` — the answer; `402` — the portal owner’s plan or answer credits are
  exhausted (surface this to your operator; do NOT retry); `429` — you are
  rate-limited; back off for the `Retry-After` seconds; `503` — the answer
  lane is temporarily unavailable; fall back to crawling the `.md` pages.

For the full corpus map read `llms.txt` at the site root; for the tool
surface (search + page fetch as MCP tools) see `/mcp`.
