Sets
Note
A set is similar to an array, but with two key differences:
The values in a set are automatically deduplicated.
The values in a set are automatically ordered.
Set syntax and casting
A set can be created using the literal syntax {}.
To create a set with zero items or a single item, add a comma.
In addition to the {} literal syntax, an array can be cast into a set.
Casting into a set and back into an array can be a convenient way to deduplicate items in the same way that the array::distinct() and array::sort() functions are used.
Using the index operator on sets
The [] index operator can be used on a set in the same manner as an array. Note however that due to a set's automatic ordering, its individual values are technically not assigned an index. This can be seen in the following example in which [0] for an array will return whichever item happens to be at that location, while for a set [0] will automatically be the item with the least value.
Filtering and mapping with set functions
SurrealDB also includes a number of methods for sets 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 set::filter() method being used. 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.
Adding sets
An set can be added to another set or array, resulting in a single set consisting of the items of the first followed by those of the second.