Redplane
Redplane

Reputation: 3151

Base on condition, create node and return value

In my neo4j database, I have 2 node types:

public class Warrior
{
    public string Id{get;set}
    public string Name{get;set;}
}

public class Weapon
{
    public string Id{get;set;}
    public string Name{get;set;}
}

And I want my query has the same function like this :

var warrior = Match(warrior.Id == 1)
var weapon = Match(weapon.Id == 2)

if (warrior == null)
    return 0;

if (weapon == null)
    return 1;

CreateConnection(warrior-[:HAS]->Weapon)
return 2;

Thank you.

P/S : Neo4j or Neo4jClient query is accepted, I can convert them to each other.

Upvotes: 1

Views: 149

Answers (1)

Anomaly211
Anomaly211

Reputation: 1103

The following query should do what you require.

optional match (warrior:Warrior) where warrior.id=1 with warrior
optional match (weapon:Weapon) where weapon.id=2 with warrior,weapon,
case when exists(warrior.id) and exists(weapon.id) then 2 when exists(weapon.id) then 1 else 0 end as output
foreach(temp in case when output=2 then [1] else [] end | 
    create (warrior)-[:Has]->(weapon)
)
return warrior,weapon

we use optional match instead of match so that the query does not fail if match is not succeeded.

We use a case statement to check if the ID value of the variable for warrior or weapon exists and store the resulting value (0 or 1 or 2) in an output variable.

Next we use the foreach loop case trick to check if the output has the value 2 and execute the create statement.

(reference for the trick. http://www.markhneedham.com/blog/2014/08/22/neo4j-load-csv-handling-empty-columns/)

Upvotes: 1

Related Questions