Data types

FQL uses an enhanced Javascript Object Notation (JSON) format for storing and communicating data. JSON is a human and machine-readable open standard that facilitates data interchange. All of JSON’s scalar types are supported, including Number, String, Boolean values, as well as Array and Object.

Scalar types

Boolean

The boolean data type only stores true or false values. These can be directly compared for equality or inequality. They can also be compared to the boolean literal values of true and false.

{ my_boolean: true }

Null

Null is a special marker used to indicate that a data value does not exist. It is a representation of missing information, indicating a lack of a value. A lack of a value is not the same thing as a value of zero, in the same way that a lack of an answer is not the same thing as an answer of "no".

Null is a value that can be directly compared for application programmer simplicity.
This means that Null == Null returns true.

{ my_null: null }

Number

Numbers can be 64-bit signed two’s complement integers (long ints), or 64-bit double-precision floating point values (doubles); the representation is controlled, or influenced, by a driver’s host language.

Valid numbers include 3, -27, 3.1415. Neither infinity nor NaN are allowed.

JavaScript does not distinguish between integer and floating point numbers as you might expect, storing numbers as floats internally, and treating them as integers in many contexts.

If your client applications involve JavaScript, or you are using the Web Shell or fauna-shell (which are both implement in JavaScript), and your queries depend on the distinction between integers and floats, be sure to use the conversion functions ToDouble and ToInteger as necessary.

Functions that operate on numbers:

Abs

Returns the absolute value of a number.

Acos

Returns the arc cosine of a number.

Add

Returns the sum of one or more numbers.

Asin

Returns the arc sine of a number.

Atan

Returns the arc tangent of a number.

BitAnd

Returns the bitwise AND of one or more numbers.

BitNot

Returns the bitwise AND of one or more numbers.

BitOr

Returns the bitwise OR of one or more numbers.

BitXor

Returns the bitwise exclusive-OR of one or more numbers.

Ceil

Returns an integer that is greater than, or equal to, a number.

Cos

Returns the cosine of a number.

Cosh

Returns the hyperbolic cosine of a number.

Count

Counts the items in an array or set.

Degrees

Converts a number from radians to degrees.

Divide

Returns the quotient of two or more numbers.

Exp

Returns e raised to the power of a number.

Floor

Returns an integer that is less than, or equal to, a number.

Hypot

Returns the length of a hypotenuse of a right triangle, given the lengths of the other two sides.

Ln

Returns the natural logarithm (base e) of a number.

Log

Returns the natural logarithm (base 10) of a number.

Max

Returns the largest value in a list of numbers.

Mean

Returns the average value of the items in an array or set.

Min

Returns the smallest value in a list of numbers.

Modulo

Returns the remainder after dividing a list of numbers.

Multiply

Returns the product of a list of numbers.

Pow

Returns the value of a number raised to an exponent.

Radians

Converts a number from degrees to radians.

Round

Returns the integer that is closest to a number.

Sign

Returns 1, 0, or -1 to indicate the sign of a number.

Sin

Returns the sine of a number.

Sinh

Returns the hyperbolic sine of a number.

Sqrt

Returns the square root of a number.

Subtract

Returns the difference of a list of numbers.

Sum

Sums the items in an array or set.

Tan

Returns the tangent of a number.

Tanh

Returns the hyperbolic tangent of a number.

Trunc

Truncates a number to the specified decimal places.

String

String data types store any letters, numbers, whitespaces, and/or symbols in a fixed order.

FQL accepts and communicates strings as UTF-8 encoded strings. For string functions, any arguments or returned values which utilize offsets and lengths operate using code points.

Functions that operate on strings:

Casefold

Converts a string into a case-normalized string.

Concat

Combines a list of strings into a single string.

ContainsStr

Tests whether a string contains a specific string.

ContainsStrRegex

Tests whether a string contains a specific pattern.

EndsWith

Tests whether a string ends with a specific string.

FindStr

Searches for a string within a string.

FindStrRegex

Searches for a regex pattern within a string.

Format

Formats arguments as a string according to a string of format specifiers.

LTrim

Removes all whitespace from the start of a string.

Length

Returns the length in codepoints of a string.

LowerCase

Converts a string to all lowercase.

RTrim

Removes all whitespace from the end of a string.

RegexEscape

Creates a regular expression that matches the input string verbatim.

Repeat

Creates a new string by repeating a string multiple times.

