Officially out now: The TypeDB 3.0 Roadmap >>

Negations

Negations can be used to exclude certain subpatterns from your query results.

Syntax

not { <pattern> };

The patterns inside a negated is called the excluded pattern.

Like all patterns, negations can be chained, e.g.:

not { <p1> };
not { <p2> };

which is equivalent to a negated disjunction not { { <p1> } or { <p2> }; };.

Since negations are themselves patterns, they can also be nested, e.g.:

not {
  <p1>
  not { <p2> };
};

Behavior

Negations may appear in match stages of data pipelines or functions, where they behave as follows.

  • Internal variables. Variable whose scope lies inside an excluded pattern are not returned as part of the stage’s output (i.e., such variables are internal variables).

  • Satisfaction. A pattern with a negation will return those outputs which satisfy the pattern outside the negation, but do not satisfy the excluded pattern for any choice of internal variables in that pattern.

  • Recursion. When using recursive function with negations care need to be taken that evaluation of the negation does not depend on the recursive function call itself (in other words, TypeDB works with stratified negation).

Examples

  1. Retrieve users without friends

    match
      $x isa user, has username $name;
      not { friendship($x, $y); };
  2. Retrieve users without friends that have no friends

    match
      $x isa user, has username $name;
      not { friendship($x, $y);
        not { friendship($y, $z); };
      };

    Negated queries (especially nested negations) can become expensive.