{
  "schema_version": 2,
  "id": "develop/ai/search-and-query/advanced-concepts/aggregations",
  "title": "Aggregations",
  "url": "https://redis.io/docs/latest/develop/ai/search-and-query/advanced-concepts/aggregations/",
  "summary": "Groupings, projections, and aggregation functions",
  "aliases": [
    "/interact/search-and-query/search/aggregations/",
    "/develop/interact/search-and-query/advanced-concepts/aggregations",
    "/interact/search-and-query/advanced-concepts/aggregations/"
  ],
  "tags": [
    "docs",
    "develop",
    "stack",
    "oss",
    "rs",
    "rc",
    "oss",
    "kubernetes",
    "clients"
  ],
  "last_updated": "2026-10-15T15:16:04-07:00",
  "page_type": "content",
  "content_hash": "dbf37ee0b3f158e4ca280eeb58b3ecaf389a745a6b498620214559360f491e78",
  "sections": [
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "Aggregations are a way to process the results of a search query. Aggregation allows you to group, sort, and transform your result data, and to extract analytic insights from it. Much like aggregation queries in other databases and search engines, they can be used to create analytics reports, or perform [faceted search](https://en.wikipedia.org/wiki/Faceted_search) style queries.\n\nFor example, indexing a web-server's logs, you can create a report for unique users by hour, country, or any other breakdown. Or you can create different reports for errors, warnings, etc."
    },
    {
      "id": "core-concepts",
      "title": "Core concepts",
      "role": "content",
      "text": "The basic idea of an aggregate query is this:\n\n* Perform a search query, filtering for records you wish to process.\n* Build a pipeline of operations that transform the results by zero or more sequences of:\n  * **Group and reduce**: grouping by fields in the results, and applying reducer functions to each group.\n  * **Sort**: sort the results based on one or more fields.\n  * **Apply transformations**: apply mathematical and string functions on fields in the pipeline, optionally creating new fields or replacing existing ones.\n  * **Limit**: limit the result, regardless of how the result is sorted.\n  * **Filter**: filter the results (post-query) based on predicates relating to its values.\n\nThe pipeline is dynamic and re-entrant, and every operation can be repeated. For example, you can group by property X, sort the top 100 results by group size, then group by property Y and sort the results by some other property, then apply a transformation on the output.\n\nFigure 1: Aggregation Pipeline Example\n\n<img src=\"../../img/pipeline.png\">"
    },
    {
      "id": "aggregate-request-format",
      "title": "Aggregate request format",
      "role": "content",
      "text": "The aggregate request's syntax is defined as follows:\n\n[code example]"
    },
    {
      "id": "parameters-in-detail",
      "title": "Parameters in detail",
      "role": "parameters",
      "text": "Parameters that can take a variable number of arguments are expressed in the\nform of `param {nargs} {property_1... property_N}`. The first argument to the\nparameter is the number of arguments following the parameter. This allows\nRedis to avoid a parsing ambiguity in case one of your arguments has the\nname of another parameter. For example, to sort by first name, last name, and\ncountry, one would specify `SORTBY 6 firstName ASC lastName DESC country ASC`.\n\n* **index_name**: The index the query is executed against.\n\n* **query_string**: The base filtering query that retrieves the documents. It follows the exact same syntax as the search query, including filters, unions, not, optional, etc.\n\n* **LOAD {nargs} {property} ...** : Load document fields from the document HASH objects. This should be avoided as a general rule of thumb. Fields needed for aggregations should be stored as SORTABLE (and optionally UNF to avoid any normalization), where they are available to the aggregation pipeline with very low latency. LOAD hurts the performance of aggregate queries considerably since every processed record needs to execute the equivalent of HMGET against a Redis key, which when executed over millions of keys, amounts to very high processing times.\nThe document ID can be loaded using `@__key`.\n\n* **GROUPBY {nargs} {property} ...** : Group the results in the pipeline based on one or more properties. Each group should have at least one reducer (See below), a function that handles the group entries, either counting them or performing multiple aggregate operations (see below).\n\n* **REDUCE {func} {nargs} {arg} ... [AS {name}]**: Reduce the matching results in each group into a single record, using a reduction function. For example, COUNT will count the number of records in the group. See the Reducers section below for more details on available reducers.\n\n    The reducers can have their own property names using the `AS {name}` optional argument. If a name is not given, the resulting name will be the name of the reduce function and the group properties. For example, if a name is not given to COUNT_DISTINCT by property `@foo`, the resulting name will be `count_distinct(@foo)`.\n\n* **SORTBY {nargs} {property} {ASC|DESC} [MAX {num}]**: Sort the pipeline up until the point of SORTBY, using a list of properties. By default, sorting is ascending, but `ASC` or `DESC ` can be added for each property. `nargs` is the number of sorting parameters, including ASC and DESC. for example: `SORTBY 4 @foo ASC @bar DESC`.\n\n    `MAX` is used to optimized sorting, by sorting only for the n-largest elements. Although it is not connected to `LIMIT`, you usually need just `SORTBY … MAX` for common queries.\n\n* **APPLY {expr} AS {name}**: Apply a one-to-one transformation on one or more properties, and either store the result as a new property down the pipeline, or replace any property using this transformation. `expr` is an expression that can be used to perform arithmetic operations on numeric properties, or functions that can be applied on properties depending on their types (see below), or any combination thereof. For example: `APPLY \"sqrt(@foo)/log(@bar) + 5\" AS baz` will evaluate this expression dynamically for each record in the pipeline and store the result as a new property called baz, that can be referenced by further APPLY / SORTBY / GROUPBY / REDUCE operations down the pipeline.\n\n* **LIMIT {offset} {num}**. Limit the number of results to return just `num` results starting at index `offset` (zero based). AS mentioned above, it is much more efficient to use `SORTBY … MAX` if you are interested in just limiting the output of a sort operation.\n\n     However, limit can be used to limit results without sorting, or for paging the n-largest results as determined by `SORTBY MAX`. For example, getting results 50-100 of the top 100 results is most efficiently expressed as `SORTBY 1 @foo MAX 100 LIMIT 50 50`. Removing the MAX from SORTBY will result in the pipeline sorting all the records and then paging over results 50-100.\n\n* **FILTER {expr}**. Filter the results using predicate expressions relating to values in each result. The expressions are applied post-query and relate to the current state of the pipeline. See FILTER Expressions below for full details.\n\n* **PARAMS {nargs} {name} {value}**. Define one or more value parameters. Each parameter has a name and a value. Parameters can be referenced in the query string by a `$`, followed by the parameter name, e.g., `$user`, and each such reference in the search query to a parameter name is substituted by the corresponding parameter value. For example, with parameter definition `PARAMS 4 lon 29.69465 lat 34.95126`, the expression `@loc:[$lon $lat 10 km]` would be evaluated to `@loc:[29.69465 34.95126 10 km]`. Parameters cannot be referenced in the query string where concrete values are not allowed, such as in field names, e.g., `@loc`\n*"
    },
    {
      "id": "example",
      "title": "Example",
      "role": "example",
      "text": "A log of visits to a website might look like the following, each record of which has the following fields/properties:\n\n* **url** (text, sortable)\n* **timestamp** (numeric, sortable) - Unix timestamp of visit entry.\n* **country** (tag, sortable)\n* **user_id** (text, sortable, not indexed)"
    },
    {
      "id": "example-1-unique-users-by-hour-ordered-chronologically",
      "title": "Example 1: unique users by hour, ordered chronologically.",
      "role": "example",
      "text": "The first step is to determine the index name and the filtering query. A filter query of `*` means \"get all records\":\n\n[code example]\n\nNext, group the results by hour. The data contains visit times as unix timestamps in second resolution, so you'll need to extract the hour component of the timestamp. To do so, add an APPLY step that strips the sub-hour information from the timestamp and stores is as a new property, `hour`:\n\n[code example]\n\nNext, group the results by hour and count the distinct user ids in each hour. This is done by a GROUPBY/REDUCE step:\n\n[code example]\n\nNext, sort the results by hour, ascending:\n\n[code example]\n\nAnd as a final step, format the hour as a human readable timestamp. This is done by calling the transformation function `timefmt` that formats Unix timestamps. You can specify a format to be passed to the system's `strftime` function ([see documentation](https://pubs.opengroup.org/onlinepubs/9699919799/functions/strftime.html)), but not specifying one is equivalent to specifying `%FT%TZ` to `strftime`.\n\n[code example]"
    },
    {
      "id": "example-2-sort-visits-to-a-specific-url-by-day-and-country",
      "title": "Example 2: Sort visits to a specific URL by day and country:",
      "role": "example",
      "text": "The next example filters by the url, transforms the timestamp to its day part, and groups by the day and country, counting the number of visits per group, sorting by day ascending and country descending.\n\n[code example]"
    },
    {
      "id": "groupby-reducers",
      "title": "GROUPBY reducers",
      "role": "content",
      "text": "`GROUPBY` works similarly to SQL `GROUP BY` clauses, and creates groups of results based on one or more properties in each record. For each group, Redis returns the group keys, or the values common to all records in the group, and the results of zero or more `REDUCE` clauses.\n\nEach `GROUPBY` step in the pipeline may be accompanied by zero or more `REDUCE` clauses. Reducers apply an accumulation function to each record in the group and reduces them into a single record representing the group. When the processing is complete, all the records upstream of the `GROUPBY` step emit their reduced record.\n\nFor example, the simplest reducer is COUNT, which simply counts the number of records in each group.\n\nIf multiple `REDUCE` clauses exist for a single `GROUPBY` step, each reducer works independently on each result and writes its final output once. Each reducer may have its own alias determined using the `AS` optional parameter. If `AS` is not specified, the alias is the reduce function and its parameters, e.g. `count_distinct(foo,bar)`."
    },
    {
      "id": "supported-groupby-reducers",
      "title": "Supported GROUPBY reducers",
      "role": "compatibility",
      "text": "#### COUNT\n\n**Format**\n\n[code example]\n\n**Description**\n\nCount the number of records in each group\n\n#### COUNT_DISTINCT\n\n**Format**\n\n[code example]`\n\n**Description**\n\nCount the number of distinct values for `property`.\n\n> [!NOTE]\n> The reducer creates a hash-set per group, and hashes each record. This can be memory heavy if the groups are big.\n\n#### COUNT_DISTINCTISH\n\n**Format**\n\n[code example]\n\n**Description**\n\nSame as COUNT_DISTINCT, provides an approximation instead of an exact count, which consumes less memory and CPU for big groups.\n\n> [!NOTE]\n> The reducer uses [HyperLogLog](https://en.wikipedia.org/wiki/HyperLogLog) counters per group, at ~3% error rate, and 1024 bytes of constant space  per group. This means it is ideal for a few huge groups and not ideal for many small groups. In the former case, it can be an order of magnitude faster and consume much less memory than COUNT_DISTINCT, but again, it does not fit every use case.\n\n#### SUM\n\n**Format**\n\n[code example]\n\n**Description**\n\nReturn the sum of all numeric values of a given property in a group. Non-numeric values in the group are counted as 0.\n\n#### MIN\n\n**Format**\n\n[code example]\n\n**Description**\n\nReturn the minimal value of a property, whether it is a string, number, or NULL.\n\n#### MAX\n\n**Format**\n\n[code example]\n\n**Description**\n\nReturn the maximal value of a property, whether it is a string, number or NULL.\n\n#### AVG\n\n**Format**\n\n[code example]\n\n**Description**\n\nReturn the average value of a numeric property. This is equivalent to reducing by sum and count, and later, applying the ratio of them as an APPLY step.\n\n#### STDDEV\n\n**Format**\n\n[code example]\n\n**Description**\n\nReturn the [standard deviation](https://en.wikipedia.org/wiki/Standard_deviation) of a numeric property in the group.\n\n#### QUANTILE\n\n**Format**\n\n[code example]\n\n**Description**\n\nReturn the value of a numeric property at a given quantile of the results. Quantile is expressed as a number between 0 and 1. For example, the median can be expressed as the quantile at 0.5, e.g. `REDUCE QUANTILE 2 @foo 0.5 AS median` .\n\nIf multiple quantiles are required, just repeat the QUANTILE reducer for each quantile. For example, `REDUCE QUANTILE 2 @foo 0.5 AS median REDUCE QUANTILE 2 @foo 0.99 AS p99`.\n\n#### TOLIST\n\n**Format**\n\n[code example]\n\n**Description**\n\nMerge all distinct values of a given property into a single array.\n\n#### FIRST_VALUE\n\n**Format**\n\n[code example]\n\n**Description**\n\nReturn the first or top value of a given property in the group, optionally by comparing it to another property. For example, you can extract the name of the oldest user in the group:\n\n[code example]\n\nIf no `BY` is specified, the first value encountered in the group is returned.\n\nIf you wish to get the top or bottom value in the group sorted by the same value, you are better off using the `MIN/MAX` reducers, but the same effect will be achieved by doing `REDUCE FIRST_VALUE 4 @foo BY @foo DESC`.\n\n#### RANDOM_SAMPLE\n\n**Format**\n\n[code example]\n\n**Description**\n\nPerform a reservoir sampling of the group elements with a given size, and return an array of the sampled items with an even distribution.\n\n#### COLLECT\n\n> [!NOTE]\n> The `COLLECT` reducer was introduced in version 8.8.0.\n\n**Format**\n\n[code example]\n\n**Description**\n\nCollect documents within each group as an array of key-value maps, projecting either all fields currently available in the pipeline or an explicit list of fields, with optional sorting, limiting, and deduplication.\n\n- `FIELDS *` returns all document fields available at the current pipeline stage. This is stage-local: it does not trigger an implicit load and does not reach back to fields from earlier stages that were not preserved as grouping keys or reducer aliases.\n- `FIELDS {num} {field_1} ...` projects a specific list of fields. The special fields `@__key` (document key) and `@__score` (document score) are supported as projectable fields alongside document fields.\n- Fields missing from a document are omitted from that entry (sparse output, with no NULL placeholders).\n- `DISTINCT` (optional) deduplicates entries with identical projected fields, keeping the best representative according to the sort keys. When `DISTINCT` is omitted, all documents are retained including duplicates.\n- `SORTBY` (optional) sorts documents within each group by one or more fields with `ASC`/`DESC`.\n- `LIMIT` (optional) limits the number of documents returned per group. Neither `offset` nor `count` can exceed [`search-max-aggregate-results`](https://redis.io/docs/latest/develop/ai/search-and-query/administration/configuration#search-max-aggregate-results). A larger value returns the error `LIMIT offset exceeds maximum of <N>` or `LIMIT count exceeds maximum of <N>`.\n\nEach collected entry is returned as a key-value map (matching the standard `FT.AGGREGATE` result format). The `COLLECT` output is an array of such maps nested under the alias. For example:\n\n[code example]\n\nFor example, to group movies by genre and collect the top 5 movies per group, sorted by rating in descending order:\n\n[code example]"
    },
    {
      "id": "apply-expressions",
      "title": "APPLY expressions",
      "role": "content",
      "text": "`APPLY` performs a one-to-one transformation on one or more properties in each record. It either stores the result as a new property down the pipeline, or replaces any property using this transformation.\n\nThe transformations are expressed as a combination of arithmetic expressions and built in functions. Evaluating functions and expressions is recursively nested and can be composed without limit. For example: `sqrt(log(foo) * floor(@bar/baz)) + (3^@qaz % 6)` or simply `@foo/@bar`.\n\nIf an expression or a function is applied to values that do not match the expected types, no error is emitted and a NULL value is set as the result.\n\nAPPLY steps must have an explicit alias determined by the `AS` parameter."
    },
    {
      "id": "literals-inside-expressions",
      "title": "Literals inside expressions",
      "role": "content",
      "text": "* Numbers are expressed as integers or floating point numbers, e.g., `2`, `3.141`, and `-34`. `inf` and `-inf` are acceptable as well.\n* Strings are quoted with either single or double quotes. Single quotes are acceptable inside strings quoted with double quotes and vice versa. Punctuation marks can be escaped with backslashes. e.g. `\"foo's bar\"` ,`'foo\\'s bar'`, `\"foo \\\"bar\\\"\"` .\n* Any literal or sub-expression can be wrapped in parentheses to resolve ambiguities of operator precedence."
    },
    {
      "id": "arithmetic-operations",
      "title": "Arithmetic operations",
      "role": "content",
      "text": "For numeric expressions and properties, addition (`+`), subtraction (`-`), multiplication (`*`), division (`/`), modulo (`%`), and power (`^`) are supported. Bitwise logical operators are not supported.\n\nNote that these operators apply only to numeric values and numeric sub-expressions. Any attempt to multiply a string by a number, for instance, will result in a NULL output."
    },
    {
      "id": "list-of-field-apply-functions",
      "title": "List of field APPLY functions",
      "role": "content",
      "text": "| Function | Description                                                  | Example            |\n| -------- | ------------------------------------------------------------ | ------------------ |\n| exists(s)| Checks whether a field exists in a document.                 | `exists(@field)`   |\n| case(condition, if_true, if_false) | If condition is non-zero, return if_true, otherwise return if_false. | `case(exists(@foo), @foo, \"no foo\")` |"
    },
    {
      "id": "list-of-numeric-apply-functions",
      "title": "List of numeric APPLY functions",
      "role": "content",
      "text": "| Function | Description                                                  | Example            |\n| -------- | ------------------------------------------------------------ | ------------------ |\n| log(x)   | Return the logarithm of a number, property or subexpression  | `log(@foo)`        |\n| abs(x)   | Return the absolute number of a numeric expression           | `abs(@foo-@bar)`   |\n| ceil(x)  | Round to the smallest value not less than x                  | `ceil(@foo/3.14)`  |\n| floor(x) | Round to largest value not greater than x                    | `floor(@foo/3.14)` |\n| log2(x)  | Return the logarithm of x to base 2                          | `log2(2^@foo)`     |\n| exp(x)   | Return the exponent of x, e.g., `e^x`                        | `exp(@foo)`        |\n| sqrt(x)  | Return the square root of x                                  | `sqrt(@foo)`       |"
    },
    {
      "id": "list-of-string-apply-functions",
      "title": "List of string APPLY functions",
      "role": "content",
      "text": "| Function                         |                                                              |                                                          |\n| -------------------------------- | ------------------------------------------------------------ | -------------------------------------------------------- |\n| upper(s)                         | Return the uppercase conversion of s                         | `upper('hello world')`                                   |\n| lower(s)                         | Return the lowercase conversion of s                         | `lower(\"HELLO WORLD\")`                                   |\n| startswith(s1,s2)                | Return `1` if s2 is the prefix of s1, `0` otherwise.         | `startswith(@field, \"company\")`                          |\n| contains(s1,s2)                  | Return the number of occurrences of s2 in s1, `0` otherwise. If s2 is an empty string, return `length(s1) + 1`.  | `contains(@field, \"pa\")`                                 |\n| strlen(s)                        | Return the length of s                                       | `strlen(@t)`                                             |\n| substr(s, offset, count)         | Return the substring of s, starting at _offset_ and having _count_ characters. <br />If offset is negative, it represents the distance from the end of the string. <br />If count is -1, it means \"the rest of the string starting at offset\". | `substr(\"hello\", 0, 3)` <br> `substr(\"hello\", -2, -1)`  |\n| format( fmt, ...)                | Use the arguments following `fmt` to format a string. <br />Currently the only format argument supported is `%s` and it applies to all types of arguments. | `format(\"Hello, %s, you are %s years old\", @name, @age)` |\n| matched_terms([max_terms=100])   | Return the query terms that matched for each record (up to 100), as a list. If a limit is specified, Redis will return the first N matches found, based on query order. | `matched_terms()`                                        |\n| split(s, [sep=\",\"], [strip=\" \"]) | Split a string by any character in the string sep, and strip any characters in strip. If only s is specified, it is split by commas and spaces are stripped. The output is an array. | split(\"foo,bar\")                                         |"
    },
    {
      "id": "list-of-datetime-apply-functions",
      "title": "List of date/time APPLY functions",
      "role": "content",
      "text": "| Function            | Description                                                  |\n| ------------------- | ------------------------------------------------------------ |\n| timefmt(x, [fmt])      | Return a formatted time string based on a numeric timestamp value x. <br /> See [strftime](https://pubs.opengroup.org/onlinepubs/9699919799/functions/strftime.html) for formatting options. <br />Not specifying `fmt` is equivalent to `%FT%TZ`. |\n| parsetime(timesharing, [fmt]) | The opposite of timefmt() - parse a time format using a given format string |\n| day(timestamp) | Round a Unix timestamp to midnight (00:00) start of the current day. |\n| hour(timestamp) | Round a Unix timestamp to the beginning of the current hour. |\n| minute(timestamp) | Round a Unix timestamp to the beginning of the current minute. |\n| month(timestamp) | Round a unix timestamp to the beginning of the current month. |\n| dayofweek(timestamp) | Convert a Unix timestamp to the day number (Sunday = 0). |\n| dayofmonth(timestamp) | Convert a Unix timestamp to the day of month number (1 .. 31). |\n| dayofyear(timestamp) | Convert a Unix timestamp to the day of year number (0 .. 365). |\n| year(timestamp) | Convert a Unix timestamp to the current year (e.g. 2018). |\n| monthofyear(timestamp) | Convert a Unix timestamp to the current month (0 .. 11). |"
    },
    {
      "id": "list-of-geo-apply-functions",
      "title": "List of geo APPLY functions",
      "role": "content",
      "text": "| Function | Description                                                  | Example            |\n| -------- | ------------------------------------------------------------ | ------------------ |\n| geodistance(field,field)        | Return distance in meters.    | `geodistance(@field1,@field2)`       |\n| geodistance(field,\"lon,lat\")    | Return distance in meters.    | `geodistance(@field,\"1.2,-3.4\")`     |\n| geodistance(field,lon,lat)      | Return distance in meters.    | `geodistance(@field,1.2,-3.4)`       |\n| geodistance(\"lon,lat\",field)    | Return distance in meters.    | `geodistance(\"1.2,-3.4\",@field)`     |\n| geodistance(\"lon,lat\",\"lon,lat\")| Return distance in meters.    | `geodistance(\"1.2,-3.4\",\"5.6,-7.8\")` |\n| geodistance(\"lon,lat\",lon,lat)  | Return distance in meters.    | `geodistance(\"1.2,-3.4\",5.6,-7.8)`   |\n| geodistance(lon,lat,field)      | Return distance in meters.    | `geodistance(1.2,-3.4,@field)`       |\n| geodistance(lon,lat,\"lon,lat\")  | Return distance in meters.    | `geodistance(1.2,-3.4,\"5.6,-7.8\")`   |\n| geodistance(lon,lat,lon,lat)    | Return distance in meters.    | `geodistance(1.2,-3.4,5.6,-7.8)`     |\n\n[code example]\n\nTo retrieve the distance:\n\n[code example]\n\nNote: the geo field must be preloaded using `LOAD`.\n\nResults can also be sorted by distance:\n\n[code example]\n\nNote: Make sure no location is missing, otherwise the SORTBY will not return any results.\nUse FILTER to make sure you do the sorting on all valid locations."
    },
    {
      "id": "filter-expressions",
      "title": "FILTER expressions",
      "role": "content",
      "text": "FILTER expressions filter the results using predicates relating to values in the result set.\n\nThe FILTER expressions are evaluated post-query and relate to the current state of the pipeline. Thus they can be useful to prune the results based on group calculations. Note that the filters are not indexed and will not speed up processing.\n\nFilter expressions follow the syntax of APPLY expressions, with the addition of the conditions `==`, `!=`, `<`, `<=`, `>`, `>=`. Two or more predicates can be combined with logical AND (`&&`) and OR (`||`). A single predicate can be negated with a NOT prefix (`!`).\n\nFor example, filtering all results where the user name is 'foo' and the age is less than 20 is expressed as:\n\n[code example]\n\nSeveral filter steps can be added, although at the same stage in the pipeline, it is more efficient to combine several predicates into a single filter step."
    },
    {
      "id": "cursor-api",
      "title": "Cursor API",
      "role": "content",
      "text": "[code example]\n\nYou can use cursors with [`FT.AGGREGATE`](https://redis.io/docs/latest/commands/ft.aggregate), with the `WITHCURSOR` keyword. Cursors allow you to\nconsume only part of the response, allowing you to fetch additional results as needed.\nThis is much quicker than using `LIMIT` with offset, since the query is executed only\nonce, and its state is stored on the server.\n\nTo use cursors, specify the `WITHCURSOR` keyword in [`FT.AGGREGATE`](https://redis.io/docs/latest/commands/ft.aggregate). For example:\n\n[code example]\n\nThis will return a response of an array with two elements. The first element is\nthe actual (partial) result, and the second is the cursor ID. The cursor ID\ncan then be fed to [`FT.CURSOR READ`](https://redis.io/docs/latest/commands/ft.cursor-read) repeatedly until the cursor ID is 0, in\nwhich case all results have been returned.\n\nTo read from an existing cursor, use [`FT.CURSOR READ`](https://redis.io/docs/latest/commands/ft.cursor-read). For example:\n\n[code example]\n\nAssuming `342459320` is the cursor ID returned from the [`FT.AGGREGATE`](https://redis.io/docs/latest/commands/ft.aggregate) request, here is an example in pseudo-code:\n\n[code example]\n\nNote that even if the cursor is 0, a partial result may still be returned."
    },
    {
      "id": "cursor-settings",
      "title": "Cursor settings",
      "role": "content",
      "text": "#### Read size\n\nYou can control how many rows are read for each cursor fetch by using the\n`COUNT` parameter. This parameter can be specified both in [`FT.AGGREGATE`](https://redis.io/docs/latest/commands/ft.aggregate)\n(immediately after `WITHCURSOR`) or in [`FT.CURSOR READ`](https://redis.io/docs/latest/commands/ft.cursor-read).\n\nThe following example will read 10 rows at a time:\n[code example]\n\nYou can override this setting by also specifying `COUNT` in `CURSOR READ`. The following example will return at most 50 results:\n\n[code example]\n\nThe default read size is 1000.\n\n#### Timeouts and limits\n\nBecause cursors are stateful resources that occupy memory on the server, they\nhave a limited lifetime. To safeguard against orphaned/stale cursors,\ncursors have an idle timeout value. If no activity occurs on the cursor before\nthe idle timeout, the cursor is deleted. The idle timer resets to 0 whenever\nthe cursor is read from using `CURSOR READ`.\n\nThe default idle timeout is 300000 milliseconds (or 300 seconds). You can modify\nthe idle timeout using the `MAXIDLE` keyword when creating the cursor. Note that\nthe value cannot exceed the default 300s.\n\nFor example, to set a limit of ten seconds:\n\n[code example]\n\nDuring a cursor’s lifetime, CURSOR READ may return results that exclude newer updates.\n\nAlso, note that in case of any load rebalancing operations (such as Atomic Slot Migration) occurring during the lifetime of a cursor, some results may be missing. In a Redis Software deployment, these operations may happen behind the scenes without any user intervention."
    },
    {
      "id": "other-cursor-commands",
      "title": "Other cursor commands",
      "role": "content",
      "text": "Cursors can be explicitly deleted using the `CURSOR DEL` command. For example:\n\n[code example]\n\nNote that cursors are automatically deleted if all their results have been\nreturned, or if they have timed out.\n\nAll idle cursors can be forcefully purged at the same time using `FT.CURSOR GC idx 0` command.\nBy default, Redis uses a lazy throttled approach to garbage collection, which\ncollects idle cursors every 500 operations, or every second, whichever is later."
    }
  ],
  "examples": [
    {
      "id": "aggregate-request-format-ex0",
      "language": "sql",
      "code": "FT.AGGREGATE\n  {index_name:string}\n  {query_string:string}\n  [VERBATIM]\n  [LOAD {nargs:integer} {property:string} ...]\n  [GROUPBY\n    {nargs:integer} {property:string} ...\n    REDUCE\n      {FUNC:string}\n      {nargs:integer} {arg:string} ...\n      [AS {name:string}]\n    ...\n  ] ...\n  [SORTBY\n    {nargs:integer} {string} ...\n    [MAX {num:integer}] ...\n  ] ...\n  [APPLY\n    {EXPR:string}\n    AS {name:string}\n  ] ...\n  [FILTER {EXPR:string}] ...\n  [LIMIT {offset:integer} {num:integer} ] ...\n  [PARAMS {nargs} {name} {value} ... ]",
      "section_id": "aggregate-request-format"
    },
    {
      "id": "example-1-unique-users-by-hour-ordered-chronologically-ex0",
      "language": "plaintext",
      "code": "FT.AGGREGATE myIndex \"*\"",
      "section_id": "example-1-unique-users-by-hour-ordered-chronologically"
    },
    {
      "id": "example-1-unique-users-by-hour-ordered-chronologically-ex1",
      "language": "plaintext",
      "code": "FT.AGGREGATE myIndex \"*\"\n  APPLY \"@timestamp - (@timestamp % 3600)\" AS hour",
      "section_id": "example-1-unique-users-by-hour-ordered-chronologically"
    },
    {
      "id": "example-1-unique-users-by-hour-ordered-chronologically-ex2",
      "language": "plaintext",
      "code": "FT.AGGREGATE myIndex \"*\"\n  APPLY \"@timestamp - (@timestamp % 3600)\" AS hour\n\n  GROUPBY 1 @hour\n  \tREDUCE COUNT_DISTINCT 1 @user_id AS num_users",
      "section_id": "example-1-unique-users-by-hour-ordered-chronologically"
    },
    {
      "id": "example-1-unique-users-by-hour-ordered-chronologically-ex3",
      "language": "plaintext",
      "code": "FT.AGGREGATE myIndex \"*\"\n  APPLY \"@timestamp - (@timestamp % 3600)\" AS hour\n\n  GROUPBY 1 @hour\n  \tREDUCE COUNT_DISTINCT 1 @user_id AS num_users\n\n  SORTBY 2 @hour ASC",
      "section_id": "example-1-unique-users-by-hour-ordered-chronologically"
    },
    {
      "id": "example-1-unique-users-by-hour-ordered-chronologically-ex4",
      "language": "plaintext",
      "code": "FT.AGGREGATE myIndex \"*\"\n  APPLY \"@timestamp - (@timestamp % 3600)\" AS hour\n\n  GROUPBY 1 @hour\n  \tREDUCE COUNT_DISTINCT 1 @user_id AS num_users\n\n  SORTBY 2 @hour ASC\n\n  APPLY timefmt(@hour) AS hour",
      "section_id": "example-1-unique-users-by-hour-ordered-chronologically"
    },
    {
      "id": "example-2-sort-visits-to-a-specific-url-by-day-and-country-ex0",
      "language": "plaintext",
      "code": "FT.AGGREGATE myIndex \"@url:\\\"about.html\\\"\"\n    APPLY \"@timestamp - (@timestamp % 86400)\" AS day\n    GROUPBY 2 @day @country\n    \tREDUCE count 0 AS num_visits\n    SORTBY 4 @day ASC @country DESC",
      "section_id": "example-2-sort-visits-to-a-specific-url-by-day-and-country"
    },
    {
      "id": "supported-groupby-reducers-ex0",
      "language": "plaintext",
      "code": "REDUCE COUNT 0",
      "section_id": "supported-groupby-reducers"
    },
    {
      "id": "supported-groupby-reducers-ex1",
      "language": "`",
      "code": "REDUCE COUNT_DISTINCT 1 {property}",
      "section_id": "supported-groupby-reducers"
    },
    {
      "id": "supported-groupby-reducers-ex2",
      "language": "plaintext",
      "code": "REDUCE COUNT_DISTINCTISH 1 {property}",
      "section_id": "supported-groupby-reducers"
    },
    {
      "id": "supported-groupby-reducers-ex3",
      "language": "plaintext",
      "code": "REDUCE SUM 1 {property}",
      "section_id": "supported-groupby-reducers"
    },
    {
      "id": "supported-groupby-reducers-ex4",
      "language": "plaintext",
      "code": "REDUCE MIN 1 {property}",
      "section_id": "supported-groupby-reducers"
    },
    {
      "id": "supported-groupby-reducers-ex5",
      "language": "plaintext",
      "code": "REDUCE MAX 1 {property}",
      "section_id": "supported-groupby-reducers"
    },
    {
      "id": "supported-groupby-reducers-ex6",
      "language": "plaintext",
      "code": "REDUCE AVG 1 {property}",
      "section_id": "supported-groupby-reducers"
    },
    {
      "id": "supported-groupby-reducers-ex7",
      "language": "plaintext",
      "code": "REDUCE STDDEV 1 {property}",
      "section_id": "supported-groupby-reducers"
    },
    {
      "id": "supported-groupby-reducers-ex8",
      "language": "plaintext",
      "code": "REDUCE QUANTILE 2 {property} {quantile}",
      "section_id": "supported-groupby-reducers"
    },
    {
      "id": "supported-groupby-reducers-ex9",
      "language": "plaintext",
      "code": "REDUCE TOLIST 1 {property}",
      "section_id": "supported-groupby-reducers"
    },
    {
      "id": "supported-groupby-reducers-ex10",
      "language": "plaintext",
      "code": "REDUCE FIRST_VALUE {nargs} {property} [BY {property} [ASC|DESC]]",
      "section_id": "supported-groupby-reducers"
    },
    {
      "id": "supported-groupby-reducers-ex11",
      "language": "plaintext",
      "code": "REDUCE FIRST_VALUE 4 @name BY @age DESC",
      "section_id": "supported-groupby-reducers"
    },
    {
      "id": "supported-groupby-reducers-ex12",
      "language": "plaintext",
      "code": "REDUCE RANDOM_SAMPLE {nargs} {property} {sample_size}",
      "section_id": "supported-groupby-reducers"
    },
    {
      "id": "supported-groupby-reducers-ex13",
      "language": "plaintext",
      "code": "REDUCE COLLECT {nargs}\n    FIELDS ( * | {num_fields} {field_1} [{field_2} ...] )\n    [DISTINCT]\n    [SORTBY {nargs} {@field} [ASC|DESC] [{@field} [ASC|DESC] ...]]\n    [LIMIT {offset} {count}]\n  [AS {alias}]",
      "section_id": "supported-groupby-reducers"
    },
    {
      "id": "supported-groupby-reducers-ex14",
      "language": "plaintext",
      "code": "\"top_fruits\" =>\n    1) \"__key\"    => \"doc_10\"\n       \"__score\"  => \"0.95\"\n       \"fruit\"    => \"apple\"\n       \"color\"    => \"yellow\"\n       \"sweetness\"=> \"6\"\n    2) \"__key\"    => \"doc_1\"\n       \"__score\"  => \"0.82\"\n       \"fruit\"    => \"banana\"\n       \"color\"    => \"yellow\"\n       \"sweetness\"=> \"5\"",
      "section_id": "supported-groupby-reducers"
    },
    {
      "id": "supported-groupby-reducers-ex15",
      "language": "plaintext",
      "code": "FT.AGGREGATE idx:movies \"*\"\n    LOAD *\n    GROUPBY 1 @genre\n      REDUCE COLLECT 10 FIELDS 1 * SORTBY 2 @rating DESC LIMIT 0 5 AS top_movies\n    SORTBY 1 @genre LIMIT 0 50",
      "section_id": "supported-groupby-reducers"
    },
    {
      "id": "list-of-geo-apply-functions-ex0",
      "language": "plaintext",
      "code": "FT.AGGREGATE myIdx \"*\"  LOAD 1 location  APPLY \"geodistance(@location,\\\"-1.1,2.2\\\")\" AS dist",
      "section_id": "list-of-geo-apply-functions"
    },
    {
      "id": "list-of-geo-apply-functions-ex1",
      "language": "plaintext",
      "code": "FT.AGGREGATE myIdx \"*\"  LOAD 1 location  APPLY \"geodistance(@location,\\\"-1.1,2.2\\\")\" AS dist",
      "section_id": "list-of-geo-apply-functions"
    },
    {
      "id": "list-of-geo-apply-functions-ex2",
      "language": "plaintext",
      "code": "FT.AGGREGATE idx \"*\" LOAD 1 @location FILTER \"exists(@location)\" APPLY \"geodistance(@location,-117.824722,33.68590)\" AS dist SORTBY 2 @dist DESC",
      "section_id": "list-of-geo-apply-functions"
    },
    {
      "id": "filter-expressions-ex0",
      "language": "plaintext",
      "code": "FT.AGGREGATE\n  ...\n  FILTER \"@name=='foo' && @age < 20\"\n  ...",
      "section_id": "filter-expressions"
    },
    {
      "id": "cursor-api-ex0",
      "language": "plaintext",
      "code": "FT.AGGREGATE ... WITHCURSOR [COUNT {read size} MAXIDLE {idle timeout}]\nFT.CURSOR READ {idx} {cid} [COUNT {read size}]\nFT.CURSOR DEL {idx} {cid}",
      "section_id": "cursor-api"
    },
    {
      "id": "cursor-api-ex1",
      "language": "plaintext",
      "code": "FT.AGGREGATE idx * WITHCURSOR",
      "section_id": "cursor-api"
    },
    {
      "id": "cursor-api-ex2",
      "language": "plaintext",
      "code": "FT.CURSOR READ idx 342459320",
      "section_id": "cursor-api"
    },
    {
      "id": "cursor-api-ex3",
      "language": "plaintext",
      "code": "response, cursor = FT.AGGREGATE \"idx\" \"redis\" \"WITHCURSOR\";\nwhile (1) {\n  processResponse(response)\n  if (!cursor) {\n    break;\n  }\n  response, cursor = FT.CURSOR read \"idx\" cursor\n}",
      "section_id": "cursor-api"
    },
    {
      "id": "cursor-settings-ex0",
      "language": "plaintext",
      "code": "FT.AGGREGATE idx query WITHCURSOR COUNT 10",
      "section_id": "cursor-settings"
    },
    {
      "id": "cursor-settings-ex1",
      "language": "plaintext",
      "code": "FT.CURSOR READ idx 342459320 COUNT 50",
      "section_id": "cursor-settings"
    },
    {
      "id": "cursor-settings-ex2",
      "language": "plaintext",
      "code": "FT.AGGREGATE idx query WITHCURSOR MAXIDLE 10000",
      "section_id": "cursor-settings"
    },
    {
      "id": "other-cursor-commands-ex0",
      "language": "plaintext",
      "code": "FT.CURSOR DEL idx 342459320",
      "section_id": "other-cursor-commands"
    }
  ]
}