ReplaceStr

Replaces a portion of a string with another string.

ReplaceStrRegex

Replaces a pattern in a string with another string.

Space

Creates a whitespace string of the specified size.

StartsWith

Tests whether a string starts with a specific string.

SubString

Returns a portion of a string.

TitleCase

Converts a string to use TitleCase.

Trim

Removes all whitespace from the start and end of a string.

UpperCase

Converts a string to all uppercase.

Literal

A literal is a constant value for a given data type. Boolean, Number, String, and Null all evaluate to their associated type:

true, false   // Boolean
1, 2          // Number
3.4, 1.2e10   // Number
"a", "b"      // String
null          // Null

Array

An Array is a data structure that contains a group of elements. When an Array is used in FQL, it evaluates to its contents.

try
{
    Value result = await client.Query(
        Arr(1, 2, Concat(Arr("Hen ", "Wen")))
    );
    Console.WriteLine(result);
}
catch (Exception e)
{
    Console.WriteLine($"ERROR: {e.Message}");
}
Arr(LongV(1), LongV(2), StringV(Hen Wen))
result, err := client.Query(
	f.Arr{
		1, 2, f.Concat(f.Arr{"Hen ", "Wen"}),
	})

if err != nil {
	fmt.Fprintln(os.Stderr, err)
} else {
	fmt.Println(result)
}
[1 2 Hen Wen]
System.out.println(
    client.query(
        Arr(
            Value(1),
            Value(2),
            Concat(Arr(Value("Hen "), Value("Wen")))
        )
    ).get());
[1, 2, "Hen Wen"]
client.query(
  [1, 2, q.Concat(['Hen ', 'Wen'])]
)
.then((ret) => console.log(ret))
.catch((err) => console.error(
  'Error: [%s] %s: %s',
  err.name,
  err.message,
  err.errors()[0].description,
))
[ 1, 2, 'Hen Wen' ]
result = client.query(
  [1, 2, q.concat(["Hen ", "Wen"])]
)
print(result)
[ 1, 2, "Hen Wen" ]
[1, 2, Concat(['Hen ', 'Wen'])]
[ 1, 2, 'Hen Wen' ]
Query metrics:
  •    bytesIn:  31

  •   bytesOut:  28

  • computeOps:   1

  •    readOps:   0

  •   writeOps:   0

  •  readBytes:   0

  • writeBytes:   0

  •  queryTime: 5ms

  •    retries:   0

Functions that operate on arrays:

All

Tests whether all of the provided values are true.

Any

Tests whether any of the provided values are true.

Append

Adds items to end of array.

Count

Counts the items in an array or set.

Difference

Returns an array of items in one array that are missing from additional arrays.

Distinct

Returns an array of the distinct items within an array.

Drop

Removes items from start of array.

Filter

Fetches specific items from array.

Foreach

Iterates over array items.

Intersection

Returns an array of the items that exist in all arrays.

IsEmpty

Tests whether an array or set is empty.

IsNonEmpty

Tests whether an array or set contains items.

Map

Applies a function to all array items.

Max

Returns the largest value in a list of numbers.

Mean

Returns the average value of the items in an array or set.

Min

Returns the smallest value in a list of numbers.

Prepend

Adds items to start of array.

Reduce

Reduce an array or set to a result via a lambda function.

Reverse

Reverses the order of the items in an array.

Select

Retrieves a specific field value from a document.

Sum

Sums the items in an array or set.

Take

Fetches items from start of array.

ToObject

Converts an array to an object.

Union

Returns an array that combines the items in multiple arrays.

Object

The Object type represents a JSON-like object, where its contents are a collection of key/value pairs. The keys must be strings and the values must be valid FQL data types. The value expressions are evaluated sequentially in the order that they were specified, left to right. Objects evaluate to their contents:

try
{
    Value result = await client.Query(
        Obj("name", "Hen Wen", "age", Add(100, 10))
    );
    Console.WriteLine(result);
}
catch (Exception e)
{
    Console.WriteLine($"ERROR: {e.Message}");
}
ObjectV(name: StringV(Hen Wen),age: LongV(110))
result, err := client.Query(
	f.Obj{"name": "Hen Wen", "age": f.Add(100, 10)})

