Lesson 8: Structuring query results

Lesson 8.1: Chaining clauses

  • Clauses can be chained arbitrarily into query pipelines, since they all consume streams of concept rows and produce stream of concept rows

    match <pattern>
    reduce <operation>
    match <pattern>
    sort <vars>;
    insert <pattern>
    delete <pattern>
    match <pattern>
    limit N;
    ...
  • fetch clauses can only be placed at the end of a query pipeline to transform the stream into a stream of JSON documents

Lesson 8.3: Aggregations

  • Use reduce operators to aggregate streams

  • The reduce operators are count, sum, max, min, mean, median, and std. Except for count, each modifier takes a variable to aggregate over as an argument, which can represent either a numeric attribute or a numeric value.

  • You can group reductions by using groupby

    reduce $count = count groupy $book;

Sorting and pagination

  • The query streams can be sorted using the sort operator

    match <pattern>
    sort var;
  • The results of queries can be paginated using the limit and offset modifiers, which take a literal integer as an argument.

    match <pattern>
    offset 10;
    limit 5;
  • The sort, limit, and offset modifiers can all be used individually or in any combination.

Subqueries

  • Subqueries can be encapsulated and invoked easily wth functions.

Lesson 8.5: Structured fetching

  • Fetch clauses can project attributes

    fetch {
     "value": $owner.attribute-type,
    };
  • Attributes, values, and types can be fetched directly in the fetch clause

    fetch {
      "attribute": $attribute,
      "type": $type_,
      "computed-value": $computed-value,
    };
  • Subqueries can be written directly into the fetch clause with the correct encapsulation:

fetch {
  "attached-values": [ match ...; fetch { ... }; ],
};
  • Underlying idea: all leaves in a fetch clause structure must be serializeable to a value

Further learning

Learn how to design schemas for TypeDB using the conceptual PERA model, including common design patterns and pitfalls.

Learn how to use functions to abstract complex patterns into simple forms, and capture complex logic.