### Traversal Expression Example Source: https://github.com/sanity-io/groq/blob/main/spec/07-compound-expressions.md Demonstrates a complex traversal path starting from a wildcard, accessing nested properties, array elements, and then traversing to related documents. ```groq users.foo.bar[0].sources[]->name ``` -------------------------------- ### Array Target Traversal Examples Source: https://github.com/sanity-io/groq/blob/main/spec/03-execution.md Examples of array target traversals, which are known to return an array but operate on an unknown type. These are distinct from traversals that also work on arrays or do not work on arrays. ```groq user.roles[dataset == "production"] ``` ```groq {name,type}[] ``` -------------------------------- ### Basic GROQ Query Example Source: https://github.com/sanity-io/groq/blob/main/spec/03-execution.md A simple query to select names and friends from documents of type 'person'. Demonstrates basic filtering and projection. ```groq *[_type == "person"]{name, friends[country == "NO"]} ``` -------------------------------- ### Example of Chaining Pipe Functions Source: https://github.com/sanity-io/groq/blob/main/spec/12-pipe-functions.md Demonstrates how to chain pipe functions like order() and select() in a GROQ query. The input array is processed sequentially by each pipe. ```groq *[_type == "person"] | order(name) | {"age"} ``` -------------------------------- ### Datetime Serialization Example (With Milliseconds) Source: https://github.com/sanity-io/groq/blob/main/spec/04-data-types.md Represents a datetime value in RFC 3339 format with millisecond information (3 fractional digits). ```json 2006-01-02T15:04:05.508Z ``` -------------------------------- ### Object Literal Example Source: https://github.com/sanity-io/groq/blob/main/spec/04-data-types.md Demonstrates creating an object literal within a GROQ query to project computed values. This is useful for transforming query results into a structured format. ```groq *[_type == "rect"]{"area": width * height} ``` -------------------------------- ### Datetime Serialization Example (No Milliseconds) Source: https://github.com/sanity-io/groq/blob/main/spec/04-data-types.md Represents a datetime value in RFC 3339 format without millisecond information. ```json 2006-01-02T15:04:05Z ``` -------------------------------- ### Selector Evaluation Example Source: https://github.com/sanity-io/groq/blob/main/spec/03-execution.md Illustrates how a selector like `.users[1].name` identifies a specific value within a nested JSON structure. ```groq .users[1].name ``` -------------------------------- ### Defining a Custom Function in GROQ Source: https://github.com/sanity-io/groq/blob/main/spec/12-custom-functions.md Demonstrates the syntax for defining a custom function named 'firstPost' within the 'blog' namespace. Functions must be defined at the start of a query using the `fn` keyword and terminated by a semicolon. ```groq fn blog.firstPost() => { title, _createdAt }[0]; ``` -------------------------------- ### GROQ Query with Parent Scope Reference Source: https://github.com/sanity-io/groq/blob/main/spec/03-execution.md An example demonstrating how to reference parent scope attributes using '^' to perform a join-like operation, fetching a person's children. ```groq *[_type == "person"]{ id, name, "children": *[_type == "person" && parentId == ^.id] } ``` -------------------------------- ### Score Evaluation Example Source: https://github.com/sanity-io/groq/blob/main/spec/03-execution.md Assigns a score of 2.0 to documents where 'a > 1' and 1.0 to others. Scores are computed once per result and summed. ```groq * | score(a > 1) ``` -------------------------------- ### Pipe Function Call for Chained Operations Source: https://github.com/sanity-io/groq/blob/main/spec/07-compound-expressions.md Chains multiple operations using pipe functions. This example filters documents by type, orders them by name, and then selects the age field. ```groq *[_type == "person"] | order(name) | {age} ``` -------------------------------- ### Element Access Traversal Source: https://github.com/sanity-io/groq/blob/main/spec/08-traversal-operators.md Access elements in an array by their index. Supports positive indexing from the start and negative indexing from the end. ```groq array[0] ``` ```groq array[-1] ``` -------------------------------- ### Inclusive Range Syntax Source: https://github.com/sanity-io/groq/blob/main/spec/04-data-types.md Defines an inclusive range where both the start and end values are included. Used in contexts like the 'in' operator or array slicing. ```groq 1..3 ``` -------------------------------- ### Boosted Predicate Scoring Source: https://github.com/sanity-io/groq/blob/main/spec/03-execution.md Adds a boost value to the score if the predicate matches. For example, `boost(a > 1, 10)` results in a score of 11 for matching expressions. ```groq boost(a > 1, 10) ``` -------------------------------- ### Exclusive Range Syntax Source: https://github.com/sanity-io/groq/blob/main/spec/04-data-types.md Defines a right-exclusive range where the start value is included but the end value is excluded. Used in contexts like the 'in' operator or array slicing. ```groq 1...3 ``` -------------------------------- ### Defining a Custom Function with Parameters in GROQ Source: https://github.com/sanity-io/groq/blob/main/spec/12-custom-functions.md Illustrates defining a function that accepts parameters. The 'postsByTag' function takes a 'tag' parameter and returns posts matching that tag. ```groq fn blog.postsByTag(tag) => { *[tag == ^.tag] { title, tags } }; ``` -------------------------------- ### Everything Expression in GROQ Source: https://github.com/sanity-io/groq/blob/main/spec/06-simple-expressions.md Returns the full dataset. This expression is represented by an asterisk. ```groq *[_type == "person"] ~ ``` -------------------------------- ### Invoking a Custom Function in GROQ Source: https://github.com/sanity-io/groq/blob/main/spec/12-custom-functions.md Shows how to invoke the previously defined 'firstPost' function from the 'blog' namespace. The invocation uses the namespace and function identifier, followed by parentheses for parameters (none in this case). ```groq blog.firstPost() ``` -------------------------------- ### Multi-expression Scoring with score() Source: https://github.com/sanity-io/groq/blob/main/spec/12-pipe-functions.md Demonstrates using multiple expressions within the score() pipe function to create a combined relevance score. Each expression contributes to the final score, allowing for complex ranking logic. ```groq *[_type == "listing"] | score(body match "jacuzzi", bedrooms > 2, available && !inContract) ``` -------------------------------- ### GROQ vs JavaScript for Data Traversal Source: https://github.com/sanity-io/groq/blob/main/spec/03-execution.md Compares GROQ's terse syntax for accessing nested data with equivalent JavaScript array methods. ```groq *[_type == "user"]._id ``` ```javascript data.filter(u => u._type == "user").map(u => u._id) ``` -------------------------------- ### global::before() Source: https://github.com/sanity-io/groq/blob/main/spec/11-functions.md The `before` function, in delta mode, returns the attributes before the change. It returns the 'before' object of the query context. ```APIDOC ## global::before() ### Description Returns the attributes before a change in delta mode. ### Method Function Call Expression ### Parameters #### Scope - **scope**: The query context scope. ### Return Value - The 'before' object of the query context. ``` -------------------------------- ### Invoking a Custom Function with Parameters in GROQ Source: https://github.com/sanity-io/groq/blob/main/spec/12-custom-functions.md Demonstrates invoking a function that requires parameters. The 'postsByTag' function is called with the parameter 'technology' to filter posts. ```groq blog.postsByTag('technology') ``` -------------------------------- ### dateTime::now() Source: https://github.com/sanity-io/groq/blob/main/spec/11-functions.md The now function in the dateTime namespace returns the current point in time as a datetime object. ```APIDOC ## dateTime::now() ### Description Returns the current point in time as a datetime object. ### Signature dateTime_now(args, scope) ### Parameters - **args**: No arguments are expected. - **scope**: The current execution scope. ### Returns - A datetime object representing the current time. ``` -------------------------------- ### global::now() Source: https://github.com/sanity-io/groq/blob/main/spec/11-functions.md The `now` function returns the current point in time as an RFC 3339 formatted string. It is recommended to use `dateTime::now()` for a proper datetime object. ```APIDOC ## global::now() ### Description Returns the current point in time as an RFC 3339 formatted string. ### Method Function Call Expression ### Parameters This function takes no arguments. ### Return Value - An RFC 3339 formatted string representing the current time. ``` -------------------------------- ### ExecuteQuery Function Signature Source: https://github.com/sanity-io/groq/blob/main/spec/03-execution.md Defines the signature and conceptual steps for the ExecuteQuery function. It involves creating a new root scope from the context and then evaluating the query expression within that scope. ```pseudocode ExecuteQuery(query, context): - Let {scope} be the result of {NewRootScope(context)}. - Let {expr} be the expression of {query}. - Let {result} be the result of {Evalute(expr, scope)}. - Return {result}. ``` -------------------------------- ### Object Literal Syntactic Sugar Source: https://github.com/sanity-io/groq/blob/main/spec/04-data-types.md Shows the shorthand syntax for object literals in GROQ when the attribute name and the value expression are the same. This simplifies queries by reducing redundancy. ```groq *[_type == "person"]{name} ``` ```groq *[_type == "person"]{"name": name} ``` -------------------------------- ### Additive Scoring with Multiple score() calls Source: https://github.com/sanity-io/groq/blob/main/spec/12-pipe-functions.md Shows that multiple score() pipe functions applied sequentially are additive, similar to providing multiple expressions within a single score() call. This allows for modular scoring logic. ```groq * | score(a == 1) | score(b == 2) ``` -------------------------------- ### Sorting Results with order() Source: https://github.com/sanity-io/groq/blob/main/spec/12-pipe-functions.md Uses the order() pipe function to sort an array of documents by a specified field. The sorting logic is defined by comparison functions and can handle ascending or descending order. ```groq *[_type == "person"] | order(name) ``` -------------------------------- ### GROQ global::select() Function Source: https://github.com/sanity-io/groq/blob/main/spec/11-functions.md Chooses a value based on a series of conditional pairs or a default value. Returns the first matching condition's value or the default. ```groq global_select(args, scope): - For each {arg} in {args}: - If {arg} is a {Pair}: - Let {condNode} be the first {Expression} of the {Pair}. - Let {resultNode} be the second {Expression} of the {Pair}. - Let {cond} be the result of {Evaluate(condNode, scope)}. - If {cond} is {true}: - Return the result of {Evaluate(resultNode, scope)}. - Otherwise: - Return the result of {Evaluate(arg, scope)}. global_select_validate(args): - Let {seenDefault} be {false}. - For each {arg} in {args}: - If {seenDefault} is {true}: - Report an error. - If {arg} is not a {Pair}: - Set {seenDefault} to {true}. ``` -------------------------------- ### global::pt() Source: https://github.com/sanity-io/groq/blob/main/spec/14-extensions.md This function acts as a constructor for the PT type. It takes an object or an array of objects and attempts to parse them as Portable Text blocks, returning a PT value if successful, otherwise null. ```APIDOC ## global::pt() ### Description This function is a constructor for the PT type. It takes an object or an array of objects and returns a PT value. It attempts to parse the input as Portable Text blocks. ### Function Signature global_pt(args, scope) ### Parameters - **args**: An array of nodes representing the input data. - **scope**: The current evaluation scope. ### Returns A PT value if the input is a valid Portable Text object or an array of valid Portable Text objects, otherwise null. ### Validation global_pt_validate(args) - Reports an error if the length of `args` is not 1. ``` -------------------------------- ### Projection Traversal Source: https://github.com/sanity-io/groq/blob/main/spec/08-traversal-operators.md Create a new object by selecting and transforming fields from an existing object. Useful for shaping query results. ```groq *[_type == "person"]{name, "isLegal": age >= 18} ``` -------------------------------- ### GROQ boost() Function for Scoring Source: https://github.com/sanity-io/groq/blob/main/spec/11-functions.md Increases or decreases the score computed by score(). Must be used within the argument list to score(). ```groq * | score(boost(title matches "milk", 5.0), body matches "milk") ``` ```groq boost(args, scope): - Let {predicateNode} be the first element of {args}. - Let {result} be the result of {Evaluate(predicateNode, scope)}. - Let {numNode} be the second element of {args}. - Let {num} be the result of {Evaluate(numNode, scope)}. - If {num} is not a number: - Return {null}. - If {num} is negative: - Return {null}. - Return {result}. boost_validate(args): - If the length of {args} is not 2: - Report an error. ``` -------------------------------- ### global::after() Source: https://github.com/sanity-io/groq/blob/main/spec/11-functions.md The `after` function, in delta mode, returns the attributes after the change. It returns the 'after' object of the query context. ```APIDOC ## global::after() ### Description Returns the attributes after a change in delta mode. ### Method Function Call Expression ### Parameters #### Scope - **scope**: The query context scope. ### Return Value - The 'after' object of the query context. ``` -------------------------------- ### Logical Expression Scoring Source: https://github.com/sanity-io/groq/blob/main/spec/03-execution.md Demonstrates scoring for logical AND and OR expressions. Scores are the sum of clauses evaluating to true. ```groq true && false ``` ```groq true && true ``` ```groq true || true ``` ```groq true || false ``` -------------------------------- ### geo::latLng() Source: https://github.com/sanity-io/groq/blob/main/spec/14-extensions.md This function creates a GeoJSON Point from provided latitude and longitude values. It includes validation for the input types and ranges. ```APIDOC ## geo::latLng() ### Description This function takes latitude and longitude as arguments and returns a GeoJSON Point object. ### Function Signature geo_latLng(args, scope) ### Parameters - **args**: An array containing two nodes: the first for latitude and the second for longitude. - **scope**: The current evaluation scope. ### Returns A GeoJSON Point object with `lat` and `lng` as coordinates if the inputs are valid numbers within the correct ranges. Returns null otherwise. ### Validation geo_latLng_validate(args) - Reports an error if the length of `args` is not 2. ``` -------------------------------- ### Scoring Results with score() Source: https://github.com/sanity-io/groq/blob/main/spec/12-pipe-functions.md Applies the score() pipe function to assign a relevance score to documents based on matching criteria. This is useful for search-like functionality where results need to be ranked. ```groq *[_type == "listing"] | score(body match "jacuzzi") ``` -------------------------------- ### global::upper() Source: https://github.com/sanity-io/groq/blob/main/spec/11-functions.md The upper function returns an uppercased version of the input string. It handles null values by returning null. ```APIDOC ## global::upper() ### Description Returns the uppercased form of a string value. If the input value is null, it returns null. ### Signature global_upper(args, scope) ### Parameters - **args**: The arguments passed to the function. - **scope**: The current execution scope. ### Returns - The uppercased string or null. ``` -------------------------------- ### JSON String Literal Source: https://github.com/sanity-io/groq/blob/main/spec/02-syntax.md A simple string is a valid GROQ expression. ```json "Hi! 👋" ``` -------------------------------- ### GROQ global::string() Function Source: https://github.com/sanity-io/groq/blob/main/spec/11-functions.md Converts scalar values to their string representation. Returns null for non-scalar types. ```groq global_string(args, scope): - Let {node} be the first element of {args}. - Let {val} be the result of {Evaluate(node, scope)}. - If {val} is {true}: - Return the string "true". - If {val} is {false}: - Return the string "false". - If {val} is a string: - Return {val}. - If {val} is a number: - Return a string representation of the number. - If {val} is a datetime: - Return the datetime in the [RFC 3339](https://tools.ietf.org/html/rfc3339) timestamp format with a Z suffix. - Otherwise: - Return {null}. global_string_validate(args): - If the length of {args} is not 1: - Report an error. ``` -------------------------------- ### Attribute Access Traversal Source: https://github.com/sanity-io/groq/blob/main/spec/08-traversal-operators.md Access attributes of an object using dot notation or bracket notation with a string key. Use when you know the exact attribute name. ```groq person.name ``` ```groq person["Full Name"] ``` -------------------------------- ### Number Data Type Source: https://github.com/sanity-io/groq/blob/main/spec/04-data-types.md Supports signed 64-bit double-precision floating-point numbers according to IEEE 754. Special values like Infinity and NaN are coerced to null. ```groq Number : - Integer - Decimal - ScientificNotation Sign : one of + - Integer : Sign? Digit+ Decimal : Sign? Digit+ Fractional ScientificNotation : Sign? Digit+ Fractional? ExponentMarker Sign? Digit+ Fractional : . Digit+ ExponentMarker : one of `e` `E` ``` -------------------------------- ### global::count() Source: https://github.com/sanity-io/groq/blob/main/spec/11-functions.md The `count` function returns the length of an array. It takes a single argument, which should be an array. ```APIDOC ## global::count() ### Description Returns the number of elements in an array. ### Method Function Call Expression ### Parameters #### Arguments - **args**: An array containing a single element, which must be an array. ### Return Value - The length of the input array, or null if the input is not an array. ``` -------------------------------- ### global::lower() Source: https://github.com/sanity-io/groq/blob/main/spec/11-functions.md The lower function returns a lowercased version of the input string. It handles null values by returning null. ```APIDOC ## global::lower() ### Description Returns the lowercased form of a string value. If the input value is null, it returns null. ### Signature global_lower(args, scope) ### Parameters - **args**: The arguments passed to the function. - **scope**: The current execution scope. ### Returns - The lowercased string or null. ``` -------------------------------- ### global::geo() Source: https://github.com/sanity-io/groq/blob/main/spec/14-extensions.md This function serves as a constructor for the geo type. It accepts an object or another geo value and returns a geo value, attempting to parse the input as a geographic point or GeoJSON. ```APIDOC ## global::geo() ### Description This function is a constructor for the geographic value (geo type). It takes an object or another geo value as input and returns a geo value. It supports parsing geographic points and GeoJSON objects. ### Function Signature global_geo(args, scope) ### Parameters - **args**: An array of nodes representing the input data. - **scope**: The current evaluation scope. ### Returns A geo value if the input is a valid geographic point or GeoJSON representation, otherwise null. ### Validation global_geo_validate(args) - Reports an error if the length of `args` is not 1. ``` -------------------------------- ### global::length() Source: https://github.com/sanity-io/groq/blob/main/spec/11-functions.md The `length` function returns the length of a string or an array. It accepts a single argument which can be a string or an array. ```APIDOC ## global::length() ### Description Returns the length of a string or an array. ### Method Function Call Expression ### Parameters #### Arguments - **args**: An array containing a single element, which can be a string or an array. ### Return Value - The length of the string or array, or null if the input is neither. ``` -------------------------------- ### Function Call Expression in GROQ Source: https://github.com/sanity-io/groq/blob/main/spec/06-simple-expressions.md Invokes built-in or custom GROQ functions. Supports namespaces for function resolution and allows passing expressions as arguments. ```groq *{"score": round(score, 2)} ~~~~~~~~~~~~~~~ ``` ```groq *{"description": global::lower(description)} ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``` -------------------------------- ### GROQ global::references() Function Source: https://github.com/sanity-io/groq/blob/main/spec/11-functions.md Checks if a given scope contains references to a specified document ID. It recursively traverses the scope to find matching references. ```groq global_references(args, scope): - Let {pathSet} be an empty array. - For each {arg} of {args}: - Let {path} be the result of {Evaluate(arg, scope)}. - If {path} is a string: - Append {path} to {pathSet}. - If {path} is an array: - Concatenate all strings of {path} to {pathSet}. - If {pathSet} is empty: - Return {false}. - Let {base} be the this value of {scope}. - Return the result of {HasReferenceTo(base, pathSet)}. HasReferenceTo(base, pathSet): - If {base} is an array: - For each {value} in {base}: - Let {result} be the result of {HasReferenceTo(value, pathSet)}. - If {result} is {true}: - Return {true}. - Return {false}. - If {base} is an object: - If {base} has an attribute `_ref`: - Let {ref} be the value of the attribute `_ref` in {base}. - If {ref} exists in {pathSet}: - Return {true}. - Otherwise: - Return {false}. - For each {key} and {value} in {base}: - Let {result} be the result of {HasReferenceTo(value, pathSet)}. - If {result} is {true}: - Return {true}. - Return {false}. global_references_validate(args): - If the length of {args} is 0: - Report an error. ``` -------------------------------- ### documents::get() Source: https://github.com/sanity-io/groq/blob/main/spec/14-extensions.md Retrieves a document using its Global Document Reference (GDR). Returns the document object if found, otherwise returns null. Handles validation for GDR format and argument count. ```APIDOC ## documents::get() ### Description This function takes a Global Document Reference referencing a document and returns the document. It searches across available data sources in the current scope to find the document matching the GDR. ### Function Signature `documents_get(args, scope)` ### Parameters - `args`: An array containing a single element: the Global Document Reference (GDR) string. - `scope`: The evaluation scope, which contains information about other data sources. ### Returns - The document object if found. - `null` if the GDR is invalid, not a string, or if the document cannot be found in any of the accessible datasets. ### Validation `documents_get_validate(args, scope)`: Reports an error if the number of arguments is not 1. ``` -------------------------------- ### Array Postfix Traversal Source: https://github.com/sanity-io/groq/blob/main/spec/08-traversal-operators.md Coerces a value into an array. If the value is already an array, it is returned as is. ```groq value[] ``` -------------------------------- ### global::dateTime() Source: https://github.com/sanity-io/groq/blob/main/spec/11-functions.md The `dateTime` function converts a string or another datetime value into a datetime value. It supports RFC 3339 format for string inputs. ```APIDOC ## global::dateTime() ### Description Converts a string or datetime value to a datetime value. ### Method Function Call Expression ### Parameters #### Arguments - **args**: An array containing a single element, which can be a string (RFC 3339 format) or a datetime value. ### Return Value - A datetime value if the input is valid, otherwise null. ``` -------------------------------- ### geo::distance() Source: https://github.com/sanity-io/groq/blob/main/spec/14-extensions.md Calculates the distance in meters between two geo point values using an approximation of the Earth's distance. Returns null if arguments are not valid geo points. ```APIDOC ## geo::distance() ### Description This function accepts two geo values, which must be point values, and returns the distance in meters. While the exact algorithm is implementation-defined (e.g., using the Haversine formula), it should approximate a real Earth distance as closely as possible. ### Function Signature `geo_distance(args, scope)` ### Parameters - `args`: An array containing two geo point values. - `scope`: The evaluation scope. ### Returns - The geographic distance in meters between the two points. - `null` if either argument is not a geo value or not a Geo Point/GeoJSON Point. ### Validation `geo_distance_validate(args)`: Reports an error if the number of arguments is not 2. ``` -------------------------------- ### Parameter Expression in GROQ Source: https://github.com/sanity-io/groq/blob/main/spec/06-simple-expressions.md Returns the value of a parameter, denoted by a '$' followed by an identifier. Used for dynamic query filtering. ```groq *[_type == $type] ~~~~~ ``` -------------------------------- ### JSON Array Literal Source: https://github.com/sanity-io/groq/blob/main/spec/02-syntax.md An array of strings is a valid GROQ expression. ```json ["An", "array", "of", "strings"] ``` -------------------------------- ### delta::operation() Source: https://github.com/sanity-io/groq/blob/main/spec/11-functions.md Returns the operation type (create, update, or delete) for a change in delta mode. ```APIDOC ## delta::operation() ### Description Returns the type of operation (create, update, or delete) for the current change being processed in delta mode. ### Signature delta_operation(args, scope) ### Parameters - **args**: No arguments are expected. - **scope**: The current execution scope. ### Returns - A string representing the operation: "create", "update", or "delete". ``` -------------------------------- ### Comments in GROQ Source: https://github.com/sanity-io/groq/blob/main/spec/02-syntax.md Comments can be placed on their own line or at the end of a line. They are ignored by the parser. ```example { // Comments can be on a separate line "key": "value" // Or at the end of a line } ``` -------------------------------- ### GROQ global::round() Function Source: https://github.com/sanity-io/groq/blob/main/spec/11-functions.md Rounds a number to a specified precision. Returns null if the input is not a number or precision is invalid. ```groq global_round(args, scope): - Let {numNode} be the first element of {args}. - Let {num} be the result of {Evaluate(numNode, scope)}. - If {num} is not a number: - Return {null}. - If the length of {args} is 2: - Let {precNode} be the second element of {args}. - Let {prec} be the result of {Evaluate(precNode, scope)}. - If {prec} is not a number: - Return {null}. - Otherwise: - Let {prec} be 0. - Return {num} rounded to {prec} number of digits after the decimal point. global_round_validate(args): - If the length of {args} is less than 1 or greater than 2: - Report an error. ``` -------------------------------- ### Boolean Data Type Source: https://github.com/sanity-io/groq/blob/main/spec/04-data-types.md Represents logical truth values. ```groq Boolean : - true - false ``` -------------------------------- ### Array Data Type Source: https://github.com/sanity-io/groq/blob/main/spec/04-data-types.md Represents an ordered collection of values, which can include any data type and nested arrays. Supports the spread syntax (...) for flattening elements. ```groq Array : [ ArrayElements? `,`? ] ArrayElements : - ArrayElement - ArrayElements , ArrayElement ArrayElement : `...`? Expression ``` ```groq EvaluateArray(scope): 1. Let {result} be a new empty array. 2. For each {ArrayElement}: 3. Let {elementNode} be the {Expression} of the {ArrayElement}. 4. Let {element} be the result of {Evaluate(elementNode, scope)}. 5. If the {ArrayElement} contains {...}: 1. If {element} is an array: 1. Concatenate {element} to {result}. 6. Otherwise: 1. Append {element} to {result}. 7. Return {result}. ``` -------------------------------- ### global::coalesce() Source: https://github.com/sanity-io/groq/blob/main/spec/11-functions.md The `coalesce` function returns the first argument that is not null. It iterates through provided arguments and returns the first non-null evaluated value. ```APIDOC ## global::coalesce() ### Description Returns the first non-null value from a list of arguments. ### Method Function Call Expression ### Parameters #### Arguments - **args**: An array of nodes to evaluate. ### Return Value - The first non-null evaluated argument, or null if all arguments are null. ``` -------------------------------- ### Filter Documents by ID Source: https://github.com/sanity-io/groq/blob/main/spec/01-overview.md This query filters documents where the 'id' field is greater than 2 and projects only the 'name' field. ```groq *[id > 2]{"name"} ``` -------------------------------- ### Comment within String Literal Source: https://github.com/sanity-io/groq/blob/main/spec/02-syntax.md Demonstrates that comments are not parsed within string literals. This is not a valid comment. ```example { "key // This isn't a comment": "value" } ``` -------------------------------- ### Null Data Type Source: https://github.com/sanity-io/groq/blob/main/spec/04-data-types.md Represents an unknown value, similar to SQL's NULL. Operations involving null result in null. ```groq Null : null ``` -------------------------------- ### String Data Type Source: https://github.com/sanity-io/groq/blob/main/spec/04-data-types.md Stores UTF-8 encoded characters. Supports standard JSON string syntax with extensions for control characters and Unicode characters above 16-bit. ```groq String : - `"` DoubleStringCharacter* `"` - `'` SingleStringCharacter* `'` DoubleStringCharacter : - SourceCharacter but not one of `"`, `\` - `\` EscapeSequence SingleStringCharacter : - SourceCharacter but not one of `'`, `\` - `\` EscapeSequence EscapeSequence : - SingleEscapeSequence - UnicodeEscapeSequence SingleEscapeSequence : one of ' `"` `\` / b f n r t UnicodeEscapeSequence : - u HexDigit HexDigit HexDigit HexDigit - u{ HexDigit+ } Escape sequences are interpreted as follows: - `\' ` represents U+0027. - `\"` represents U+0022. - `\\` represents U+005C. - `\/` represents U+002F. - `\b` represents U+0008. - `\f` represents U+000C. - `\n` represents U+000A. - `\r` represents U+000D. - `\t` represents U+0009. - `\uXXXX` represents the Unicode code point U+XXXX. - `\uXXXX\uYYYY`, where XXXX is a high surrogate (W1, 0xD800–0xDBFF) and YYYY is a low surrogate (W2, 0xDC00–0xDFFF) is interpreted as a UTF-16 surrogate pair and encoded into a single code point. It's a syntactical error when a Unicode escape sequence represents an invalid Unicode code point. ``` -------------------------------- ### Parent Expression in GROQ Source: https://github.com/sanity-io/groq/blob/main/spec/06-simple-expressions.md Returns the 'this' value for an upper scope. The '^' symbol navigates up one scope level, and '^.' navigates up and accesses an attribute. ```groq // Find all people who have a cool friend *[_type == "person" && *[_id == ^.friend._ref][0].isCool] ~ ``` -------------------------------- ### global::defined() Source: https://github.com/sanity-io/groq/blob/main/spec/11-functions.md The `defined` function checks if the provided argument is not null. It returns true if the argument has a value, and false if it is null. ```APIDOC ## global::defined() ### Description Checks if a value is not null. ### Method Function Call Expression ### Parameters #### Arguments - **args**: An array containing a single element to check. ### Return Value - `true` if the argument is not null, `false` otherwise. ``` -------------------------------- ### Slice Traversal Source: https://github.com/sanity-io/groq/blob/main/spec/08-traversal-operators.md Extract a contiguous sub-array (slice) using a range of indices. Indices can be positive or negative and are clamped to the array bounds. ```groq people[0..10] ``` -------------------------------- ### diff::changedAny() Source: https://github.com/sanity-io/groq/blob/main/spec/11-functions.md The changedAny function in the diff namespace returns true if any key paths matched by the selector have changed between two objects. ```APIDOC ## diff::changedAny() ### Description Checks if any key paths, as defined by a selector, have changed between two objects (left-hand side and right-hand side). ### Signature diff_changedAny(args, scope) ### Parameters - **args**: An array containing three elements: the left-hand side object, the right-hand side object, and a selector. - **scope**: The current execution scope. ### Returns - `true` if there is an overlap between the changed key paths and the selected key paths, `false` otherwise. ``` -------------------------------- ### documents::incomingGlobalDocumentReferenceCount() Source: https://github.com/sanity-io/groq/blob/main/spec/14-extensions.md Retrieves the count of global document references that point to a given document. This count is dynamically updated. ```APIDOC ## documents::incomingGlobalDocumentReferenceCount() ### Description This function returns the number of Global Document References referencing a document. The count is stored in the `_incomingGDRCount` property of the document and is updated automatically when references are added or removed. ### Method Call ### Parameters This function does not take any arguments. ### Response - **_incomingGDRCount** (number | null) - The number of global document references pointing to the document, or null if the property is not set. ### Response Example ```json { "_incomingGDRCount": 5 } ``` ### Error Handling - If the `_incomingGDRCount` property is null, the function returns null. ``` -------------------------------- ### This Attribute Expression in GROQ Source: https://github.com/sanity-io/groq/blob/main/spec/06-simple-expressions.md Returns an attribute from the 'this' value of the current scope. Ensures the base is an object and contains the specified attribute. ```groq *[_id == "document"][name == "Michael Bluth"] ~~~ ~~~~ ``` -------------------------------- ### This Expression in GROQ Source: https://github.com/sanity-io/groq/blob/main/spec/06-simple-expressions.md Returns the 'this' value of the current scope. Used to reference the current object or value being processed. ```groq *[_id == "doc"][0].numbers[@ >= 10] ~ ``` -------------------------------- ### pt::text() Source: https://github.com/sanity-io/groq/blob/main/spec/14-extensions.md This function converts a PT value (a Portable Text object or an array of objects) into its string representation. It appends double newline characters between blocks if multiple blocks are present. ```APIDOC ## pt::text() ### Description This function takes a PT value and returns its string representation. If the PT value consists of multiple blocks, they are joined with double newline characters. ### Function Signature pt_text(args, scope) ### Parameters - **args**: An array of nodes representing the PT value. - **scope**: The current evaluation scope. ### Returns A string version of the text content of the PT value, or null if the input is not a valid PT value. ### Validation pt_text_validate(args) - Reports an error if the length of `args` is not 1. ``` -------------------------------- ### Parenthesis Expression for Operator Precedence Source: https://github.com/sanity-io/groq/blob/main/spec/07-compound-expressions.md Use parenthesis to explicitly control the order of operations in GROQ expressions. This ensures calculations are performed as intended. ```groq (1 + 2) * 3 ``` -------------------------------- ### Documents Extension - Global Document Reference type Source: https://github.com/sanity-io/groq/blob/main/spec/14-extensions.md Defines the Global Document Reference (GDR) type, a string format used to uniquely identify a document across different datasets. ```APIDOC ## Global Document Reference type ### Description A Global Document Reference (GDR) type represents a reference to a document. The referenced document can be in a dataset separate from the dataset of the query context in the current scope. A GDR consists of a string formatted to uniquely identify a dataset and a document within that dataset. ### Function `MatchesGDR({gdr}, {datasetID}, {documentID})` ### Parameters - `{gdr}`: The Global Document Reference string to check. - `{datasetID}`: The ID of the dataset to compare against. - `{documentID}`: The ID of the document to compare against. ### Returns - `true` if the `{gdr}` matches the provided `{datasetID}` and `{documentID}`. - `false` if `{gdr}` is not a string, not in a valid GDR format, or does not match the provided IDs. ``` -------------------------------- ### Filter Traversal Source: https://github.com/sanity-io/groq/blob/main/spec/08-traversal-operators.md Filter an array to return only elements that satisfy a given condition. The condition is evaluated for each element in its own scope. ```groq *[_type == "person"] ``` -------------------------------- ### delta::changedOnly Source: https://github.com/sanity-io/groq/blob/main/spec/11-functions.md A variant of diff::changedOnly that operates on the before/after objects within the query context in delta mode. ```APIDOC ## delta::changedOnly ### Description Determines if only the key paths, specified by a selector, have changed between the before and after objects in the current delta query context. ### Signature delta_changedOnly(args, scope) ### Parameters - **args**: Contains the selector to apply. - **scope**: The current execution scope, which must be in delta mode. ### Returns - A boolean indicating if only the selected key paths have changed. ``` -------------------------------- ### delta::changedAny Source: https://github.com/sanity-io/groq/blob/main/spec/11-functions.md A variant of diff::changedAny that operates on the before/after objects within the query context in delta mode. ```APIDOC ## delta::changedAny ### Description Determines if any key paths, specified by a selector, have changed between the before and after objects in the current delta query context. ### Signature delta_changedAny(args, scope) ### Parameters - **args**: Contains the selector to apply. - **scope**: The current execution scope, which must be in delta mode. ### Returns - A boolean indicating if any selected key paths have changed. ``` -------------------------------- ### diff::changedOnly() Source: https://github.com/sanity-io/groq/blob/main/spec/11-functions.md The changedOnly function in the diff namespace returns true if only the key paths matched by the selector have changed between two objects. ```APIDOC ## diff::changedOnly() ### Description Checks if only the key paths, as defined by a selector, have changed between two objects (left-hand side and right-hand side). ### Signature diff_changedOnly(args, scope) ### Parameters - **args**: An array containing three elements: the left-hand side object, the right-hand side object, and a selector. - **scope**: The current execution scope. ### Returns - `true` if the list of changed key paths is a subset of the selected key paths, `false` otherwise. ``` -------------------------------- ### geo::contains() Source: https://github.com/sanity-io/groq/blob/main/spec/14-extensions.md Checks if the first geo value completely contains the second geo value using a planar coordinate system. Returns true if containment is met, false otherwise. Returns null if either argument is not a geo value. ```APIDOC ## geo::contains() ### Description Returns true if the first geo argument completely contains the second one, using a planar (non-spherical) coordinate system. Both geo arguments can be any geo value. A geo value is considered contained if all its points are within the boundaries of the first geo value. For `MultiPolygon`, it's sufficient that only one of the polygons contains the first geo value. ### Function Signature `geo_contains(args, scope)` ### Parameters - `args`: An array containing two geo values. - `scope`: The evaluation scope. ### Returns - `true` if the first geo value contains the second. - `false` if the first geo value does not contain the second. - `null` if either argument is not a geo value. ### Validation `geo_contains_validate(args)`: Reports an error if the number of arguments is not 2. ``` -------------------------------- ### JSON Object Literal Source: https://github.com/sanity-io/groq/blob/main/spec/02-syntax.md A complex JSON object with various data types is a valid GROQ expression. ```json { "array": ["string", 3.14, true, null], "boolean": true, "number": 3.14, "null": null, "object": {"key": "value"}, "string": "Hi! 👋" } ```