4

I am having 2 nodes lets say of 2 type 'Student' and 'Class'

Student have {id, name}.
Class have {id, name}.

Student can have optional relationship with Class node as 'ATTENDS'.

(s:Student)-[r:ATTENDS]->(c:Class).

[r:ATTENDS] - Optional relationship. (present or may not present)

I want student record as it's all properties. If present relationship then class_name will match with present "Class" node else class_name will be null.

{student_id,student_name,class_name}

I tried by cypher query, but not getting result. Please help.

OPTIONAL MATCH (s:Student)-[:ATTENDS]->(c:Class) WHERE s.id =1
RETURN s.id AS student_id , s.name as student_name, c.name as class_name

By this query, if relationship exists then all values, if no relationship exists then all values are null.

David Makogon
  • 69,407
  • 21
  • 141
  • 189
Somnath Muluk
  • 55,015
  • 38
  • 216
  • 226

3 Answers3

5

If you don't care about the type of relation, you could run

MATCH (student:Student {id :1}) 
OPTIONAL MATCH (s)-->(class:Class)
RETURN student.id, student.name, class.name

and you'll have no need to set aliases.

David
  • 2,987
  • 1
  • 29
  • 35
2

Got solution to this problem by trying different queries.

MATCH (s:Student {id :1}) 
OPTIONAL MATCH (s)-[:ATTENDS]->(c:Class)
RETURN s.id AS student_id , s.name as student_name, c.name as class_name

Need to first match required criteria and then optional match. If anyone have simpler solution then please post.

Somnath Muluk
  • 55,015
  • 38
  • 216
  • 226
1

Wrote a graph-gist for this at http://gist.neo4j.org/?11110772

The short answer is:

MATCH (s:Student) OPTIONAL MATCH (s)-->(c:Course)
RETURN s.name, c.name

Read the gist for more details. http://gist.neo4j.org/?11110772

Note that you cannot ignore the first MATCH. If the entire query is optional, nothing will be retrieved. In SQL you also have a non optional query on one table and then a left join to the second, optional, table.

Craig Taverner
  • 759
  • 4
  • 5