Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.
on 02-28-2022 07:00 AM
I want to create parent nodes (intermediate nodes) for a linked list. In the nodes below, I want a parent node with head at (13) and tail at (17) and another one with head at (17) and tail at (21).
However, when I find the nodes, it creates an extra parent node between (13) and (21) which I do not want.
Here is the code:
//Finding the First Node based on a relationship:
MATCH (a:Alternate)
MATCH (firstnode:Original)
MATCH (firstnode)-[t:ALT]->(a) //a is first Alternate node
CALL
{
WITH a
MATCH (lastnode:Original)
MATCH p = (a)-[:ALT*]->(lastnode)
WITH reduce(output = [], node IN nodes(p) | output + node) as lastNodeCollection, MAX(length(p)) AS max
WITH lastNodeCollection[max] AS last
Return last
}
CALL
{
with firstnode, last
MERGE (last)<-[:LAST]-(v:Parent)-[:FIRST]->(firstnode)
}
Return firstnode, last
Any idea on what I can do to the code to get the desired results?
Can you provide a script to create your test data?
You will get the same results with the following query:
match(first:Original)-[:ALT*]->(last:Original)
merge(last)<-[:LAST]-(v:Parent)-[:FIRST]->(first)
The cause of your problem is in the variable length match statement. There are two paths satisfying the pattern for the '13' node, that is '13'->'17' and '13'->'21'. You can add a constraint to your pattern to only find paths that have two :Original nodes, not more. This would eliminate the path from '13'->'21'.
Try this:
match p=(first:Original)-[:ALT*]->(last:Original)
where size([i in nodes(p) where i:Original])=2
merge (last)<-[:LAST]-(v:Parent)-[:FIRST]->(first)
Thank you, this does the trick!