外部ID和插入块 (External IDs and Upsert Block)

upsert块使得管理外部id很容易。

首先,设置如下Schema

xid: string @index(exact) .
<http://schema.org/name>: string @index(exact) .
<http://schema.org/type>: [uid] @reverse .

然后设置类型:

{
  set {
    _:blank <xid> "http://schema.org/Person" .
    _:blank <dgraph.type> "ExternalType" .
  }
}

现在您可以创建一个新的person并使用upsert块添加其类型:

upsert {
    query {
      var(func: eq(xid, "http://schema.org/Person")) {
        Type as uid
      }
      var(func: eq(<http://schema.org/name>, "Robin Wright")) {
        Person as uid
      }
    }
    mutation {
        set {
          uid(Person) <xid> "https://www.themoviedb.org/person/32-robin-wright" .
          uid(Person) <http://schema.org/type> uid(Type) .
          uid(Person) <http://schema.org/name> "Robin Wright" .
          uid(Person) <dgraph.type> "Person" .
        }
    }
  }

还可以删除person并分离Typeperson节点之间的关系。这和上面是一样的,但是你使用了关键字delete而不是sethttp://schema.org/Person将保留,但Robin Wright将被删除:

upsert {
    query {
      var(func: eq(xid, "http://schema.org/Person")) {
        Type as uid
      }
      var(func: eq(<http://schema.org/name>, "Robin Wright")) {
        Person as uid
      }
    }
    mutation {
        delete {
          uid(Person) <xid> "https://www.themoviedb.org/person/32-robin-wright" .
          uid(Person) <http://schema.org/type> uid(Type) .
          uid(Person) <http://schema.org/name> "Robin Wright" .
          uid(Person) <dgraph.type> "Person" .
        }
    }
  }

再次查询一个用户:

{
  q(func: eq(<http://schema.org/name>, "Robin Wright")) {
    uid
    xid
    <http://schema.org/name>
    <http://schema.org/type> {
      uid
      xid
    }
  }
}