cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

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).
3X_1_0_10a34ef6f1318b3e8ef95b37fdf02990b537ecd5.png

However, when I find the nodes, it creates an extra parent node between (13) and (21) which I do not want.
3X_2_2_22911c16316baec38702762ff4591a46483e27fe.png

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?

Comments
glilienfield
Ninja
Ninja

Can you provide a script to create your test data?

glilienfield
Ninja
Ninja

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)

sanna_aizad
Node Link

Thank you, this does the trick!

Version history
Last update:
‎02-28-2022 07:00 AM
Updated by:
Contributors