Reduce operator

Reduce

Syntax

reduce <var> = <operator> [ (<var>) ] [ , ... ];

TypeQL supports the following reduce operators:

  • count — total number of answers, or, when used with a variable, number of distinct values of the variable,

  • max — the maximum value of the variable,

  • min — the minimum value of the variable,

  • mean — the arithmetic mean of the values of the variable,

  • median — the median value of the variable,

  • std — the sample standard deviation of the values of the variable,

  • sum — the sum of the values of the variable.

Examples

Schema for the following examples
#!test[schema, commit]
define
  entity content owns id;
  entity page sub content,
    owns page-id,
    owns name;
  entity profile sub page,
    owns username;
  entity user sub profile,
    owns phone,
    owns karma;

  attribute id value string;
  attribute page-id sub id;
  attribute username sub page-id;
  attribute name value string;
  attribute phone value string;
  attribute karma value double;
attribute start-date, value date;
relation friendship relates friend @card(0..2), owns start-date;
user plays friendship:friend;
  attribute last-login, value date;
  user owns last-login;

  attribute size-kb, value double;
  entity file, owns size-kb;

  relation located, relates country, relates user;
  entity country, plays located:country;
  user plays located:user;

Count the number of logins since 2025-01-01:

#!test[read]
match
  $user isa user, has last-login >= 2025-01-01;
reduce $logins = count;

Get disk usage statistics of the files:

#!test[read]
match
  $file isa file, has size-kb $s;
reduce $total = sum($s), $mean = mean($s), $max = max($s);

Grouping

When groupby is used within a reduce, the answer stream is subdivided into groups based on the value of the grouping variable. The reduction is then performed separately within each such group. The output of a reduce with groupby is a stream of rows, one for each value of the grouping variable.

Syntax

reduce <var> = <operator> [ (<var>) ] [ , ... ] groupby <var>;

Example

Get the number of users per country:

#!test[read]
match
  $user isa user;
  $country isa country;
  {
    located($user, $country);
  } or {
    located($user, $place);
    located($place, $country);
  };
reduce $user-count = count groupby $country;