if err != nil {
	fmt.Fprintln(os.Stderr, err)
} else {
	fmt.Println(result)
}
map[age:110 name:Hen Wen]
System.out.println(
    client.query(
        Obj(
            "name", Value("Hen Wen"),
            "age", Add(Value(100), Value(10))
        )
    ).get());
{name: "Hen Wen", age: 110}
client.query(
  { name: 'Hen Wen', age: q.Add(100, 10) }
)
.then((ret) => console.log(ret))
.catch((err) => console.error(
  'Error: [%s] %s: %s',
  err.name,
  err.message,
  err.errors()[0].description,
))
{ name: 'Hen Wen', age: 110 }
result = client.query(
  {
    "name": "Hen Wen",
    "age": q.add(100, 10)
  }
)
print(result)
{ "name": "Hen Wen", "age": 110 }
The Shell version of this example is not currently available.
Query metrics:
  •    bytesIn:  52

  •   bytesOut:  41

  • computeOps:   1

  •    readOps:   0

  •   writeOps:   0

  •  readBytes:   0

  • writeBytes:   0

  •  queryTime: 4ms

  •    retries:   0

Functions that operate on objects:

Merge

Merge two objects into one, with an optional resolver lambda.

Select

Retrieves a specific field value from a document.

ToArray

Converts an object to an array.

Special types

In addition to the basic types, FQL supports the following types beyond those native to JSON:

Byte

The Bytes type denotes a Base64-encoded string representing a byte array.

try
{
    Value result = await client.Query(
        new byte[] { 0x1, 0x2, 0x3 }
    );
    Console.WriteLine(result);
}
catch (Exception e)
{
    Console.WriteLine($"ERROR: {e.Message}");
}
BytesV(0x01, 0x02, 0x03)
result, err := client.Query(
	f.BytesV{0x1, 0x2, 0x3})

if err != nil {
	fmt.Fprintln(os.Stderr, err)
} else {
	fmt.Println(result)
}
[1 2 3]
System.out.println(
    client.query(
        Value(new byte[]{ 0x1, 0x2, 0x3 })
    ).get());
[0x01 0x02 0x03]
client.query(
  new Uint8Array([0x1, 0x2, 0x3])
)
.then((ret) => console.log(ret))
.catch((err) => console.error(
  'Error: [%s] %s: %s',
  err.name,
  err.message,
  err.errors()[0].description,
))
Bytes("AQID")
result = client.query(
  bytearray(b'\x01\x02\x03')
)
print(result)
bytearray(b'\x01\x02\x03')
new Uint8Array([0x1, 0x2, 0x3])
{ '0': 1, '1': 2, '2': 3 }
Query metrics:
  •    bytesIn:  17

  •   bytesOut:  30

  • computeOps:   1

  •    readOps:   0

  •   writeOps:   0

  •  readBytes:   0

  • writeBytes:   0

  •  queryTime: 2ms

  •    retries:   0

Date

The Date type denotes a date, with no associated time zone.

try
{
    Value result = await client.Query(
        Date("1970-01-01")
    );
    Console.WriteLine(result);
}
catch (Exception e)
{
    Console.WriteLine($"ERROR: {e.Message}");
}
FaunaDate(1970-01-01 12:00:00 AM)
result, err := client.Query(
	f.Date("1970-01-01"))

if err != nil {
	fmt.Fprintln(os.Stderr, err)
} else {
	fmt.Println(result)
}
{0 62135596800 <nil>}
System.out.println(
    client.query(
        Date(Value("1970-01-01"))
    ).get());
1970-01-01
client.query(
  q.Date('1970-01-01')
)
.then((ret) => console.log(ret))
.catch((err) => console.error(
  'Error: [%s] %s: %s',
  err.name,
  err.message,
  err.errors()[0].description,
))
Date("1970-01-01")
result = client.query(
  q.date("1970-01-01")
)
print(result)
1970-01-01
Date('1970-01-01')
Date("1970-01-01")
Query metrics:
  •    bytesIn:  21

  •   bytesOut:  35

  • computeOps:   1

  •    readOps:   0

  •   writeOps:   0

  •  readBytes:   0

  • writeBytes:   0

  •  queryTime: 2ms

  •    retries:   0

Functions that operate on times or dates:

Date

Converts an ISO-8601 string into a Date.

DayOfMonth

Returns the day of the month from a timestamp.

DayOfWeek

Returns the day of the week from a timestamp.

DayOfYear

Returns the day of the year from a timestamp.

Epoch

