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

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

问题描述

我试图在每个节点都不存在的情况下建立一个数据库,它将创建一个新的数据库并在该节点与另一个节点之间建立关系.如果该节点存在,则两个节点都将建立关系.

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天全站免登陆