cancel
Showing results for 
Search instead for 
Did you mean: 

Longest Path with condition

rinaldo_bonazzo
Node Clone
Hi,
I need to find the longest path between 2 nodes with the relationship HAS_INVOICE 
MATCH p=(f:Company)-[r:HAS_INVOICE*1..10]->(t:Company)
RETURN p;
this query is working fine.
Now I need only the relationship with invoiceState property with value  DUE or OVERDUE 
MATCH p=(f:Company)-[r:HAS_INVOICE*1..10]->(t:Company)
WHERE NOT (f)-[:HAS_INVOICE {invoiceState = 'PAID'}]->(t)
RETURN p;
Error 
Invalid input '[': expected "+" or "-" (line 2, column 15 (offset: 70))
"WHERE NOT (f)-[:HAS_INVOICE {invoiceState = 'PAID'}]->(t)"
               ^

This query is working fine but I'm not able to retrieve the longestpath

MATCH p=(f:Company)-[r:HAS_INVOICE]->(t:Company) 
WHERE 
r.invoiceState in ['DUE', 'OVERDUE']
RETURN p;

Thanks for your help 

Rinaldo 

3 REPLIES 3

Cobra
Ninja
Ninja

Hi @rinaldo_bonazzo 😄

You should use a predicate function

MATCH p=(f:Company)-[:HAS_INVOICE*1..10]->(t:Company) 
WHERE all(r IN relationships(p) WHERE r.invoiceState in ['DUE', 'OVERDUE'])
RETURN p;

Regards,
Cobra

glilienfield
Ninja
Ninja

The error is a result of the equal sign. The correct syntax is the following, which will restrict to a relationship the that property value. 

[:HAS_INVOICE{invoiceState: ‘Paid’}]

you can find the longest path by sorting on the path length and returning the longest. Add the following after your ‘RETURN p’ statement:

ORDER BY length(p) DESC

LIMIT 1

the above solution assumes there is only one longest path, or you just one of the longest at random if there are more than one. I can provide a different solution when there could be multiple, but it seems that should not occur in your case. 

Thanks @glilienfield I expect to retrive the path greater than 3 hops

 

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.