Creates a timestamp from an offset since 1970-01-01 in seconds, milliseconds, microseconds, or nanoseconds.

Hour

Returns the hour from a timestamp.

Minute

Returns the minute from a timestamp.

Month

Returns the month from a timestamp.

Now

Returns a timestamp representing the current transaction time.

Second

Returns the second from a timestamp.

Time

Converts now, or an ISO-8601 string, into a timestamp.

TimeAdd

Adds an offset to a provided timestamp/date.

TimeDiff

Returns the difference between two timestamps/dates, in specified units.

TimeSubtract

Subtracts an offset from a provided timestamp/date.

Year

Returns the year from a timestamp.

Page

A Page has an array of results and other decorated elements. In some cases the whole result set may not fit into the array, so other fields (the cursor fields) allow you to walk the results set in blocks (like pages in a book). The cursor fields retrieve blocks of results before or after the current page of results. When Pages are passed to functions that accept arrays, only the array element of the Page is examined or transformed. Other elements of the Page, such as the cursor, remain unaffected and are passed directly through to the output.

Field Type Description

data

The elements in the page.

after

The cursor for the next page, inclusive. Optional.

before

The cursor for the previous page, exclusive. Optional.

Functions that operate on pages:

All

Tests whether all of the provided values are true.

Any

Tests whether any of the provided values are true.

Append

Adds items to end of array.

Count

Counts the items in an array or set.

Difference

Returns an array of items in one array that are missing from additional arrays.

Distinct

Returns an array of the distinct items within an array.

Drop

Removes items from start of array.

Filter

Fetches specific items from array.

Foreach

Iterates over array items.

Intersection

Returns an array of the items that exist in all arrays.

IsEmpty

Tests whether an array or set is empty.

IsNonEmpty

Tests whether an array or set contains items.

Map

Applies a function to all array items.

Max

Returns the largest value in a list of numbers.

Mean

Returns the average value of the items in an array or set.

Min

Returns the smallest value in a list of numbers.

Prepend

Adds items to start of array.

Reduce

Reduce an array or set to a result via a lambda function.

Reverse

Reverses the order of the items in an array.

Select

Retrieves a specific field value from a document.

Sum

Sums the items in an array or set.

Take

Fetches items from start of array.

ToObject

Converts an array to an object.

Union

Returns an array that combines the items in multiple arrays.

Query

The Query type denotes a query expression object, and represents any valid FQL query expression.

Reference

The Reference type (or simply Ref) is a unique identifier for a document in a particular database. A Reference serves the same purpose as a foreign key in a traditional relational database. However, given Fauna’s schemaless nature, there is no enforcement that a Ref must point to an existing document.

Each Reference is a compound value, composed of:

  • a reference to the collection containing the document: either a user-defined collection, or a system schema collection, such as Tokens.

  • a document ID: a string-encoded 64-bit integer. Note that References to system schema collections do not have document IDs; the name of the system schema collection is its unique identifier.

Together, the collection reference and the document ID refer to a distinct document: no two documents in a database can share the same reference.

For example:

Ref(Collection("users"), "12345")

When creating a document, if you do not specify a document ID (by using the Ref function), a synthetic document ID is generated. Synthetic document ID generation is based on the Snowflake ID algorithm.

References may be extracted from documents, or constructed using the Collection, Database, Function, Index, or Role functions, or the general-purpose Ref function.

try
{
    Value result = await client.Query(
        Select("ref", Get(Collection("spells")))
    );
    Console.WriteLine(result);
}
catch (Exception e)
{
    Console.WriteLine($"ERROR: {e.Message}");
}
RefV(id = "spells", collection = RefV(id = "collections"))
result, err := client.Query(
	f.Select("ref", f.Get(f.Collection("spells"))))

if err != nil {
	fmt.Fprintln(os.Stderr, err)
} else {
	fmt.Println(result)
}
{spells 0xc00008e300 0xc00008e300 <nil>}
System.out.println(
    client.query(
        Select(Value("ref"), Get(Collection("spells")))
    ).get());
