在 Neo4j 中创建关系而不重新创建节点

问题描述 投票:0回答:1

我目前正在使用 Neo4j 开发一个项目,我面临着在不重新创建节点的情况下创建关系的挑战。以下是该场景的简要概述: 想要在现有用户、新帖子和多个类别(已存在)之间建立关系。

我的目标是在现有用户、新创建的帖子和多个预先存在的类别之间建立关系。然而,问题在于,不仅创建了关系,还生成了多个帖子。

以下是当前的 Cypher 查询:

MATCH (user:User {username: 'your_username'})
MATCH (categories:Category)
WHERE ID(categories) IN [1, 2, 3]

// Create a new post node (you can adjust this part based on your post structure)
CREATE (post:TPost {title: 'Post Title', content: 'Post Content', createdAt: timestamp()})

// Create relationships between the user and the post
CREATE (user)-[:POSTED]->(post)

WITH post, COLLECT(categories) AS categoryList

// this part should create relationships only 
FOREACH (category IN categoryList | 
    CREATE (post)-[:BELONGS_TO]->(category) 
);

database graph neo4j cypher graph-databases
1个回答
0
投票

您的第二个

MATCH
返回 3 个
Category
节点,因此作为
CREATE (:TPost)
子句输入的表有 3 行,这意味着
CREATE
发生 3 次,创建 3 个帖子。

CREATE (:TPost)
移至获取 3 个
Category
节点之前,它只会执行一次(假设
User
只有一个匹配项):

MATCH (user:User {username: 'your_username'})
CREATE (post:TPost {title: 'Post Title', content: 'Post Content', createdAt: timestamp()})
CREATE (user)-[:POSTED]->(post)
WITH post
MATCH (categories:Category)
WHERE id(categories) IN [1, 2, 3]
CREATE (post)-[:BELONGS_TO]->(category);
© www.soinside.com 2019 - 2024. All rights reserved.