Running upserts with pydrgaph using pure dictionary objects

Experience Report for Feature Request

Using pydgraph is an experience with mixed feelings. Most stuff runs pretty well, but there are still issues, that make using it very painful.

I want to run an upsert, and currently (to my knowledge) the only way to achieve this with the python client is the following:

import pydgraph
query = '{ q(func: eq(email, "user@company1.io")) { v as uid } }'
nquad = ''' uid(v) <name> "first last" .
               uid(v) <email> "user@company1.io" . '''


client_stub = pydgraph.DgraphClientStub('localhost:9080')
client = pydgraph.DgraphClient(client_stub)
txn = client.txn()
mutation = txn.create_mutation(set_nquads=nquad)
request = txn.create_request(query=query, mutations=[mutation], commit_now=True)
txn.do_request(request)
txn.discard()

This is an awful lot of code and requires using DQL’s query syntax as well as RDF syntax.

Running a simple set-mutation however, is currently very convenient:

import pydgraph
mutation = {'name': 'first last', 'email': 'user@company1.io'}

client_stub = pydgraph.DgraphClientStub('localhost:9080')
client = pydgraph.DgraphClient(client_stub)
txn = client.txn()
txn.mutate(set_obj=mutation)
txn.commit()
txn.discard()

Above code is intuitive and convenient, because we can use native python dictionaries and a straight-forward structure.

On the other hand, running complex upsert operations using curl + json works. This implies, that in terms of convenience the python requests library is currently superior:

import requests

query = '{ q(func: eq(email, "user@company1.io")) { v as uid } }'
mutations = [ {"set": [
                           {"uid": "uid(v)", "name": "first last", "email": "user@company1.io"}


upsert = {'query': query, "mutations": mutations}
endpoint = "http://localhost:8080/mutate?commitNow=true"
r = requests.post(endpoint, json=upsert)

Above code allows for a clean python dictionary and reduces the amount of “foreign” syntax. Is there any plan to implement json-like upserts with pydgraph?

And what would speak against using curl-style requests for running upserts?

Thanks for the feedback @mrwunderbar666. I can see how an additional helper function to the pydgraph client can help with having simpler API for upserts.

On that note, it looks like all the pieces are already in place for you to have your own Python function in your app that can solve what you’re looking to do. You can create a function that takes the input of your preferred upsert dictionary {'query': query, 'mutations': mutations} and then call the underlying txn.create_request calls etc. to do the upserts.