Database Reference
In-Depth Information
Working with relationships
Let's understand the process of defining relationships in the form of Cypher queries in the
same way as you did in the previous section while working with nodes:
• How do we get nodes that are associated or have relationships with other nodes?
Answer : MATCH (n)-[r]-(n1) RETURN n,r,n1;
Explanation : We are instructing Cypher to scan the complete database
and capture all nodes, their relationships, and nodes with which they have
relationships in variables n , r , and n1 and then further return/print the
results on your Neo4j shell. Also, in the preceding query, we have used -
and not -> as we do not care about the direction of relationships that we
retrieve.
• How do we get nodes, their associated properties that have some specific type of
relationship, or the specific property of a relationship?
Answer : MATCH (n)-[r:ACTED_IN {Role : "Rocky
Balboa"}]->(n1) RETURN n,r,n1;
Explanation : We are instructing Cypher to scan the complete database
and capture all nodes, their relationships, and nodes, which have a rela-
tionship as ACTED_IN and with the property of Role as Rocky Bal-
boa . Also, in the preceding query, we do care about the direction (in-
coming/outgoing) of a relationship, so we are using -> .
Note
For matching multiple relations replace [r:ACTED_IN] with [r:ACTED_IN
| DIRECTED] and use single quotes or escape characters wherever there are
special characters in the name of relationships.
• How do we get a coartist?
Answer : MATCH (n {Name : "Sylvester Stallone"})-
[r]->(x)<-[r1]-(n1) return n.Name as
Artist,type(r),x.Title as Movie, type(r1),
n1.Name as Artist2;
Explanation : We are trying to find out all artists that are related to
Sylvester Stallone in some manner or the other. Once you run
the preceding query, you will see something like the following image,
which should be self-explanatory. Also, see the usage of as and type .
as is similar to the SQL construct and is used to define a meaningful
Search WWH ::




Custom Search