检查节点是否存在,如果不存在则创建 [英] Check whether a node exists, if not create

查看:40
本文介绍了检查节点是否存在,如果不存在则创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个数据库,每当一个节点不存在时,它就会创建一个新节点并在这个节点和另一个节点之间建立关系.如果节点存在,则两个节点都建立关系.

Im trying to make a database were everytime a node does't exist it will create a new one and set a relationship between this node and another. If the node exists, both nodes get a relationship.

我的问题是,如果我尝试连接 2 个现有节点,将重新创建第二个节点.我尝试了 MERGE 和 CREATE UNIQUE,两者都不起作用.

My problem is that, if I try to connect 2 existing nodes, the 2nd node will be recreated. I tried with MERGE and CREATE UNIQUE, both didnt work.

我的示例代码:

CREATE (test1 name:'1'})
MATCH (n)
WHERE n.name = '1'
MERGE (n)-[:know {r:'123'}]->(test3 {name:'3'})

MATCH (n)
WHERE n.name = '1'
MERGE (n)-[:know {r:'123'}]->(test2 {name:'2'})

到这里它可以工作,但有:

Till here it works but with:

MATCH (n)
WHERE n.name = '3'
MERGE (n)-[:know {r:'123'}]->(test2 {name:'2'})

它创建一个新节点2"而不是连接到现有节点.

it creates a new node "2" instead of connect to the one exist.

推荐答案

在完整模式上使用 MERGE 时,行为是要么整个模式匹配,要么创建整个模式.MERGE 不会部分使用现有模式 — 它是全部或全部.如果需要部分匹配,可以通过将模式拆分为多个 MERGE 子句来实现. http://docs.neo4j.org/chunked/stable/query-merge.html

MERGE (n)-[:know {r:'123'}]->(test2 {name:'2'}) 将尝试匹配整个模式,因为它匹配不存在,它创造它.你可以做的是:

MERGE (n)-[:know {r:'123'}]->(test2 {name:'2'}) will try to match the entire pattern and since it does not exist, it creates it. What you can do is:

MERGE (n {name: '3'}) //Create if a node with name='3' does not exist else match it
MERGE (test2 {name:'2'}) //Create if a node with name='2' does not exist else match it
MERGE (n)-[:know {r:'123'}]->(test2) //Create the relation between these nodes if it does not already exist

这篇关于检查节点是否存在,如果不存在则创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