Skip to content

RETURN clause

Marijn van Wezel edited this page Dec 15, 2022 · 4 revisions

The RETURN clause defines what to include in the query result set. It takes a set of expression to return, and an optional parameter specifying whether the return should be DISTINCT.

Query::returning(Alias|AnyType|mixed[]|bool|float|int|Pattern|string|(Alias|AnyType|mixed[]|bool|float|int|Pattern|string)[] $expressions, bool $distinct = false): Query

Parameters

  • $expressions : A single expression to return, or a non-empty list of expressions to return.
  • $distinct : Whether to be a RETURN DISTINCT clause.

Relevant methods

  • addColumn(Alias|AnyType|mixed[]|bool|float|int|Pattern|string ...$columns): self : Add one or more values to return.
  • setDistinct(bool $distinct = true): self : Sets whether this query only return unique rows.

Examples

Return nodes

$n = node()->withProperties(['name' => 'B']);
$query = query()
    ->match($n)
    ->returning($n)
    ->build();

$this->assertStringMatchesFormat("MATCH (%s {name: 'B'}) RETURN %s", $query);

Return relationships

$r = relationshipTo()->addType('KNOWS');
$query = query()
    ->match(node()->withProperties(['name' => 'A'])->relationship($r, node()))
    ->returning($r)
    ->build();

$this->assertStringMatchesFormat("MATCH ({name: 'A'})-[%s:KNOWS]->() RETURN %s", $query);

Return property

$n = node()->withProperties(['name' => 'A']);
$query = query()
    ->match($n)
    ->returning($n->property('name'))
    ->build();

$this->assertStringMatchesFormat("MATCH (%s {name: 'A'}) RETURN %s.name", $query);

Variable with uncommon characters

$n = node()->withVariable('This isn\'t a common variable name');
$query = query()
    ->match($n)
    ->where($n->property('name')->equals('A'))
    ->returning($n->property('happy'))
    ->build();

$this->assertSame("MATCH (`This isn't a common variable name`) WHERE (`This isn't a common variable name`.name = 'A') RETURN `This isn't a common variable name`.happy", $query);

Column alias

$a = node()->withProperties(['name' => 'A']);
$query = query()
    ->match($a)
    ->returning($a->property('age')->alias('SomethingTotallyDifferent'))
    ->build();

$this->assertStringMatchesFormat("MATCH (%s {name: 'A'}) RETURN %s.age AS SomethingTotallyDifferent", $query);

Other expressions

$a = node()->withProperties(['name' => 'A']);
$query = query()
    ->match($a)
    ->returning([$a->property('age')->gt(30), "I'm a literal"])
    ->build();

$this->assertStringMatchesFormat("MATCH (%s {name: 'A'}) RETURN (%s.age > 30), 'I\\'m a literal'", $query);

Unique results

$b = node();
$query = query()
    ->match(node()->withProperties(['name' => 'A'])->relationshipTo($b))
    ->returning($b, true)
    ->build();

$this->assertStringMatchesFormat("MATCH ({name: 'A'})-->(%s) RETURN DISTINCT %s", $query);

External links