Writing only unique nodes based on values not working

I’m noticing when running:

uid := FunctionToGetUidBasedOnValue(value)
if uid == "" {
    CreateNode(value)
}
err := txn.Commit()
if err != nil {
   txn.Discard()
}

I still get duplicate values made of the same value. I want nodes to be unique based on value.
I have used debug and found that multiple goroutines running FunctionToGetUidBasedOnValue(value) with the same value contents are saying that no object exists.

How is this possible?

I thought txn.Commit() forced the get query to happen at the same time as the Mutate, and if the get failed, it would fail the Mutate.

It sounds like you want to upsert an edge here. You can use the @upsert directive in your schema to do upserts. https://docs.dgraph.io/query-language/#upsert-directive

Commit does not “batch up” all the transaction operations (queries, mutations) in one go (if it did, you wouldn’t get query or mutation responses without calling Commit). Commit tells Dgraph to try and persist all the changes in the commit or abort if there’s a conflict.

2 Likes

Thanks Daniel. That’s done the trick.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.