0
点赞
收藏
分享

微信扫一扫

dgraph 创建节点和边的时候判断节点是否存在,如果存在,就不创建,如果不存在,则创建


neo4j里面有一个merge的操作,能够自动帮助我们来判断节点和边在数据库里面属否存在,dgraph有没有呢,答案是有的,就是upsert,我的示例代码:

upsert {
query {
var(func: eq(person_id, "xxx")) {
Person as uid
}
var(func: eq(company_id, "yyy")) {
Company as uid
}
}
mutation {
set {
uid(Person) <name> "罗志祥" .
uid(Person) <person_id> "xxx" .
uid(Person) <manager> uid(Company) (position="CEO") .
uid(Person) <dgraph.type> "Person" .
uid(Company) <name> "无名公司" .
uid(Company) <dgraph.type> "Company" .
uid(Company) <company_id> "yyy" .
}
}
}

来看看官网怎么解释的:

To use ​​upsert operations​​​ on a predicate, specify the ​​@upsert​​​ directive in the schema. When committing transactions involving predicates with the ​​@upsert​​ directive, Dgraph checks index keys for conflicts, helping to enforce uniqueness constraints when running concurrent upserts.

我的schema为:

<person_id>: string @index(exact) @upsert .
<name>: string @index(term) .
<company_id>: string @index(hash) @upsert .

是不是很简单呢。

怎么验证呢,多moute几次,然后用下面的语句查一下,看有没有重复:

{
data(func: eq(person_id, "xxx")) {
name
person_id
manager @facets(orderasc:position) {
name
company_id
}
}
}

参考文献

[1]. ​​https://dgraph.io/docs/master/mutations/#upsert-block​​

[2].External IDs and Upsert Block. ​​https://dgraph.io/docs/mutations/#external-ids-and-upsert-block​​

举报

相关推荐

0 条评论