Previous Next JavaScript must be enabled to correctly display this content

## Array and Map Constructors

Syntax

    array_constructor ::=
       "[" expression ("," expression)* "]"

    map_constructor ::=
       ("{" expression ":" expression
       ("," expression ":" expression)* "}") |
       ("{" "}")

Semantics

An array constructor constructs a new array out of the items returned by the expressions inside the square brackets. These expressions are computed left to right, and the produced items are appended to the array. Any NULLs produced by the input expressions are skipped (arrays cannot contain NULLs).

Similarly, a map constructor constructs a new map out of the items returned by the expressions inside the curly brackets. These expressions come in pairs: each pair computes one field. The first expression in a pair must return at most one string, which serves as the field's name and the second returns the associated field value. If a value expression returns more than one items, an array is implicitly constructed to store the items, and that array becomes the field value. If either a field name or a field value expression returns the empty sequence, no field is constructed. If the computed name or value for a field is NULL the field is skipped (maps cannot contain NULLs).

The type of the constructed arrays or maps is determined during query compilation, based on the types of the input expressions and the usage of the constructor expression. Specifically, if a constructed array or map may be inserted in another constructed array or map and this "parent" array/map has type ARRAY(JSON) or MAP(JSON), then the "child" array/map will also have type ARRAY(JSON) or MAP(JSON). This is to enforce the restriction that "typed" data are not allowed inside JSON data (see Data Type Hierarchy).

Example 6-93 Array and Map Constructor

For each user create a map with 3 fields recording the user's last name, their phone information, and the expense categories in which more than $5000 was spent.

    SELECT
    {
        "last_name" : u.lastName,
        "phones" : u.address.phones,
        "high_expenses" : [ u.expenses.keys($value > 5000) ]
    }
    FROM users u

Notice that the use of an explicit array for the "high_expenses" field guarantees that the field will exist in all the constructed maps, even if the path inside the array constructor returns empty. Notice also that although it is known at compile time that all elements of the constructed arrays will be strings, the arrays are constructed with type ARRAY(JSON) (instead of ARRAY(STRING)), because they are inserted into a JSON map.