ref(id = "spells", collection = ref(id = "collections"))
client.query(
  q.Select('ref', q.Get(q.Collection('spells')))
)
.then((ret) => console.log(ret))
.catch((err) => console.error(
  'Error: [%s] %s: %s',
  err.name,
  err.message,
  err.errors()[0].description,
))
Collection("spells")
result = client.query(
  q.select("ref", q.get(q.collection("spells")))
)
print(result)
Ref(id=spells, collection=Ref(id=collections))
Select('ref', Get(Collection('spells')))
Collection("spells")
Query metrics:
  •    bytesIn:   55

  •   bytesOut:   80

  • computeOps:    1

  •    readOps:    1

  •   writeOps:    0

  •  readBytes:   70

  • writeBytes:    0

  •  queryTime: 11ms

  •    retries:    0

try
{
    Value result = await client.Query(
        Ref(Collection("spells"), "1")
    );
    Console.WriteLine(result);
}
catch (Exception e)
{
    Console.WriteLine($"ERROR: {e.Message}");
}
RefV(id = "1", collection = RefV(id = "spells", collection = RefV(id = "collections")))
result, err := client.Query(
	f.Ref(f.Collection("spells"), "1"))

if err != nil {
	fmt.Fprintln(os.Stderr, err)
} else {
	fmt.Println(result)
}
{1 0xc000164150 0xc000164150 <nil>}
System.out.println(
    client.query(
        Ref(Collection("spells"), Value(1))
    ).get());
ref(id = "1", collection = ref(id = "spells", collection = ref(id = "collections")))
client.query(
  q.Ref(q.Collection('spells'), '1')
)
.then((ret) => console.log(ret))
.catch((err) => console.error(
  'Error: [%s] %s: %s',
  err.name,
  err.message,
  err.errors()[0].description,
))
Ref(Collection("spells"), "1")
result = client.query(
  q.ref(q.collection("spells"), "1")
)
print(result)
Ref(id=1, collection=Ref(id=spells, collection=Ref(id=collections)))
Ref(Collection('spells'), '1')
Ref(Collection("spells"), "1")
Query metrics:
  •    bytesIn:  40

  •   bytesOut: 113

  • computeOps:   1

  •    readOps:   0

  •   writeOps:   0

  •  readBytes:   0

  • writeBytes:   0

  •  queryTime: 3ms

  •    retries:   0

To access the collection Reference within a Reference:

try
{
    Value result = await client.Query(
        Select("collection", Ref(Collection("spells"), "1"))
    );
    Console.WriteLine(result);
}
catch (Exception e)
{
    Console.WriteLine($"ERROR: {e.Message}");
}
RefV(id = "spells", collection = RefV(id = "collections"))
result, err := client.Query(
	f.Select("collection", f.Ref(f.Collection("spells"), "1")))

if err != nil {
	fmt.Fprintln(os.Stderr, err)
} else {
	fmt.Println(result)
}
{spells 0xc000092480 0xc000092480 <nil>}
System.out.println(
    client.query(
        Select(
            Value("collection"),
            Ref(Collection("spells"), Value(1))
        )
    ).get());
ref(id = "spells", collection = ref(id = "collections"))
client.query(
  q.Select('collection', q.Ref(q.Collection('spells'), '1'))
)
.then((ret) => console.log(ret))
.catch((err) => console.error(
  'Error: [%s] %s: %s',
  err.name,
  err.message,
  err.errors()[0].description,
))
Collection("spells")
result = client.query(
  q.select("collection", q.ref(q.collection("spells"), "1"))
)
print(result)
Ref(id=spells, collection=Ref(id=collections))
Select("collection", Ref(Collection('spells'), '1'))
Collection("spells")
Query metrics:
  •    bytesIn:  71

  •   bytesOut:  80

  • computeOps:   1

  •    readOps:   0

  •   writeOps:   0

  •  readBytes:   0

  • writeBytes:   0

  •  queryTime: 5ms

  •    retries:   0

To access the document ID within a Reference:

try
{
    Value result = await client.Query(
        Select("id", Ref(Collection("spells"), "1"))
    );
    Console.WriteLine(result);
}
catch (Exception e)
{
    Console.WriteLine($"ERROR: {e.Message}");
}
StringV(1)
result, err := client.Query(
	f.Select("id", f.Ref(f.Collection("spells"), "1")))

if err != nil {
	fmt.Fprintln(os.Stderr, err)
} else {
	fmt.Println(result)
}
1
System.out.println(
    client.query(
        Select(
            Value("id"),
            Ref(Collection("spells"), Value(1))
        )
    ).get());
