External IDs - Mutations

Dgraph’s input language, RDF, also supports triples of the form <a_fixed_identifier> <predicate> literal/node and variants on this, where the label a_fixed_identifier is intended as a unique identifier for a node. For example, mixing schema.org identifiers, the movie database identifiers and blank nodes:

_:userA <http://schema.org/type> <http://schema.org/Person> .
_:userA <dgraph.type> "Person" .
_:userA <http://schema.org/name> "FirstName LastName" .
<https://www.themoviedb.org/person/32-robin-wright> <http://schema.org/type> <http://schema.org/Person> .
<https://www.themoviedb.org/person/32-robin-wright> <http://schema.org/name> "Robin Wright" .

As Dgraph doesn’t natively support such external IDs as node identifiers. Instead, external IDs can be stored as properties of a node with an xid edge. For example, from the above, the predicate names are valid in Dgraph, but the node identified with <http://schema.org/Person> could be identified in Dgraph with a UID, say 0x123, and an edge

<0x123> <xid> "http://schema.org/Person" .
<0x123> <dgraph.type> "ExternalType" .

While Robin Wright might get UID 0x321 and triples

<0x321> <xid> "https://www.themoviedb.org/person/32-robin-wright" .
<0x321> <http://schema.org/type> <0x123> .
<0x321> <http://schema.org/name> "Robin Wright" .
<0x321> <dgraph.type> "Person" .

An appropriate schema might be as follows.

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

Query Example: All people.

{
  var(func: eq(xid, "http://schema.org/Person")) {
    allPeople as <~http://schema.org/type>
  }
  q(func: uid(allPeople)) {
    <http://schema.org/name>
  }
}

Query Example: Robin Wright by external ID.

{
  robin(func: eq(xid, "https://www.themoviedb.org/person/32-robin-wright")) {
    expand(_all_) { expand(_all_) }
  }
}

Note xid edges are not added automatically in mutations. In general it is a user’s responsibility to check for existing xid’s and add nodes and xid edges if necessary. Dgraph leaves all checking of uniqueness of such xid’s to external processes.


This is a companion discussion topic for the original entry at https://dgraph.io/docs/mutations/external-ids/