2
votes

So as a complication to this question, I basically want to do

MATCH (n:TEST) OPTIONAL MATCH (n)-[r]->() RETURN DISTINCT n, r

And I want to return n and r as one column with no repeat values. However, running

MATCH (n:TEST) OPTIONAL MATCH (n)-[r]->() UNWIND n+r AS x RETURN DISTINCT x

gives a "Type mismatch: expected List but was Relationship (line 1, column 47)" error. And this query

MATCH (n:TEST) RETURN DISTINCT n UNION MATCH ()-[n]->() RETURN DISTINCT n

Puts nodes and relationships in the same column, but the context from the first match is lost in the second half.

So how can I return all matched nodes and relationships as one minimal list?

UPDATE:

This is the final modified version of the answer query I am using

MATCH (n:TEST) OPTIONAL MATCH (n)-[r]->() RETURN n {.*, rels:collect(r {properties:properties(r), id:id(r), type:type(r), startNode:id(startNode(r)), endNode:id(endNode(r))})} as n

1

1 Answers

5
votes

There are a couple ways to handle this, depending on if you want to hold these within lists, or within maps, or if you want a map projection of a node to include its relationships.

If you're using Neo4j 3.1 or newer, then map projection is probably the easiest approach. Using this, we can output the properties of a node and include its relationships as a collected property:

MATCH (n:TEST) 
OPTIONAL MATCH (n)-[r]->() 
RETURN n {.*, rels:collect(r)} as n

Here's what you might do if you wanted each row to be its own pairing of a node and a single one of its relationships as a list:

...
RETURN [n, r] as pair

And as a map:

...
RETURN {node:n, rel:r} as pair

EDIT

As far as returning more data from each relationship, if you check the Code results tab, you'll see that the id, relationship type, and start and end node ids are included, and accessible from your back-end code.

However, if you want to explicitly return this data, then we just need to include it in the query, using another map projection for each relationship:

MATCH (n:TEST) 
OPTIONAL MATCH (n)-[r]->() 
RETURN n {.*, rels:collect(r {.*, id:id(r), type:type(r), startNode:startNode(r), endNode:endNode(r)})} as n