Package: pydgraph
pydgraphThis is the official Dgraph database client implementation for Python (Python >= v3.7), usinggRPC.This client follows theDgraph Go clientclosely.Before using this client, we highly recommend that you read the
the product documentation atdgraph.io/docs.Table of contentspydgraphTable of contentsInstallSupported VersionsQuickstartUsing a clientCreating a ClientLogin into a NamespaceConnecting To Dgraph CloudAltering the DatabaseCreating a TransactionRunning a MutationRunning a QueryQuery with RDF responseRunning an Upsert: Query + MutationRunning a Conditional UpsertCommitting a TransactionCleaning Up ResourcesSetting Metadata HeadersSetting a timeoutAsync methodsExamplesDevelopmentSetting up environmentBuild from sourceRunning testsInstallInstall using pip:pipinstallpydgraphSupported VersionsDepending on the version of Dgraph that you are connecting to, you will have to
use a different version of this client.Dgraph versionpydgraph version20.3.X20.3.020.7.X20.7.020.11.X20.7.021.03.X21.3.022.0.X21.3.023.0.X23.0.0QuickstartBuild and run thesimple projectin theexamplesfolder, which
contains an end-to-end example of using the Dgraph python client. For additional details, follow the
instructions in the project'sREADME.Using a clientCreating a ClientYou can initialize aDgraphClientobject by passing it a list ofDgraphClientStubclients as variadic arguments. Connecting to multiple Dgraph
servers in the same cluster allows for better distribution of workload.The following code snippet shows just one connection.importpydgraphclient_stub=pydgraph.DgraphClientStub('localhost:9080')client=pydgraph.DgraphClient(client_stub)Login into a NamespaceIf your server has Access Control Lists enabled (Dgraph v1.1 or above), the client must be
logged in for accessing data. Useloginendpoint:Calling login will obtain and remember the access and refresh JWT tokens. All subsequent operations
via the logged in client will send along the stored access token.client.login("groot","password")If your server additionally has namespaces (Dgraph v21.03 or above), use thelogin_into_namespaceAPI.client.login_into_namespace("groot","password","123")Connecting To Dgraph CloudIf you want to connect to Dgraph running onDgraph Cloudinstance, then
get the gRPC endpoint of your cluster that you can find in theSettings sectionof Dgraph Cloud console and obtain a Client
or Admin API key (created in theAPI key tabof the Setting section). Create theclient_stubusing the gRPC endpoint and the API key:client_stub=pydgraph.DgraphClientStub.from_cloud("https://morning-glade.grpc.us-east-1.aws.cloud.dgraph.io:443","<api-key>")client=pydgraph.DgraphClient(client_stub)TheDgraphClientStub.from_slash_endpoint()method has been removed v23.0.
Please useDgraphClientStub.from_cloud()instead.Altering the DatabaseTo set the schema, create anOperationobject, set the schema and pass it toDgraphClient#alter(Operation)method.schema='name: string @index(exact) .'op=pydgraph.Operation(schema=schema)client.alter(op)Operationcontains other fields as well, includingDropAttrandDropAll.DropAllis
useful if you wish to discard all the data, and start from a clean slate, without bringing
the instance down.DropAttris used to drop all the data related to a predicate.# Drop all data including schema from the Dgraph instance. This is a useful# for small examples such as this since it puts Dgraph into a clean state.op=pydgraph.Operation(drop_all=True)client.alter(op)Indexes can be computed in the background.
You can set therun_in_backgroundfield ofpydgraph.OperationtoTruebefore passing it to theAlterfunction. You can find more detailshere.schema='name: string @index(exact) .'op=pydgraph.Operation(schema=schema,run_in_background=True)client.alter(op)Creating a TransactionTo create a transaction, call theDgraphClient#txn()method, which returns a
newTxnobject. This operation incurs no network overhead.It is good practice to callTxn#discard()in afinallyblock after running
the transaction. CallingTxn#discard()afterTxn#commit()is a no-op
and you can callTxn#discard()multiple times with no additional side-effects.txn=client.txn()try:# Do something here# ...finally:txn.discard()# ...To create a read-only transaction, callDgraphClient#txn(read_only=True).
Read-only transactions are ideal for transactions which only involve queries.
Mutations and commits are not allowed.txn=client.txn(read_only=True)try:# Do some queries here# ...finally:txn.discard()# ...To create a read-only transaction that executes best-effort queries, callDgraphClient#txn(read_only=True, best_effort=True). Best-effort queries are
faster than normal queries because they bypass the normal consensus protocol.
For this same reason, best-effort queries cannot guarantee to return the latest
data. Best-effort queries are only supported by read-only transactions.Running a MutationTxn#mutate(mu=Mutation)runs a mutation. It takes in aMutationobject,
which provides two main ways to set data: JSON and RDF N-Quad. You can choose
whichever way is convenient.Txn#mutate()provides convenience keyword argumentsset_objanddel_objfor setting JSON values andset_nquadsanddel_nquadsfor setting N-Quad
values. See examples below for usage.We define a person object to represent a person and use it in a transaction.# Create data.p={'name':'Alice'}# Run mutation.txn.mutate(set_obj=p)# If you want to use a mutation object, use this instead:# mu = pydgraph.Mutation(set_json=json.dumps(p).encode('utf8'))# txn.mutate(mu)# If you want to use N-Quads, use this instead:# txn.mutate(set_nquads='_:alice <name> "Alice" .')# Delete dataquery="""query all($a: string){all(func: eq(name, $a)){uid}}"""variables={'$a':'Bob'}res=txn.query(query,variables=variables)ppl=json.loads(res.json)# For a mutation to delete a node, use this:txn.mutate(del_obj=person)For a complete example with multiple fields and relationships, look at thesimple projectin theexamplesfolder.Sometimes, you only want to commit a mutation, without querying anything further.
In such cases, you can set the keyword argumentcommit_now=Trueto indicate
that the mutation must be immediately committed.A mutation can be executed usingtxn.do_requestas well.mutation=txn.create_mutation(set_nquads='_:alice <name> "Alice" .')request=txn.create_request(mutations=[mutation],commit_now=True)txn.do_request(request)Running a QueryYou can run a query by callingTxn#query(string). You will need to pass in aDQLquery string. If you want to pass
an additional dictionary of any variables that you might want to set in the query,
callTxn#query(string, variables=d)with the variables dictionaryd.The query response contains thejsonfield, which returns the JSON response.
Let’s run a query with a variable$a, deserialize the result from JSON and
print it out:# Run query.query="""query all($a: string) {all(func: eq(name, $a)){name}}"""variables={'$a':'Alice'}res=txn.query(query,variables=variables)# If not doing a mutation in the same transaction, simply use:# res = client.txn(read_only=True).query(query, variables=variables)ppl=json.loads(res.json)# Print results.print('Number of people named "Alice":{}'.format(len(ppl['all'])))forpersoninppl['all']:print(person)This should print:Number of people named "Alice": 1AliceYou can also usetxn.do_requestfunction to run the query.request=txn.create_request(query=query)txn.do_request(request)Query with RDF responseYou can get query result as a RDF response by callingTxn#query(string)withresp_formatset
toRDF. The response would contain ardffield, which has the RDF encoded result.Note:If you are querying only foruidvalues, use a JSON format response.res=txn.query(query,variables=variables,resp_format="RDF")print(res.rdf)Running an Upsert: Query + MutationThetxn.do_requestfunction allows you to use upsert blocks. An upsert block
contains one query block and one or more mutation blocks, so it lets you perform
queries and mutations in a single request. Variables defined in the query block
can be used in the mutation blocks using theuidandvalfunctions
implemented by DQL.To learn more about upsert blocks, see theUpsert Block documentation.query="""{u as var(func: eq(name, "Alice"))}"""nquad="""uid(u) <name> "Alice" .uid(u) <age> "25" ."""mutation=txn.create_mutation(set_nquads=nquad)request=txn.create_request(query=query,mutations=[mutation],commit_now=True)txn.do_request(request)Running a Conditional UpsertThe upsert block also allows specifying a conditional mutation block using an@ifdirective.
The mutation is executed only when the specified condition is true. If the condition is false,
the mutation is silently ignored.See more about Conditional Upsertshere.query="""{user as var(func: eq(email, "wrong_email@dgraph.io"))}"""cond="@if(eq(len(user), 1))"nquads="""uid(user) <email> "correct_email@dgraph.io" ."""mutation=txn.create_mutation(cond=cond,set_nquads=nquads)request=txn.create_request(mutations=[mutation],query=query,commit_now=True)txn.do_request(request)Committing a TransactionA transaction can be committed using theTxn#commit()method. If your transaction
consist solely ofTxn#queryorTxn#queryWithVarscalls, and no calls toTxn#mutate, then callingTxn#commit()is not necessary.An error is raised if another transaction(s) modify the same data concurrently that was
modified in the current transaction. It is up to the user to retry transactions
when they fail.txn=client.txn()try:# ...# Perform any number of queries and mutations# ...# and finally...txn.commit()exceptpydgraph.AbortedError:# Retry or handle exception.finally:# Clean up. Calling this after txn.commit() is a no-op# and hence safe.txn.discard()Cleaning Up ResourcesTo clean up resources, you have to callDgraphClientStub#close()individually for
all the instances ofDgraphClientStub.SERVER_ADDR1="localhost:9080"SERVER_ADDR2="localhost:9080"# Create instances of DgraphClientStub.stub1=pydgraph.DgraphClientStub(SERVER_ADDR1)stub2=pydgraph.DgraphClientStub(SERVER_ADDR2)# Create an instance of DgraphClient.client=pydgraph.DgraphClient(stub1,stub2)# Use client...# Clean up resources by closing all client stubs.stub1.close()stub2.close()Setting Metadata HeadersMetadata headers such as authentication tokens can be set through the metadata of gRPC methods.
Below is an example of how to set a header named "auth-token".# The following piece of code shows how one can set metadata with# auth-token, to allow Alter operation, if the server requires it.# metadata is a list of arbitrary key-value pairs.metadata=[("auth-token","the-auth-token-value")]dg.alter(op,metadata=metadata)Setting a timeoutA timeout value representing the number of seconds can be passed to thelogin,alter,query, andmutatemethods using thetimeoutkeyword argument.For example, the following alters the schema with a timeout of ten seconds:dg.alter(op, timeout=10)Async methodsThealtermethod in the client has an asynchronous version calledasync_alter. The async methods return a future. You can directly call theresultmethod on the future. However. The DgraphClient class provides a static
methodhandle_alter_futureto handle any possible exception.alter_future=self.client.async_alter(pydgraph.Operation(schema="name: string @index(term) ."))response=pydgraph.DgraphClient.handle_alter_future(alter_future)Thequeryandmutatemethods int theTxnclass also have async versions
calledasync_queryandasync_mutationrespectively. These functions work
just likeasync_alter.You can use thehandle_query_futureandhandle_mutate_futurestatic methods
in theTxnclass to retrieve the result. A short example is given below:txn=client.txn()query="query body here"future=txn.async_query()response=pydgraph.Txn.handle_query_future(future)Keep in mind that due to the nature of async calls, the async functions cannot
retry the request if the login is invalid. You will have to check for this error
and retry the login (with the functionretry_loginin both theTxnandClientclasses). A short example is given below:client=DgraphClient(client_stubs)# client_stubs is a list of gRPC stubs.alter_future=client.async_alter()try:response=alter_future.result()exceptExceptionase:# You can use this function in the util package to check for JWT# expired errors.ifpydgraph.util.is_jwt_expired(e):# retry your request here.Examplessimple: Quickstart example of using pydgraph.tls: Quickstart example that uses TLS.parse_datetime: Demonstration of converting Dgraph's DateTime strings to native python datetime.DevelopmentSetting up environmentThere are many ways to set up your local Python environment. We suggest some sane defaults here.Usepyenvto manage your Python installations.Most recent versions of Python should work, but the version of Python officially supported is located in.python-versionCreate a Python virtual environment usingpython -m venv .venvActivate virtual environment viasource .venv/bin/activateBuild from sourceTo build and install pydgraph locally, runpipinstall-e".[dev]"If you have made changes to thepydgraph/proto/api.protofile, you need need
to regenerate the source files generated by Protocol Buffer tools. To do that,
install thegrpcio-toolslibrary and then run the following
command:pythonscripts/protogen.pyRunning testsTo run the tests in your local machine, run:bashscripts/local-test.shThis script assumes dgraph is located on your path. Dgraph release binaries can
be foundhere.
The test script also requires thatdockeranddocker composeare installed on
your machine.The script will take care of bringing up a Dgraph cluster and bringing it down
after the tests are executed. The script connects to randomly selected ports for
HTTP and gRPC requests to prevent interference with clusters running on the
default port. Docker and docker-compose need to be installed before running the
script. Refer to the officialDocker documentationfor instructions on how to install those packages.