Neo4j more efficient Cypher query for finding connected nodes with a relationship
Clash Royale CLAN TAG#URR8PPP
Neo4j more efficient Cypher query for finding connected nodes with a relationship
I have a patch where I know a starting and end node with an unknown number of nodes between the 2. I wish to collect a collection of nodes and each nodes exiting relationship in the chain.
PROFILE MATCH p = (:Questionid:'1234')-[:Answer*0..3]->(t)-
[:Answer]->(:Questionid:'5678')
WHERE t:Set OR t:Read
OPTIONAL MATCH (x)-[v:Answer]->(y)
WHERE x.id <> '1234' and x IN nodes(p) AND v IN rels(p)
return x,v
This query is pretty inefficient as the OPTIONAL MATCH (x)-[v:Answer]->(y)
requires a full nodes scan.
OPTIONAL MATCH (x)-[v:Answer]->(y)
I know that t
and as a result x
will be of types Set
or Read
which would reduce the scan quite a bit but don't think there is a way to query this.
t
x
Set
Read
Is there any way to optimise this?
1 Answer
1
You can simply unwind the path you have already got:
MATCH p = (:Questionid:'1234')-[:Answer*0..3]->(t)-[:Answer]->(:Questionid:'5678')
WHERE t:Set OR t:Read
WITH nodes(p) AS nds,
rels(p) AS rls
UNWIND range(1, length(nds)-2) AS i
RETURN nds[i] AS x,
rls[i] AS v
@Sheff But why? The lengths of arrays of nodes and relations are already known.
– stdob--
Aug 10 at 14:24
@Sheff Of course, you can add a check that the length of an array of nodes is greater than two.
– stdob--
Aug 10 at 14:26
I see what you mean. The issue is that the path I am querying may not exist (which I didn't mention in my question) hence the possibility of a null
nds
– Sheff
Aug 10 at 14:32
nds
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
That looks great! I assume the range function will need some check for null as there may be no nodes in the path?
– Sheff
Aug 10 at 14:19