"1"
client.query(
  q.Select('id', q.Ref(q.Collection('spells'), '1'))
)
.then((ret) => console.log(ret))
.catch((err) => console.error(
  'Error: [%s] %s: %s',
  err.name,
  err.message,
  err.errors()[0].description,
))
1
result = client.query(
  q.select("id", q.ref(q.collection("spells"), "1"))
)
print(result)
1
Select("id", Ref(Collection('spells'), '1'))
'1'
Query metrics:
  •    bytesIn:  63

  •   bytesOut:  16

  • computeOps:   1

  •    readOps:   0

  •   writeOps:   0

  •  readBytes:   0

  • writeBytes:   0

  •  queryTime: 3ms

  •    retries:   0

Set

The Set type denotes a set identifier. A set is a group of tuples, typically representing resources or index terms, that are in a specific order.

Unlike other special types, a Set cannot be declared or created using FQL syntax: a Set is created or accessed via FQL functions.

try
{
    Value result = await client.Query(
        Match(Index("spells_by_element"), "fire")
    );
    Console.WriteLine(result);
}
catch (Exception e)
{
    Console.WriteLine($"ERROR: {e.Message}");
}
SetRefV(System.Collections.Generic.Dictionary`2[System.String,FaunaDB.Types.Value])
result, err := client.Query(
	f.MatchTerm(f.Index("spells_by_element"), "fire"))

if err != nil {
	fmt.Fprintln(os.Stderr, err)
} else {
	fmt.Println(result)
}
{map[match:{spells_by_element 0xc0000bf290 0xc0000bf290 <nil>} terms:fire]}
System.out.println(
    client.query(
        Match(
            Index("spells_by_element"),
            Value("fire")
        )
    ).get());
{@set = {match: ref(id = "spells_by_element", collection = ref(id = "indexes")), terms: "fire"}}
client.query(
  q.Match(q.Index('spells_by_element'), 'fire')
)
.then((ret) => console.log(ret))
.catch((err) => console.error(
  'Error: [%s] %s: %s',
  err.name,
  err.message,
  err.errors()[0].description,
))
Match(Index("spells_by_element"), "fire")
result = client.query(
  q.match(q.index("spells_by_element"), "fire")
)
print(result)
SetRef({'match': Ref(id=spells_by_element, collection=Ref(id=indexes)), 'terms': 'fire'})
Match(Index('spells_by_element'), 'fire')
Match(Index("spells_by_element"), "fire")
Query metrics:
  •    bytesIn:  54

  •   bytesOut: 121

  • computeOps:   1

  •    readOps:   0

  •   writeOps:   0

  •  readBytes:   0

  • writeBytes:   0

  •  queryTime: 4ms

  •    retries:   0

Indexes are groups of sets, each of which has a natural key; a tuple of zero or more terms. The Match function constructs a set ref to identify a set for a given tuple of terms within an index:

try
{
    Value result = await client.Query(
        Match(Index("spells_by_element"), "water")
    );
    Console.WriteLine(result);
}
catch (Exception e)
{
    Console.WriteLine($"ERROR: {e.Message}");
}
SetRefV(System.Collections.Generic.Dictionary`2[System.String,FaunaDB.Types.Value])
result, err := client.Query(
	f.MatchTerm(f.Index("spells_by_element"), "water"))

if err != nil {
	fmt.Fprintln(os.Stderr, err)
} else {
	fmt.Println(result)
}
{map[match:{spells_by_element 0xc0001804b0 0xc0001804b0 <nil>} terms:water]}
System.out.println(
    client.query(
        Match(Index(Value("spells_by_element")), Value("water"))
    ).get());
{@set = {match: ref(id = "spells_by_element", collection = ref(id = "indexes")), terms: "water"}}
client.query(
  q.Match(q.Index('spells_by_element'), 'water')
)
.then((ret) => console.log(ret))
.catch((err) => console.error(
  'Error: [%s] %s: %s',
  err.name,
  err.message,
  err.errors()[0].description,
))
Match(Index("spells_by_element"), "water")
result = client.query(
  q.match(q.index("spells_by_element"), "water")
)
print(result)
SetRef({'match': Ref(id=spells_by_element, collection=Ref(id=indexes)), 'terms': 'water'})
Match(Index('spells_by_element'), 'water')
Match(Index("spells_by_element"), "water")
Query metrics:
  •    bytesIn:  55

  •   bytesOut: 122

  • computeOps:   1

  •    readOps:   0

  •   writeOps:   0

  •  readBytes:   0

  • writeBytes:   0

  •  queryTime: 4ms

  •    retries:   0

