DevHero
DevHero

Reputation: 17

Neo4JClient 3.1 to 5.1 update query that match two nodes and create relationship

I am struggling to update my code that uses Neo4JClient v3.x to work with the latest Neo4J server and Neo4jClient v5.x.

my query basically will create 2 nodes and a relationship between them. if any node or both nodes does not exist, they will be created along the relationship

old working query:

query1 = client.Cypher
    .Match("(e1:Entity)", "(e2:Entity)")
    .Where("e1.Id={id1} and e2.Id={id2}")
    .WithParam("id1", id1)
    .WithParam("id2", id2)
    .WithParam("line", line)
    .Merge("(e1)-[r:REF {LINE:{line}}]->(e2)");

above code does not work in the new version of Neo4j server / Neo4jClient my attempt to modify it currently create duplicate nodes instead of unique ones

query1 = client.Cypher
    .Create("(e1:Entity $id1)")
    .Create("(e2:Entity $id2)")
    .WithParam("id1",new { Id = id1 })
    .WithParam("id2", new { Id = id2 })
    .WithParam("line", line)
    .Create("(e1)-[r:REF {LINE:$line}\]->(e2)");

can you help me convert the first query above to work in the newer version ?

Upvotes: 0

Views: 71

Answers (1)

Charlotte Skardon
Charlotte Skardon

Reputation: 6270

Your first query does a MATCH at the beginning, which would never have CREATEd e1 or e2 - you would need to use MERGE to achieve what you're after.

This query:

query1 = client.Cypher
    .Merge("(e1:Entity {Id: $id1})")
    .Merge("(e2:Entity {Id: $id2})")
    .Merge("(e1)-[r:REF {LINE:$line}]->(e2)")
    .WithParams(new { id1, id2, line });

should do what you actually want.

e1 and e2 would be CREATEd if they are not in the database, or MATCHed if they are in the database.

You might want to consider if you want the relationship done in the same way, in which case, swap .Create(...) to be .Merge(...)

EDIT: I noticed in your original query that you did in fact MERGE the relationship, so I've updated the code accordingly.

Upvotes: 1

Related Questions