brunocascio
brunocascio

Reputation: 1986

Neo4j insert nodes with various relationships

I tried to create "recipe", "ingredients" and "user" nodes (author).

Basically, an author can have many recipes; and recipes have a many-to-many relationship with ingredients.

I have this query:

MATCH (user:User)
WHERE ID(user) = {uid}
CREATE (recipe:Recipe {name:"receta 4"})
WITH ingredient
MATCH (ingredient:Ingredient)
WHERE ID(ingredient) = node(7)
CREATE (recipe)-[ri:HAS {unit: "vasos", cant: 1}]-(ingredient)
WITH ingredient
MATCH (ingredient:Ingredient)
WHERE ID(ingredient) = node(6)
CREATE (recipe)-[ri:HAS {unit: "cditas", cant: 2}]-(ingredient)
CREATE (user)-[:PREPARE]->(recipe)
RETURN recipe

But, i get error:

ingredient not defined (line 4, column 7)
"WITH (ingredient:Ingredient)"
       ^
Neo.ClientError.Statement.InvalidSyntax

Which is the correct form for this query?

My js code:

Recipe.create = function (req, callback) {

    var data = req.body;
    var uid = parseInt(req.params.id);

    var query = [
        'MATCH (user:User)',
        'WHERE ID(user) = {uid}',
        'CREATE (recipe:Recipe {data})',
    ];

    // set ingredients
    var ingId;
    var unit;
    var cant;
    for (var i = data.ingredients.length - 1; i >= 0; i--) {
        ing   = data.ingredients[i];
        ingId = parseInt(ing.id);
        unit  = ing.unit;
        cant  = ing.cant;
        query.push(
            'MATCH (ingredient:Ingredient)',
            'WHERE ID(ingredient) = node(' + ingId + ')',
            'CREATE (recipe)-[ri:HAS {unit: "'+unit+'", cant: '+cant+'}]-(ingredient)'
        );    
    }

    query.push(
        'CREATE (user)-[:PREPARE]->(recipe)',
        'RETURN recipe'
    );

    query.join("\n");

    db.cypher({
        query:query, 
        params:{
            data: data,
            uid: uid
        }
    }, function (err, results) {
        if (err) return callback(err);
        console.log(results)
        callback(null, results);            
    });
};

Upvotes: 1

Views: 112

Answers (1)

Ryan Boyd
Ryan Boyd

Reputation: 3018

I believe the issue is with the WITH clause referencing the next node to be created, rather than referencing the previous node to be created. Additionally, the code is trying to create undirected relationships.

Try this:

MATCH (user:User)
WHERE ID(user) = {uid}
CREATE (recipe:Recipe {name:"receta 4"})
WITH recipe
MATCH (ingredient:Ingredient)
WHERE id(ingredient) = 7
CREATE (recipe)-[ri:HAS {unit: "vasos", cant: 1}]->(ingredient)
WITH recipe
MATCH (ingredient:Ingredient)
WHERE ID(ingredient) = 6
CREATE (recipe)-[ri:HAS {unit: "cditas", cant: 2}]->(ingredient)
CREATE (user)-[:PREPARE]->(recipe)
RETURN recipe

Upvotes: 2

Related Questions