2015-02-24 133 views
1

我試圖創建「配方」,「成分」和「用戶」節點(作者)。Neo4j插入節點與各種關係

基本上,作者可以有很多食譜;食譜與成分有着多對多的關係。

我有這個疑問:

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

@HoaParis的感謝!我說西班牙語:P – brunocascio 2015-02-24 17:50:04

回答

2

我相信這個問題是使用WITH子句引用要創建的下一個節點,而不是引用以前的節點被創建。此外,代碼正試圖創建無向關係。

試試這個:

 
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 
+0

優秀!非常感謝! – brunocascio 2015-02-24 17:48:54

+0

是的,配方關係<->成分是無向的,因爲一些查詢搜索是爲一種成分獲取所有食譜。 – brunocascio 2015-02-24 19:03:30

+1

CREATing時不支持未引導(您會看到一個錯誤)。您可以在兩個方向創建關係,也可以在將來進行MATCH查詢時查詢沒有方向性。請參閱http://stackoverflow.com/questions/24010932/neo4j-bidirectional-relationship – 2015-02-24 19:36:04