Upsert in DGraph


(Marcus Baffa) #1

Hi,

I am starting to test Dgraph and when I insert two times the same node it generates another one instead of updating the first one. I presumed that dGraph did an upsert.

I am using Scala and the code is very similar to the example. The difference is that the nodes are saved by different actors. Each actors, something like a thread, saves concurrently the nodes. The code is very simple:

val schemaNodes = s"code: string @index(exact) .\n legalName: string @index(term, fulltext) .\n fantasyName: string .\n "
val opNodes = Operation.newBuilder.setSchema(schemaNodes).build
dgraphClient.alter(opNodes)

val channel = ManagedChannelBuilder.forAddress(“localhost”, 9080).usePlaintext(true).build
val blockingStub = DgraphGrpc.newBlockingStub(channel)
val dgraphClient = new DgraphClient(Collections.singletonList(blockingStub))

  import com.google.gson.Gson
  val gson = new Gson // For JSON encode/decode

  val txn = dgraphClient.newTransaction
  import io.dgraph.DgraphProto.Mutation

  try { // Create data

    val json = gson.toJson(merchant)
    val muMerchant = setIgnoreIndexConflict(false)Mutation.newBuilder.setSetJson(ByteString.copyFromUtf8(json)).setIgnoreIndexConflict(true).build
    txn.mutate(muMerchant)setIgnoreIndexConflict(false)
    txn.commit
  } finally {
    txn.discard
  }

Even when I use setIgnoreIndexConflict(false) it keeps creating another node.

How can I make dGraph execute an Upsert instead of an Insert


(Pawan Rawal) #2

You might find this example in Java useful https://github.com/dgraph-io/dgraph4j/blob/master/src/test/java/io/dgraph/AcctUpsertTest.java. You would need to have an @upsert directive in your schema and should check if the node exists before creating another one.


(Marcus Baffa) #3

Thanks. I will check it out