Search code examples
neo4jcypherpy2neo

Neo4j: Join existing nodes in neo4j graph


Problem statement: Add two input nodes n1 and n2 with edge directed n1-[:rel]->n2

1. if n1-[:rel]->n2 exists ignore
2. if n1 and n2 exists but not with [:rel]
   create a new relationship edge between the existing nodes
3. if n1 doesnt exist
   create n1 and join n1 and existing n2 with edge [:rel]
4. if n2 doesnt exist
   create n2 and join n2 and existing n1 with edge [:rel]

Query:

 INSERT_QUERY = ''' FOREACH(t IN {term_mod_pair_list}| 
    MERGE(tt:target_Word {type:'target_term',word:t[0]['word'],pos:t[0]['tag']})- 
    [:MODIFIER]->(mod:mod_Word {type:'a-mod',word:t[1]['word'],pos:t[0]['tag']}) ) '''

I find merge is creating duplicate nodes, after some finding i see merge matches exact pattern. so if n1-[:rel]->n2 exist , new addition of relationship n1-[:rel]->n3 will create another new node n1

I have explained my problem above. how can I achieve it.


Solution

  • This will cover all four points with the additional point of:

    If n1 and n2 don't exist, create n1 and n2 and join with edge [:rel].

    MERGE (n1:Label {unique_prop: "unique_value"})
    MERGE (n2:Label {unique_prop: "unique_value"})
    MERGE (n1)-[:rel]->(n2);