An array is a collection of values contained inside [] (square brackets), each of which is stored at a certain index. Individual indexes and slices of indexes can be accessed using the same square bracket syntax.
Arrays are frequently encountered in SurrealDB, as SELECT statements return an array of values by default unless the ONLY keyword is used on an array that contains a single item.
Records in SurrealDB can store arrays of values, including arrays within arrays. Arrays can store any value stored within them, and can store different value types within the same array.
A required number of items can be specified for an array.
Mapping and filtering on arrays
The [] operator after an array can also be used to filter the items inside an array. The parameter $this is used to refer to each individual item, while WHERE (or its alias ?, a question mark) is used to set the condition for the item to pass the filter.
If a WHERE or ? clause finds an item that by itself is not equal to true or false, it will check the item's truthiness to determine whether to pass it on or not.
Filtering can be repeated if desired.
Filtering and mapping with array functions
SurrealDB also includes a number of methods for arrays that make it easier to filter and map. These methods take a closure (an anonymous function) that works in a similar way to the $this parameter above.
Here is an example of the array::filter() method being used in contrast to the classic WHERE syntax. Note that the parameter name inside the closure is named by the user, so $val in the example below could be $v or $some_val or anything else.
While the array functions section of the documentation contains the full details of each function, the following examples provide a glimpse into how they are commonly used.
The array::map() function provides access to each item in an array, allowing an opearation to be performed on it before being passed on.
If desired, a second parameter can be passed in that holds the index of the item.
Adding arrays
An array can be added to another array, resulting in a single array consisting of the items of the first followed by those of the second. This is identical to the array::concat() function.