Working with types
This page contains a number of examples and tips for working with various data types that go beyond the general API documentation for each type.
For general information on these data types, see the data types page in the query language documentation.
Arrays
Working with arrays is one of the most important skills when working with 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.
This also means that a SELECT statement used to fetch records from a datastore can be used unchanged for any other array of values.
Other syntax can be used to achieve the same result, such as pulling from a range of indexes.
Type safety and type conversion
Using typed LET statements
Using typed LET statements is a good practice when prototyping code or when getting used to SurrealQL for the first time. Take the following example that attempts to count the number of true values in a field by filtering out values that are not true, without noticing that the field actually contains strings instead of booleans. The query output ends up being 0, rather than the expected 2.
Breaking this into multiple typed LET statements shows the error right away.
With the location of the error in clear sight, a fix is that much easier to implement.
Mapping items in an array
The array::map() function provides access to each item in an array, allowing an opearation to be performed on it before being passed on. Other similar functions can also be used, such as array::filter() which passes on an array that only contains the items that return true to an expression of your choice.
The following example shows how to chain these functions to validate and modify data in a single statement. The example below removes any items with a NONE, checks to see if a the location data is a valid geometric point, and then returns the remaining items as objects with a different structure.
Files
Using files for ad-hoc memory storage
A combination of files and SurrealDB's encoding functions can be used to set up ad-hoc memory storage. This can be convenient when running an instance that saves data to disk but prefers to keep certain items in memory.
The following example shows how this pattern might be used for temporary storage such as a user's shopping cart during a single session.
Geometry types
The following example includes five records from an open database with cities worldwide that have of a population of at least 1000. The queries below create a city record from each entry that includes their name, location, and name. Next, it uses the geo::distance function to find their two closest neighbours, relating them via the close_to relation table. The final query can be viewed in traditional form to see each city's neighbours, or on Surrealist's graph view to see a visual representation of the network of closely linked cities.