1
votes

I have a graph network as shown below

enter image description here

What I want is to get "only" the longest path between Node 1 and Node 4. I have written the query as follows for it:

MATCH p = ((n {name: '1'})-[:Relation*..]-(n1{name: '4'}))
WITH max(length(p)) AS pathLength
MATCH p1 = ((n {name: '1'})-[:Relation*..]-(n1{name: '4'}))
WHERE length(p1) = pathLength
RETURN p1

However, the query returns all the relationships between the nodes (the image above is actually the result of the query) that are a part of the path, is there any way to avoid that?

New to Neo4j, any help would be appreciated.

Thanks

1

1 Answers

1
votes

You are using the pathLength of all the possible paths between n and n1. Try ordering and limiting pathLength:

MATCH p = ((n {name: '1'})-[:Relation*..]-(n1{name: '4'}))
WITH length(p) AS pathLength
ORDER BY pathLength DESC // greater path lengths first
LIMIT 1 // get only the greatest
MATCH p1 = ((n {name: '1'})-[:Relation*..]-(n1{name: '4'}))
WHERE length(p1) = pathLength
RETURN p1

Edit:

Also, have tried providing a static value (3) in the where condition. Didn't seem to change anything.

Probably the option "Connect result nodes" of your Neo4j Browser is enable. When this option is enabled the Neo4j Browser will try to connect the resultant nodes in the Graph Visualization Mode. To disable it To achieve the desired result you should go to the section "Graph Visualization" of Neo4j Browser Settings and uncheck the option "Connect result nodes" as show in the image below:

Graph visualization settings

The "extra" relationships are shown only in the graph visualization mode. If you change to Table, Text or Code these relationship are not shown.