Set refs are unique according to their structure: Two set refs with the same structure refer to the same set within a database. Functions such as Union, Intersection, and Join allow the construction of more complex logical set identifiers:

try
{
    Value result = await client.Query(
        Intersection(
            Match(Index("spells_by_element"), "water"),
            Match(Index("spells_by_element"), "fire")
        )
    );
    Console.WriteLine(result);
}
catch (Exception e)
{
    Console.WriteLine($"ERROR: {e.Message}");
}
SetRefV(System.Collections.Generic.Dictionary`2[System.String,FaunaDB.Types.Value])
result, err := client.Query(
	f.Intersection(
		f.MatchTerm(f.Index("spells_by_element"), "water"),
		f.MatchTerm(f.Index("spells_by_element"), "fire"),
	))

	if err != nil {
		fmt.Fprintln(os.Stderr, err)
	} else {
		fmt.Println(result)
	}
{map[intersection:[{map[match:{spells_by_element 0xc000109950 0xc000109950 <nil>} terms:water]} {map[match:{spells_by_element 0xc000109a70 0xc000109a70 <nil>} terms:fire]}]]}
System.out.println(
    client.query(
        Intersection(
            Match(Index(Value("spells_by_element")), Value("fire")),
            Match(Index(Value("spells_by_element")), Value("water"))
        )
    ).get());
{@set = {intersection: [{@set = {match: ref(id = "spells_by_element", collection = ref(id = "indexes")), terms: "fire"}}, {@set = {match: ref(id = "spells_by_element", collection = ref(id = "indexes")), terms: "water"}}]}}
client.query(
  q.Intersection(
    q.Match(q.Index('spells_by_element'), 'water'),
    q.Match(q.Index('spells_by_element'), 'fire'),
  )
)
.then((ret) => console.log(ret))
.catch((err) => console.error(
  'Error: [%s] %s: %s',
  err.name,
  err.message,
  err.errors()[0].description,
))
Intersection(Match(Index("spells_by_element"), "water"), Match(Index("spells_by_element"), "fire"))
result = client.query(
  q.intersection(
    q.match(q.index("spells_by_element"), "water"),
    q.match(q.index("spells_by_element"), "fire")
  )
)
print(result)
SetRef({'intersection': [SetRef({'match': Ref(id=spells_by_element, collection=Ref(id=indexes)), 'terms': 'water'}), SetRef({'match': Ref(id=spells_by_element, collection=Ref(id=indexes)), 'terms': 'fire'})]})
Intersection(
  Match(Index('spells_by_element'), 'water'),
  Match(Index('spells_by_element'), 'fire'),
)
Intersection(Match(Index("spells_by_element"), "water"), Match(Index("spells_by_element"), "fire"))
Query metrics:
  •    bytesIn: 129

  •   bytesOut: 259

  • computeOps:   1

  •    readOps:   0

  •   writeOps:   0

  •  readBytes:   0

  • writeBytes:   0

  •  queryTime: 5ms

  •    retries:   0

The Paginate function is used to retrieve the tuples of a set. The Page object returned by Paginate contains an array of tuples and cursors for moving forward or backward within the set.

Field Type Definition and Requirements

data

The elements in the page.

after

The cursor for the next Page, inclusive. Optional.

before

The cursor for the previous Page, exclusive. Optional.

Pages can be further manipulated using collection-oriented functions such as Map and Filter. Individual elements can be extracted using the Select function.

Functions that operate on sets:

All

Tests whether all of the provided values are true.

Any

Tests whether any of the provided values are true.

Count

Counts the items in an array or set.

Difference

Returns the set of items in one set that are missing from additional sets.

Distinct

Returns the set of distinct items within a set.

Events

Returns the set of events describing the history of a set or document.

Filter

Fetches specific items from a set.

Intersection

Returns the set of items that exist in all sets.

IsEmpty

Tests whether an array or set is empty.

IsNonEmpty

Tests whether an array or set contains items.

Join

Combines the items in a set with set’s indexed values.

Match

Returns the set of items that match search terms.

Max

Returns the largest value in a list of numbers.

Mean

Returns the average value of the items in an array or set.

Min

Returns the smallest value in a list of numbers.

Range

Returns a subset of a set, in the specified range.

Reduce

Reduce an array or set to a result via a lambda function.

Reverse

Reverses the order of the items in a set.

Singleton

Returns a single-item set containing the provided document reference.

Sum

Sums the items in an array or set.

Union

Returns a set that combines the items in multiple sets.

Timestamp

The Timestamp type stores an instant in time expressed as a calendar date and time of day in UTC.

A Timestamp can safely store nanosecond precision, but be careful as many operating system clocks provide only microsecond precision.

Timestamps may be inserted with offsets, but are converted to UTC; the offset component is lost.

A Timestamp must be within the range -999999999-01-01T00:00:00Z - 9999-12-31T23:59:59.999999999Z.

A document’s ts field represents the most recent event that modified the document.

A document’s ts is a timestamp, but it is not a Timestamp type. ts is a Long expressing the number of UNIX microseconds since UNIX epoch.
try
{
    Value result = await client.Query(
        Time("1970-01-01T00:00:00Z")
    );
    Console.WriteLine(result);
}
catch (Exception e)
{
    Console.WriteLine($"ERROR: {e.Message}");
}
FaunaTime(1970-01-01T00:00:00Z)
result, err := client.Query(
	f.Time("1970-01-01T00:00:00Z"))

if err != nil {
	fmt.Fprintln(os.Stderr, err)
} else {
	fmt.Println(result)
}
{0 62135596800 <nil>}
System.out.println(
    client.query(
        Time(Value("1970-01-01T00:00:00Z"))
    ).get());
1970-01-01T00:00:00Z
client.query(
  q.Time('1970-01-01T00:00:00Z')
)
.then((ret) => console.log(ret))
.catch((err) => console.error(
  'Error: [%s] %s: %s',
  err.name,
  err.message,
  err.errors()[0].description,
))
Time("1970-01-01T00:00:00Z")
result = client.query(
  q.time("1970-01-01T00:00:00Z")
)
print(result)
FaunaTime('1970-01-01T00:00:00Z')
Time('1970-01-01T00:00:00Z')
Time("1970-01-01T00:00:00Z")
Query metrics:
  •    bytesIn:  31

  •   bytesOut:  43

  • computeOps:   1

  •    readOps:   0

  •   writeOps:   0

  •  readBytes:   0

  • writeBytes:   0

  •  queryTime: 1ms

  •    retries:   0

Functions that operate on times or dates:

Date

Converts an ISO-8601 string into a Date.

DayOfMonth

Returns the day of the month from a timestamp.

DayOfWeek

Returns the day of the week from a timestamp.

DayOfYear

Returns the day of the year from a timestamp.

Epoch

Creates a timestamp from an offset since 1970-01-01 in seconds, milliseconds, microseconds, or nanoseconds.

Hour

Returns the hour from a timestamp.

Minute

Returns the minute from a timestamp.

Month

Returns the month from a timestamp.

Now

Returns a timestamp representing the current transaction time.

Second

Returns the second from a timestamp.

Time

Converts now, or an ISO-8601 string, into a timestamp.

TimeAdd

Adds an offset to a provided timestamp/date.

TimeDiff

Returns the difference between two timestamps/dates, in specified units.

TimeSubtract

Subtracts an offset from a provided timestamp/date.

Year

Returns the year from a timestamp.

Events

Strictly speaking, events aren’t types; they are objects that capture the temporal history of documents by tracking all create, update, and delete operations, as snapshots, over a document’s timeline. However, they have a common structure:

Document events

Field Value Description

ref

The reference to the document.

action

Either "create","update" or "delete".

ts

An integer value representing a UNIX timestamp, with microsecond resolution, at which the event occurred.

data

Varies based on the action.

Set events

Set events are represented by an object returned when paginating through an index.

Field Value Description

ref

The reference to the document.

action

Either add or remove.

ts

An integer value representing a UNIX timestamp, with microsecond resolution, at which the event occurred.

data

Exactly as defined by the index’s terms field.

Precedence

Types have an order of precedence. When comparing values of different types, they are ranked in the following order, from least to greatest.

  1. Number (integers and decimals: 0.5 < 1 < 1.5 < 2)

  2. Byte

  3. String

  4. Array (ordered lexically, like strings)

  5. Object (ordered lexically, like strings)

  6. Reference

  7. Timestamp

  8. Date

  9. Boolean (false < true)

  10. Null

Is this article helpful? 

Tell Fauna how the article can be improved:
Visit Fauna's forums or email docs@fauna.com

Thank you for your feedback!