Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use two match statements in a cypher query

Tags:

neo4j

cypher

I'd like to combine two requests into one query and I'm not sure what happens when 2 match statements are used in a single cypher query.

say I have a list of friends and I'd like to see a list of my friends with each of their uncles and siblings listed in a collection. Can I have two match statements that would do the job? e.g.

match friends-[:childOf]->parents-[:brother]->uncles
    , friends-[:childOf]->parents<-[:childOf]-siblings
return friends, collect(siblings), collect(uncles)

However, if I do a query like this, it always returns no results.

like image 477
MonkeyBonkey Avatar asked May 09 '13 15:05

MonkeyBonkey


People also ask

What does match do in Cypher?

Introduction. The MATCH clause allows you to specify the patterns Neo4j will search for in the database. This is the primary way of getting data into the current set of bindings. It is worth reading up more on the specification of the patterns themselves in Patterns.

Is used in Cypher query language to combine the results from multiple queries?

The UNION clause is used to combine the result of multiple queries.

What does merge do in Cypher?

MERGE either matches existing nodes and binds them, or it creates new data and binds that. It's like a combination of MATCH and CREATE that additionally allows you to specify what happens if the data was matched or created. For example, you can specify that the graph must contain a node for a user with a certain name.

How do you create a relationship between two nodes in Neo4j?

To create a relationship between two nodes, we first get the two nodes. Once the nodes are loaded, we simply create a relationship between them. The created relationship is returned by the query.


2 Answers

Since you have already chosen parents in your first match class, you can do like this -

match friends-[:childOf]->parents-[:brother]->uncles
with friends, parents, uncles
match parents<-[:childOf]-siblings
return friends, collect(siblings), collect(uncles)
like image 55
Gopi Avatar answered Sep 24 '22 09:09

Gopi


You may want to make some of those relationships optional. For example, if you find a sibling but you don't find any uncles, this query will return null because it didn't satisfy both match clauses. If you make the end relationships optional then you don't have to satisfy both clauses completely to return data. So:

match friends-[:childOf]->parents-[?:brother]->uncles
    , friends-[:childOf]->parents<-[?:childOf]-siblings
return friends, collect(siblings), collect(uncles)
like image 44
ean5533 Avatar answered Sep 23 '22 09:09

ean5533