cancel
Showing results for 
Search instead for 
Did you mean: 

Best cypher query for having a match on multiple relations

wplumot
Node

I am a bit new here ...but I have a node with one or more relation of the same type:
(RR)-[:has_bol]->(BB)
RR can have many BB

So RR can have many relations pointing to BB with property 'Code'.
Say we have:
RR1 has_bol with BB.Code: 'ab'
RR2 has_bol with BB.Code: 'abc'
RR2 has_bol with BB.Code: 'xc'
RR3 has_bol with BB.Code: 'xca'
RR3 has_bol with BB.Code: 'xc6'
RR3 has_bol with BB.Code: 'xcga'
..... 1000things further
RRx has_bol with BB.Code: 'anything'

I need a query with no performance issue that gets all the RR nodes with BB nodes where BB contains 'xc'.

If RR has 3 relations to BB with one match on BB, the query returns RR with 3 BB nodes, not one BB.

In our example above it will return RR2 with the two nodes of BB (abc, xx) and also RR3 with 3 nodes of BB ('xca', 'xc6', 'xcga')

How can one make that one work.
You can compare it with the stuff command in SQL, which have performance issues with big data.

3 REPLIES 3

ameyasoft
Graph Maven
Try this:
To return BB (abc, xx) :
MATCH (RR)-[:has_bol]->(BB)
WHERE BB.Code = 'xx' or BB.Code ENDS WITH 'c'
RETURN RR, BB

To return BB ('xca', 'xc6', 'xcga')
MATCH (RR)-[:has_bol]->(BB)
WHERE BB.Code BEGINS WITH 'xc'
RETURN RR, BB


Thank you, I thought I was doing things wrong but it seems that the simple solutions are just fine.
Start to love Neo4j

clem
Graph Steward

You might want to look at this training, especially the part about refactoring and using multiple Labels on a Node.

See:

Nodes 2022
Nodes
NODES 2022, Neo4j Online Education Summit

On November 16 and 17 for 24 hours across all timezones, you’ll learn about best practices for beginners and experts alike.