Neo4j插入具有各种关系的节点

Neo4j insert nodes with various relationships

本文关键字:关系 节点 插入 Neo4j      更新时间:2024-04-15

我尝试创建"配方"、"配料"answers"用户"节点(作者)。

基本上,一个作者可以有很多食谱;食谱与配料有着多对多的关系。

我有这个问题:

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

但是,我得到错误:

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

这个查询的正确形式是什么?

我的js代码:

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);            
    });
};

我认为问题在于with子句引用了要创建的下一个节点,而不是引用了要新建的上一个节点。此外,代码试图创建无向关系。

试试这个:

MATCH(用户:用户)WHERE ID(用户)={uid}CREATE(配方:配方{名称:"receta 4"})WITH配方MATCH(配料:配料)其中id(成分)=7CREATE(配方)-[ri:HAS{单位:"vasos",cant:1}]->(配料)WITH配方MATCH(配料:配料)WHERE ID(成分)=6CREATE(配方)-[ri:HAS{单位:"cditas",cant:2}]->(配料)CREATE(用户)-[:PREPARE]->(配方)RETURN配方