1# RediSearch Aggregations 2 3Aggregations are a way to process the results of a search query, group, sort and transform them - and extract analytic insights from them. 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. 4 5For example, indexing a web-server's logs, we can create a report for unique users by hour, country or any other breakdown; or create different reports for errors, warnings, etc. 6 7## Core concepts 8 9The basic idea of an aggregate query is this: 10 11* Perform a search query, filtering for records you wish to process. 12* Build a pipeline of operations that transform the results by zero or more steps of: 13 * **Group and Reduce**: grouping by fields in the results, and applying reducer functions on each group. 14 * **Sort**: sort the results based on one or more fields. 15 * **Apply Transformations**: Apply mathematical and string functions on fields in the pipeline, optionally creating new fields or replacing existing ones 16 * **Limit**: Limit the result, regardless of sorting the result. 17 * **Filter**: Filter the results (post-query) based on predicates relating to its values. 18 19The 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. 20 21Figure 1: Aggregation Pipeline Example 22![Aggregation Pipeline](https://docs.google.com/drawings/d/e/2PACX-1vRFyP17ingsG86OYNaienojHHA8DwnlVVv67-WlKxv7a7xTJCluWvs3SzXYQSS6QqwB9QZ1vqDuoJ-0/pub?w=518&h=163) 23 24## Aggregate request format 25 26The aggregate request's syntax is defined as follows: 27 28```sql 29FT.AGGREGATE 30 {index_name:string} 31 {query_string:string} 32 [VERBATIM] 33 [LOAD {nargs:integer} {property:string} ...] 34 [GROUPBY 35 {nargs:integer} {property:string} ... 36 REDUCE 37 {FUNC:string} 38 {nargs:integer} {arg:string} ... 39 [AS {name:string}] 40 ... 41 ] ... 42 [SORTBY 43 {nargs:integer} {string} ... 44 [MAX {num:integer}] ... 45 ] ... 46 [APPLY 47 {EXPR:string} 48 AS {name:string} 49 ] ... 50 [FILTER {EXPR:string}] ... 51 [LIMIT {offset:integer} {num:integer} ] ... 52``` 53 54#### Parameters in detail 55 56Parameters which may take a variable number of arguments are expressed in the 57form of `param {nargs} {property_1... property_N}`. The first argument to the 58parameter is the number of arguments following the parameter. This allows 59RediSearch to avoid a parsing ambiguity in case one of your arguments has the 60name of another parameter. For example, to sort by first name, last name, and 61country, one would specify `SORTBY 6 firstName ASC lastName DESC country ASC`. 62 63* **index_name**: The index the query is executed against. 64 65* **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. 66 67* **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. 68The document ID can be loaded using `@__key`. 69 70* **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). 71 72* **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. 73 74 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)`. 75 76* **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`. 77 78 `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. 79 80* **APPLY {expr} AS {name}**: Apply a 1-to-1 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. 81 82* **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. 83 84 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. 85 86* **FILTER {expr}**. Filter the results using predicate expressions relating to values in each result. They are is applied post-query and relate to the current state of the pipeline. See FILTER Expressions below for full details. 87 88## Quick example 89 90Let's assume we have log of visits to our website, each record containing the following fields/properties: 91 92* **url** (text, sortable) 93* **timestamp** (numeric, sortable) - unix timestamp of visit entry. 94* **country** (tag, sortable) 95* **user_id** (text, sortable, not indexed) 96 97### Example 1: unique users by hour, ordered chronologically. 98 99First of all, we want _all_ records in the index, because why not. The first step is to determine the index name and the filtering query. A filter query of `*` means "get all records": 100 101``` 102FT.AGGREGATE myIndex "*" 103``` 104 105Now we want to group the results by hour. Since we have the visit times as unix timestamps in second resolution, we need to extract the hour component of the timestamp. So we first add an APPLY step, that strips the sub-hour information from the timestamp and stores is as a new property, `hour`: 106 107``` 108FT.AGGREGATE myIndex "*" 109 APPLY "@timestamp - (@timestamp % 3600)" AS hour 110``` 111 112Now we want to group the results by hour, and count the distinct user ids in each hour. This is done by a GROUPBY/REDUCE step: 113 114``` 115FT.AGGREGATE myIndex "*" 116 APPLY "@timestamp - (@timestamp % 3600)" AS hour 117 118 GROUPBY 1 @hour 119 REDUCE COUNT_DISTINCT 1 @user_id AS num_users 120``` 121 122Now we'd like to sort the results by hour, ascending: 123 124``` 125FT.AGGREGATE myIndex "*" 126 APPLY "@timestamp - (@timestamp % 3600)" AS hour 127 128 GROUPBY 1 @hour 129 REDUCE COUNT_DISTINCT 1 @user_id AS num_users 130 131 SORTBY 2 @hour ASC 132``` 133 134And as a final step, we can 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](http://strftime.org/)), but not specifying one is equivalent to specifying `%FT%TZ` to `strftime`. 135 136``` 137FT.AGGREGATE myIndex "*" 138 APPLY "@timestamp - (@timestamp % 3600)" AS hour 139 140 GROUPBY 1 @hour 141 REDUCE COUNT_DISTINCT 1 @user_id AS num_users 142 143 SORTBY 2 @hour ASC 144 145 APPLY timefmt(@hour) AS hour 146``` 147 148### Example 2: Sort visits to a specific URL by day and country: 149 150In this example we filter by the url, transform the timestamp to its day part, and group by the day and country, simply counting the number of visits per group. sorting by day ascending and country descending. 151 152``` 153FT.AGGREGATE myIndex "@url:\"about.html\"" 154 APPLY "@timestamp - (@timestamp % 86400)" AS day 155 GROUPBY 2 @day @country 156 REDUCE count 0 AS num_visits 157 SORTBY 4 @day ASC @country DESC 158``` 159 160## GROUPBY reducers 161 162`GROUPBY` step work similarly to SQL `GROUP BY` clauses, and create groups of results based on one or more properties in each record. For each group, we return the "group keys", or the values common to all records in the group, by which they were grouped together - along with the results of zero or more `REDUCE` clauses. 163 164Each `GROUPBY` step in the pipeline may be accompanied by zero or more `REDUCE` clauses. Reducers apply some accumulation function to each record in the group and reduce them into a single record representing the group. When we are finished processing all the records upstream of the `GROUPBY` step, each group emits its reduced record. 165 166For example, the simplest reducer is COUNT, which simply counts the number of records in each group. 167 168If 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)`. 169 170### Supported GROUPBY reducers 171 172#### COUNT 173 174**Format** 175 176``` 177REDUCE COUNT 0 178``` 179 180**Description** 181 182Count the number of records in each group 183 184#### COUNT_DISTINCT 185 186**Format** 187 188```` 189REDUCE COUNT_DISTINCT 1 {property} 190```` 191 192**Description** 193 194Count the number of distinct values for `property`. 195 196!!! note 197 The reducer creates a hash-set per group, and hashes each record. This can be memory heavy if the groups are big. 198 199#### COUNT_DISTINCTISH 200 201**Format** 202 203``` 204REDUCE COUNT_DISTINCTISH 1 {property} 205``` 206 207**Description** 208 209Same as COUNT_DISTINCT - but provide an approximation instead of an exact count, at the expense of less memory and CPU in big groups. 210 211!!! note 212 The reducer uses [HyperLogLog](https://en.wikipedia.org/wiki/HyperLogLog) counters per group, at ~3% error rate, and 1024 Bytes of constant space allocation per group. This means it is ideal for 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 user case. 213 214#### SUM 215 216**Format** 217 218``` 219REDUCE SUM 1 {property} 220``` 221 222**Description** 223 224Return the sum of all numeric values of a given property in a group. Non numeric values if the group are counted as 0. 225 226#### MIN 227 228**Format** 229 230``` 231REDUCE MIN 1 {property} 232``` 233 234**Description** 235 236Return the minimal value of a property, whether it is a string, number or NULL. 237 238#### MAX 239 240**Format** 241 242``` 243REDUCE MAX 1 {property} 244``` 245 246**Description** 247 248Return the maximal value of a property, whether it is a string, number or NULL. 249 250#### AVG 251 252**Format** 253 254``` 255REDUCE AVG 1 {property} 256``` 257 258**Description** 259 260Return the average value of a numeric property. This is equivalent to reducing by sum and count, and later on applying the ratio of them as an APPLY step. 261 262#### STDDEV 263 264**Format** 265 266``` 267REDUCE STDDEV 1 {property} 268``` 269 270**Description** 271 272Return the [standard deviation](https://en.wikipedia.org/wiki/Standard_deviation) of a numeric property in the group. 273 274#### QUANTILE 275 276**Format** 277 278``` 279REDUCE QUANTILE 2 {property} {quantile} 280``` 281 282**Description** 283 284Return 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` . 285 286If multiple quantiles are required, just repeat the QUANTILE reducer for each quantile. e.g. `REDUCE QUANTILE 2 @foo 0.5 AS median REDUCE QUANTILE 2 @foo 0.99 AS p99` 287 288#### TOLIST 289 290**Format** 291 292``` 293REDUCE TOLIST 1 {property} 294``` 295 296**Description** 297 298Merge all **distinct** values of a given property into a single array. 299 300#### FIRST_VALUE 301 302**Format** 303 304``` 305REDUCE FIRST_VALUE {nargs} {property} [BY {property} [ASC|DESC]] 306``` 307 308**Description** 309 310Return the first or top value of a given property in the group, optionally by comparing that or another property. For example, you can extract the name of the oldest user in the group: 311 312``` 313REDUCE FIRST_VALUE 4 @name BY @age DESC 314``` 315 316If no `BY` is specified, we return the first value we encounter in the group. 317 318If you with 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`. 319 320#### RANDOM_SAMPLE 321 322**Format** 323 324``` 325REDUCE RANDOM_SAMPLE {nargs} {property} {sample_size} 326``` 327 328**Description** 329 330Perform a reservoir sampling of the group elements with a given size, and return an array of the sampled items with an even distribution. 331 332## APPLY expressions 333 334`APPLY` performs a 1-to-1 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. 335 336The 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`. 337 338If an expression or a function is applied to values that do not match the expected types, no error is emitted but a NULL value is set as the result. 339 340APPLY steps must have an explicit alias determined by the `AS` parameter. 341 342### Literals inside expressions 343 344* Numbers are expressed as integers or floating point numbers, i.e. `2`, `3.141`, `-34`, etc. `inf` and `-inf` are acceptable as well. 345* 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\""` . 346* Any literal or sub expression can be wrapped in parentheses to resolve ambiguities of operator precedence. 347 348### Arithmetic operations 349 350For numeric expressions and properties, we support addition (`+`), subtraction (`-`), multiplication (`*`), division (`/`), modulo (`%`) and power (`^`). We currently do not support bitwise logical operators. 351 352Note 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. 353 354### List of field APPLY functions 355 356| Function | Description | Example | 357| -------- | ------------------------------------------------------------ | ------------------ | 358| exists(s)| Checks whether a field exists in a document. | `exists(@field)` | 359 360### List of numeric APPLY functions 361 362| Function | Description | Example | 363| -------- | ------------------------------------------------------------ | ------------------ | 364| log(x) | Return the logarithm of a number, property or sub-expression | `log(@foo)` | 365| abs(x) | Return the absolute number of a numeric expression | `abs(@foo-@bar)` | 366| ceil(x) | Round to the smallest value not less than x | `ceil(@foo/3.14)` | 367| floor(x) | Round to largest value not greater than x | `floor(@foo/3.14)` | 368| log2(x) | Return the logarithm of x to base 2 | `log2(2^@foo)` | 369| exp(x) | Return the exponent of x, i.e. `e^x` | `exp(@foo)` | 370| sqrt(x) | Return the square root of x | `sqrt(@foo)` | 371 372### List of string APPLY functions 373 374| Function | | | 375| -------------------------------- | ------------------------------------------------------------ | -------------------------------------------------------- | 376| upper(s) | Return the uppercase conversion of s | `upper('hello world')` | 377| lower(s) | Return the lowercase conversion of s | `lower("HELLO WORLD")` | 378| startswith(s1,s2) | Return `1` if s2 is the prefix of s1, `0` otherwise. | `startswith(@field, "company")` | 379| contains(s1,s2) | Return the number of occurrences of s2 in s1, `0` otherwise. | `contains(@field, "pa")` | 380| 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)` | 381| 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)` | 382| 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, we will return the first N matches we find - based on query order. | `matched_terms()` | 383| 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, we split by commas and strip spaces. The output is an array. | split("foo,bar") | 384 385### List of date/time APPLY functions 386 387| Function | Description | 388| ------------------- | ------------------------------------------------------------ | 389| timefmt(x, [fmt]) | Return a formatted time string based on a numeric timestamp value x. <br /> See [strftime](http://strftime.org/) for formatting options. <br />Not specifying `fmt` is equivalent to `%FT%TZ`. | 390| parsetime(timesharing, [fmt]) | The opposite of timefmt() - parse a time format using a given format string | 391| day(timestamp) | Round a Unix timestamp to midnight (00:00) start of the current day. | 392| hour(timestamp) | Round a Unix timestamp to the beginning of the current hour. | 393| minute(timestamp) | Round a Unix timestamp to the beginning of the current minute. | 394| month(timestamp) | Round a unix timestamp to the beginning of the current month. | 395| dayofweek(timestamp) | Convert a Unix timestamp to the day number (Sunday = 0). | 396| dayofmonth(timestamp) | Convert a Unix timestamp to the day of month number (1 .. 31). | 397| dayofyear(timestamp) | Convert a Unix timestamp to the day of year number (0 .. 365). | 398| year(timestamp) | Convert a Unix timestamp to the current year (e.g. 2018). | 399| monthofyear(timestamp) | Convert a Unix timestamp to the current month (0 .. 11). | 400 401### List of geo APPLY functions 402 403| Function | Description | Example | 404| -------- | ------------------------------------------------------------ | ------------------ | 405| geodistance(field,field) | Return distance in meters. | `geodistance(@field1,@field2)` | 406| geodistance(field,"lon,lat") | Return distance in meters. | `geodistance(@field,"1.2,-3.4")` | 407| geodistance(field,lon,lat) | Return distance in meters. | `geodistance(@field,1.2,-3.4)` | 408| geodistance("lon,lat",field) | Return distance in meters. | `geodistance("1.2,-3.4",@field)` | 409| geodistance("lon,lat","lon,lat")| Return distance in meters. | `geodistance("1.2,-3.4","5.6,-7.8")` | 410| geodistance("lon,lat",lon,lat) | Return distance in meters. | `geodistance("1.2,-3.4",5.6,-7.8)` | 411| geodistance(lon,lat,field) | Return distance in meters. | `geodistance(1.2,-3.4,@field)` | 412| geodistance(lon,lat,"lon,lat") | Return distance in meters. | `geodistance(1.2,-3.4,"5.6,-7.8")` | 413| geodistance(lon,lat,"lon,lat") | Return distance in meters. | `geodistance(1.2,-3.4,5.6,-7.8)` | 414 415``` 416FT.AGGREGATE myIdx "*" LOAD 1 location APPLY "geodistance(@location,\"-1.1,2.2\")" AS dist 417``` 418 419To print out the distance: 420 421``` 422FT.AGGREGATE myIdx "*" LOAD 1 location APPLY "geodistance(@location,\"-1.1,2.2\")" AS dist 423``` 424 425**Note:** Geo field must be preloaded using `LOAD`. 426 427Results can also be sorted by distance: 428 429``` 430FT.AGGREGATE idx "*" LOAD 1 @location FILTER "exists(@location)" APPLY "geodistance(@location,-117.824722,33.68590)" AS dist SORTBY 2 @dist DESC 431``` 432 433**Note:** Make sure no location is missing, otherwise the SORTBY will not return any result. 434Use FILTER to make sure you do the sorting on all valid locations. 435 436## FILTER expressions 437 438FILTER expressions filter the results using predicates relating to values in the result set. 439 440The 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 the processing per se. 441 442Filter 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 (`!`). 443 444For example, filtering all results where the user name is 'foo' and the age is less than 20 is expressed as: 445 446``` 447FT.AGGREGATE 448 ... 449 FILTER "@name=='foo' && @age < 20" 450 ... 451``` 452 453Several 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. 454 455## Cursor API 456 457``` 458FT.AGGREGATE ... WITHCURSOR [COUNT {read size} MAXIDLE {idle timeout}] 459FT.CURSOR READ {idx} {cid} [COUNT {read size}] 460FT.CURSOR DEL {idx} {cid} 461``` 462 463You can use cursors with `FT.AGGREGATE`, with the `WITHCURSOR` keyword. Cursors allow you to 464consume only part of the response, allowing you to fetch additional results as needed. 465This is much quicker than using `LIMIT` with offset, since the query is executed only 466once, and its state is stored on the server. 467 468To use cursors, specify the `WITHCURSOR` keyword in `FT.AGGREGATE`, e.g. 469 470``` 471FT.AGGREGATE idx * WITHCURSOR 472``` 473 474This will return a response of an array with two elements. The first element is 475the actual (partial) results, and the second is the cursor ID. The cursor ID 476can then be fed to `FT.CURSOR READ` repeatedly, until the cursor ID is 0, in 477which case all results have been returned. 478 479To read from an existing cursor, use `FT.CURSOR READ`, e.g. 480 481``` 482FT.CURSOR READ idx 342459320 483``` 484 485Assuming `342459320` is the cursor ID returned from the `FT.AGGREGATE` request. 486 487Here is an example in pseudo-code: 488 489``` 490response, cursor = FT.AGGREGATE "idx" "redis" "WITHCURSOR"; 491while (1) { 492 processResponse(response) 493 if (!cursor) { 494 break; 495 } 496 response, cursor = FT.CURSOR read "idx" cursor 497} 498``` 499 500Note that even if the cursor is 0, a partial result may still be returned. 501 502### Cursor settings 503 504#### Read size 505 506You can control how many rows are read per each cursor fetch by using the 507`COUNT` parameter. This parameter can be specified both in `FT.AGGREGATE` 508(immediately after `WITHCURSOR`) or in `FT.CURSOR READ`. 509 510``` 511FT.AGGREGATE idx query WITHCURSOR COUNT 10 512``` 513 514Will read 10 rows at a time. 515 516You can override this setting by also specifying `COUNT` in `CURSOR READ`, e.g. 517 518``` 519FT.CURSOR READ idx 342459320 COUNT 50 520``` 521 522Will return at most 50 results. 523 524The default read size is 1000 525 526 527#### Timeouts and limits 528 529Because cursors are stateful resources which occupy memory on the server, they 530have a limited lifetime. In order to safeguard against orphaned/stale cursors, 531cursors have an idle timeout value. If no activity occurs on the cursor before 532the idle timeout, the cursor is deleted. The idle timer resets to 0 whenever 533the cursor is read from using `CURSOR READ`. 534 535The default idle timeout is 300000 milliseconds (or 300 seconds). You can modify 536the idle timeout using the `MAXIDLE` keyword when creating the cursor. Note that 537the value cannot exceed the default 300s. 538 539``` 540FT.AGGREGATE idx query WITHCURSOR MAXIDLE 10000 541``` 542 543Will set the limit for 10 seconds. 544 545### Other cursor commands 546 547Cursors can be explicitly deleted using the `CURSOR DEL` command, e.g. 548 549``` 550FT.CURSOR DEL idx 342459320 551``` 552 553Note that cursors are automatically deleted if all their results have been 554returned, or if they have been timed out. 555 556All idle cursors can be forcefully purged at once using `FT.CURSOR GC idx 0` command. 557By default, RediSearch uses a lazy throttled approach to garbage collection, which 558collects idle cursors every 500 operations, or every second - whichever is later. 559