{"id":40244116,"url":"https://github.com/dgraph-io/pydgraph","last_synced_at":"2026-01-20T00:01:27.625Z","repository":{"id":9565723,"uuid":"62349251","full_name":"dgraph-io/pydgraph","owner":"dgraph-io","description":"Official Dgraph Python client","archived":false,"fork":false,"pushed_at":"2026-01-15T22:44:59.000Z","size":1655,"stargazers_count":289,"open_issues_count":2,"forks_count":91,"subscribers_count":31,"default_branch":"main","last_synced_at":"2026-01-16T00:05:38.241Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dgraph-io.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2016-06-30T23:52:36.000Z","updated_at":"2026-01-15T20:38:08.000Z","dependencies_parsed_at":"2023-11-06T13:46:08.875Z","dependency_job_id":"d871757d-5256-46eb-8b65-5c20ed150cf4","html_url":"https://github.com/dgraph-io/pydgraph","commit_stats":{"total_commits":301,"total_committers":45,"mean_commits":6.688888888888889,"dds":0.7940199335548173,"last_synced_commit":"5537373d6fb5ad827952bc9eb7d364fd621742a5"},"previous_names":["hypermodeinc/pydgraph","dgraph-io/pydgraph"],"tags_count":27,"template":false,"template_full_name":null,"purl":"pkg:github/dgraph-io/pydgraph","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dgraph-io%2Fpydgraph","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dgraph-io%2Fpydgraph/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dgraph-io%2Fpydgraph/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dgraph-io%2Fpydgraph/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dgraph-io","download_url":"https://codeload.github.com/dgraph-io/pydgraph/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dgraph-io%2Fpydgraph/sbom","scorecard":{"id":1240543,"data":{"date":"2025-12-15","repo":{"name":"github.com/dgraph-io/pydgraph","commit":"3f1ed51adbe2986a11bfa70e5b4da51edbdd7794"},"scorecard":{"version":"v5.4.1-0.20251211185148-6c8b5dbbedcf","commit":"6c8b5dbbedcf26e5511695b853fecfe7cbf2235d"},"score":4.4,"checks":[{"name":"Maintained","score":0,"reason":"1 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0","details":null,"documentation":{"short":"Determines if the project is \"actively maintained\".","url":"https://github.com/ossf/scorecard/blob/6c8b5dbbedcf26e5511695b853fecfe7cbf2235d/docs/checks.md#maintained"}},{"name":"Code-Review","score":4,"reason":"Found 6/15 approved changesets -- score normalized to 4","details":null,"documentation":{"short":"Determines if the project requires human code review before pull requests (aka merge requests) are merged.","url":"https://github.com/ossf/scorecard/blob/6c8b5dbbedcf26e5511695b853fecfe7cbf2235d/docs/checks.md#code-review"}},{"name":"Packaging","score":-1,"reason":"packaging workflow not detected","details":["Warn: no GitHub/GitLab publishing workflow detected."],"documentation":{"short":"Determines if the project is published as a package that others can easily download, install, easily update, and uninstall.","url":"https://github.com/ossf/scorecard/blob/6c8b5dbbedcf26e5511695b853fecfe7cbf2235d/docs/checks.md#packaging"}},{"name":"Dangerous-Workflow","score":10,"reason":"no dangerous workflow patterns detected","details":null,"documentation":{"short":"Determines if the project's GitHub Action workflows avoid dangerous patterns.","url":"https://github.com/ossf/scorecard/blob/6c8b5dbbedcf26e5511695b853fecfe7cbf2235d/docs/checks.md#dangerous-workflow"}},{"name":"Binary-Artifacts","score":10,"reason":"no binaries found in the repo","details":null,"documentation":{"short":"Determines if the project has generated executable (binary) artifacts in the source repository.","url":"https://github.com/ossf/scorecard/blob/6c8b5dbbedcf26e5511695b853fecfe7cbf2235d/docs/checks.md#binary-artifacts"}},{"name":"Token-Permissions","score":0,"reason":"detected GitHub workflow tokens with excessive permissions","details":["Info: topLevel 'contents' permission set to 'read': .github/workflows/cd-pydgraph.yml:12","Info: topLevel 'contents' permission set to 'read': .github/workflows/ci-pydgraph-tests.yml:19","Info: topLevel 'contents' permission set to 'read': .github/workflows/trunk.yml:7","Warn: topLevel 'actions' permission set to 'write': .github/workflows/trunk.yml:8","Warn: topLevel 'checks' permission set to 'write': .github/workflows/trunk.yml:9","Info: no jobLevel write permissions found"],"documentation":{"short":"Determines if the project's workflows follow the principle of least privilege.","url":"https://github.com/ossf/scorecard/blob/6c8b5dbbedcf26e5511695b853fecfe7cbf2235d/docs/checks.md#token-permissions"}},{"name":"CII-Best-Practices","score":0,"reason":"no effort to earn an OpenSSF best practices badge detected","details":null,"documentation":{"short":"Determines if the project has an OpenSSF (formerly CII) Best Practices Badge.","url":"https://github.com/ossf/scorecard/blob/6c8b5dbbedcf26e5511695b853fecfe7cbf2235d/docs/checks.md#cii-best-practices"}},{"name":"Pinned-Dependencies","score":0,"reason":"dependency not pinned by hash detected -- score normalized to 0","details":["Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/cd-pydgraph.yml:18: update your workflow using https://app.stepsecurity.io/secureworkflow/dgraph-io/pydgraph/cd-pydgraph.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/cd-pydgraph.yml:22: update your workflow using https://app.stepsecurity.io/secureworkflow/dgraph-io/pydgraph/cd-pydgraph.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci-pydgraph-tests.yml:29: update your workflow using https://app.stepsecurity.io/secureworkflow/dgraph-io/pydgraph/ci-pydgraph-tests.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci-pydgraph-tests.yml:35: update your workflow using https://app.stepsecurity.io/secureworkflow/dgraph-io/pydgraph/ci-pydgraph-tests.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci-pydgraph-tests.yml:51: update your workflow using https://app.stepsecurity.io/secureworkflow/dgraph-io/pydgraph/ci-pydgraph-tests.yml/main?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci-pydgraph-tests.yml:57: update your workflow using https://app.stepsecurity.io/secureworkflow/dgraph-io/pydgraph/ci-pydgraph-tests.yml/main?enable=pin","Warn: third-party GitHubAction not pinned by hash: .github/workflows/trunk.yml:14: update your workflow using https://app.stepsecurity.io/secureworkflow/dgraph-io/pydgraph/trunk.yml/main?enable=pin","Warn: pipCommand not pinned by hash: .github/workflows/cd-pydgraph.yml:27","Warn: pipCommand not pinned by hash: .github/workflows/cd-pydgraph.yml:28","Warn: pipCommand not pinned by hash: .github/workflows/cd-pydgraph.yml:30","Warn: pipCommand not pinned by hash: .github/workflows/ci-pydgraph-tests.yml:41","Warn: pipCommand not pinned by hash: .github/workflows/ci-pydgraph-tests.yml:42","Info:   0 out of   6 GitHub-owned GitHubAction dependencies pinned","Info:   0 out of   1 third-party GitHubAction dependencies pinned","Info:   0 out of   5 pipCommand dependencies pinned"],"documentation":{"short":"Determines if the project has declared and pinned the dependencies of its build process.","url":"https://github.com/ossf/scorecard/blob/6c8b5dbbedcf26e5511695b853fecfe7cbf2235d/docs/checks.md#pinned-dependencies"}},{"name":"Vulnerabilities","score":10,"reason":"0 existing vulnerabilities detected","details":null,"documentation":{"short":"Determines if the project has open, known unfixed vulnerabilities.","url":"https://github.com/ossf/scorecard/blob/6c8b5dbbedcf26e5511695b853fecfe7cbf2235d/docs/checks.md#vulnerabilities"}},{"name":"License","score":10,"reason":"license file detected","details":["Info: project has a license file: LICENSE:0","Info: FSF or OSI recognized license: Apache License 2.0: LICENSE:0"],"documentation":{"short":"Determines if the project has defined a license.","url":"https://github.com/ossf/scorecard/blob/6c8b5dbbedcf26e5511695b853fecfe7cbf2235d/docs/checks.md#license"}},{"name":"Fuzzing","score":0,"reason":"project is not fuzzed","details":["Warn: no fuzzer integrations found"],"documentation":{"short":"Determines if the project uses fuzzing.","url":"https://github.com/ossf/scorecard/blob/6c8b5dbbedcf26e5511695b853fecfe7cbf2235d/docs/checks.md#fuzzing"}},{"name":"Signed-Releases","score":-1,"reason":"no releases found","details":null,"documentation":{"short":"Determines if the project cryptographically signs release artifacts.","url":"https://github.com/ossf/scorecard/blob/6c8b5dbbedcf26e5511695b853fecfe7cbf2235d/docs/checks.md#signed-releases"}},{"name":"Security-Policy","score":0,"reason":"security policy file not detected","details":["Warn: no security policy file detected","Warn: no security file to analyze","Warn: no security file to analyze","Warn: no security file to analyze"],"documentation":{"short":"Determines if the project has published a security policy.","url":"https://github.com/ossf/scorecard/blob/6c8b5dbbedcf26e5511695b853fecfe7cbf2235d/docs/checks.md#security-policy"}},{"name":"Branch-Protection","score":0,"reason":"branch protection not enabled on development/release branches","details":["Warn: 'allow deletion' enabled on branch 'main'","Warn: 'force pushes' enabled on branch 'main'","Info: 'branch protection settings apply to administrators' is required to merge on branch 'main'","Warn: could not determine whether codeowners review is allowed","Warn: 'up-to-date branches' is disabled on branch 'main'","Info: status check found to merge onto on branch 'main'","Warn: PRs are not required to make changes on branch 'main'; or we don't have data to detect it.If you think it might be the latter, make sure to run Scorecard with a PAT or use Repo Rules (that are always public) instead of Branch Protection settings"],"documentation":{"short":"Determines if the default and release branches are protected with GitHub's branch protection settings.","url":"https://github.com/ossf/scorecard/blob/6c8b5dbbedcf26e5511695b853fecfe7cbf2235d/docs/checks.md#branch-protection"}},{"name":"SAST","score":10,"reason":"SAST tool is run on all commits","details":["Info: all commits (23) are checked with a SAST tool"],"documentation":{"short":"Determines if the project uses static code analysis.","url":"https://github.com/ossf/scorecard/blob/6c8b5dbbedcf26e5511695b853fecfe7cbf2235d/docs/checks.md#sast"}}]},"last_synced_at":"2025-12-20T07:30:38.235Z","repository_id":9565723,"created_at":"2025-12-20T07:30:38.235Z","updated_at":"2025-12-20T07:30:38.235Z"},"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28590676,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-19T23:59:00.777Z","status":"ssl_error","status_checked_at":"2026-01-19T23:58:54.030Z","response_time":67,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-01-20T00:01:18.653Z","updated_at":"2026-01-20T00:01:27.599Z","avatar_url":"https://github.com/dgraph-io.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# pydgraph\n\nThis is the official Dgraph database client implementation for Python (Python \u003e= v3.9), using\n[gRPC](https://grpc.io).\n\nBefore using this client, we highly recommend that you read the the product documentation at\n[https://docs.dgraph.io/](https://docs.dgraph.io/).\n\n## Table of contents\n\n- [pydgraph](#pydgraph)\n  - [Table of contents](#table-of-contents)\n  - [Install](#install)\n  - [Supported Versions](#supported-versions)\n  - [Quickstart](#quickstart)\n  - [Using a client](#using-a-client)\n    - [Creating a Client](#creating-a-client)\n    - [Login into a Namespace](#login-into-a-namespace)\n    - [Altering the Database](#altering-the-database)\n    - [Creating a Transaction](#creating-a-transaction)\n    - [Running a Mutation](#running-a-mutation)\n    - [Running a Query](#running-a-query)\n    - [Query with RDF response](#query-with-rdf-response)\n    - [Running an Upsert: Query + Mutation](#running-an-upsert-query--mutation)\n    - [Running a Conditional Upsert](#running-a-conditional-upsert)\n    - [Committing a Transaction](#committing-a-transaction)\n    - [Cleaning Up Resources](#cleaning-up-resources)\n    - [Setting Metadata Headers](#setting-metadata-headers)\n    - [Setting a timeout](#setting-a-timeout)\n    - [Async methods](#async-methods)\n    - [Native Async/Await Client](#native-asyncawait-client)\n  - [Handling Transaction Conflicts](#handling-transaction-conflicts)\n    - [Using run_transaction (Recommended)](#using-run_transaction-recommended)\n    - [Using the Retry Decorator](#using-the-retry-decorator)\n    - [Using the Retry Generator](#using-the-retry-generator)\n    - [Retry Parameters](#retry-parameters)\n    - [Which Errors Are Retried?](#which-errors-are-retried)\n    - [Example: High-Contention Counter](#example-high-contention-counter)\n  - [Examples](#examples)\n  - [Contributing](#contributing)\n\n## Install\n\nInstall using pip:\n\n```sh\npip install pydgraph\n```\n\n### Protobuf Version Compatibility\n\npydgraph supports protobuf versions 4.23.0 through 6.x. The specific version installed depends on\nyour environment:\n\n- **Modern environments**: protobuf 6.x is recommended and will be installed by default on Python\n  3.13+\n- **Legacy environments**: If you need to use protobuf 4.x or 5.x (e.g., for compatibility with\n  other packages), you can pin the version:\n\n```sh\n# For protobuf 4.x compatibility\npip install pydgraph \"protobuf\u003e=4.23.0,\u003c5.0.0\"\n\n# For protobuf 5.x compatibility\npip install pydgraph \"protobuf\u003e=5.0.0,\u003c6.0.0\"\n```\n\nAll supported protobuf versions are tested in CI against both Dgraph latest and Dgraph HEAD.\n\n## Supported Versions\n\nDepending on the version of Dgraph that you are connecting to, you should use a different version of\nthis client. Using an incompatible version may lead to unexpected behavior or errors.\n\n| Dgraph version | pydgraph version |\n| :------------: | :--------------: |\n|    21.03.x     |    _21.03.x_     |\n|    23.0.x+     |     _23.0.x_     |\n|    24.0.x+     |     _24.0.x_     |\n|    25.0.x+     |     _25.0.x_     |\n\n## Quickstart\n\nBuild and run the [simple project][simple] in the `examples` folder, which contains an end-to-end\nexample of using the Dgraph python client. For additional details, follow the instructions in the\nproject's [README](./examples/simple/README.md).\n\n[simple]: ./examples/simple\n\n## Using a client\n\n### Creating a Client\n\nYou can initialize a `DgraphClient` object by passing it a list of `DgraphClientStub` clients as\nvariadic arguments. Connecting to multiple Dgraph servers in the same cluster allows for better\ndistribution of workload.\n\nThe following code snippet shows just one connection.\n\n```python\nimport pydgraph\n\nclient_stub = pydgraph.DgraphClientStub('localhost:9080')\nclient = pydgraph.DgraphClient(client_stub)\n```\n\n### Using Dgraph Connection Strings\n\nThe pydgraph package supports connecting to a Dgraph cluster using connection strings. Dgraph\nconnections strings take the form `dgraph://{username:password@}host:port?args`.\n\n`username` and `password` are optional. If username is provided, a password must also be present. If\nsupplied, these credentials are used to log into a Dgraph cluster through the ACL mechanism.\n\nValid connection string args:\n\n| Arg         | Value                           | Description                                                                                                                                                   |\n| ----------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| bearertoken | \\\u003ctoken\\\u003e                       | an access token                                                                                                                                               |\n| sslmode     | disable \\| require \\| verify-ca | TLS option, the default is `disable`. If `verify-ca` is set, the TLS certificate configured in the Dgraph cluster must be from a valid certificate authority. |\n| namespace   | \\\u003cnamespace\\\u003e                   | a previously created integer-based namespace, username and password must be supplied                                                                          |\n\nNote the `sslmode=require` pair is not supported and will throw an Exception if used. Python grpc\ndoes not support traffic over TLS that does not fully verify the certificate and domain. Developers\nshould use the existing stub/client initialization steps for self-signed certs as demonstrated in\n[examples/tls/tls_example.py](./examples/tls/tls_example.py).\n\nSome example connection strings:\n\n| Value                                                                                       | Explanation                                                                         |\n| ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |\n| dgraph://localhost:9080                                                                     | Connect to localhost, no ACL, no TLS                                                |\n| dgraph://sally:supersecret@dg.example.com:443?sslmode=verify-ca                             | Connect to remote server, use ACL and require TLS and a valid certificate from a CA |\n| dgraph://foo-bar.grpc.dgraph-io.com:443?sslmode=verify-ca\u0026bearertoken=\\\u003csome access token\\\u003e | Connect to a Dgraph cluster protected by a secure gateway                           |\n| dgraph://sally:supersecret@dg.example.com:443?namespace=2                                   | Connect to a ACL enabled Dgraph cluster in namespace 2                              |\n\nUsing the `Open` function with a connection string:\n\n```python\n# open a connection to an ACL-enabled, non-TLS cluster and login as groot\nclient = pydgraph.open(\"dgraph://groot:password@localhost:8090\")\n\n# Use the client\n...\n\nclient.close()\n```\n\n### Login into a Namespace\n\nIf your server has Access Control Lists enabled (Dgraph v1.1 or above), the client must be logged in\nfor accessing data. If you didn't use the `open` function with credentials and a namespace, use the\n`login` endpoint.\n\nCalling `login` will obtain and remember the access and refresh JWT tokens. All subsequent\noperations via the logged in client will send along the stored access token.\n\n```python\nclient.login(\"groot\", \"password\")\n```\n\nIf your server additionally has namespaces (Dgraph v21.03 or above), use the `login_into_namespace`\nAPI.\n\n```python\nclient.login_into_namespace(\"groot\", \"password\", \"123\")\n```\n\n### Altering the Database\n\n#### Set the Dgraph types schema\n\nTo set the Dgraph types schema (aka DQL schema), create an `Operation` object, set the schema and\npass it to `DgraphClient#alter(Operation)` method.\n\n```python\nschema = 'name: string @index(exact) .'\nop = pydgraph.Operation(schema=schema)\nclient.alter(op)\n```\n\nIndexes can be computed in the background. You can set the `run_in_background` field of\n`pydgraph.Operation` to `True` before passing it to the `Alter` function. You can find more details\nin the\n[Dgraph documentation on background indexes](https://docs.dgraph.io/admin/admin-tasks/update-dgraph-types#indexes-in-background).\n\n**Note** To deploy the GraphQL schema in python you have to use GraphQL client such as\n[python-graphql-client](https://github.com/prodigyeducation/python-graphql-client) to invoke the\nGraphQL admin mutation [updateGQLSchema](https://docs.dgraph.io/graphql/admin/#modifying-a-schema)\n\n```python\nschema = 'name: string @index(exact) .'\nop = pydgraph.Operation(schema=schema, run_in_background=True)\nclient.alter(op)\n```\n\n#### Drop data\n\nTo drop all data and schema:\n\n```python\n# Drop all data including schema from the Dgraph instance. This is a useful\n# for small examples such as this since it puts Dgraph into a clean state.\nop = pydgraph.Operation(drop_all=True)\nclient.alter(op)\n```\n\n**Note** If the Dgraph cluster contains a GraphQL Schema, it will also be deleted by this operation.\n\nTo drop all data and preserve the DQL schema:\n\n```python\n# Drop all data from the Dgraph instance. Keep the DQL Schema.\nop = pydgraph.Operation(drop_op=\"DATA\")\nclient.alter(op)\n```\n\nTo drop a predicate:\n\n```python\n# Drop the data associated to a predicate and the predicate from the schema.\nop = pydgraph.Operation(drop_op=\"ATTR\", drop_value=\"\u003cpredicate_name\u003e\")\nclient.alter(op)\n```\n\nthe same result is obtained using\n\n```python\n# Drop the data associated to a predicate and the predicate from the schema.\nop = pydgraph.Operation(drop_attr=\"\u003cpredicate_name\u003e\")\nclient.alter(op)\n```\n\nTo drop a type definition from DQL Schema:\n\n```python\n# Drop a type from the schema.\nop = pydgraph.Operation(drop_op=\"TYPE\", drop_value=\"\u003cpredicate_name\u003e\")\nclient.alter(op)\n```\n\n**Note** `drop_op=\"TYPE\"` just removes a type definition from the DQL schema. No data is removed\nfrom the cluster. The operation does not drop the predicates associated with the type.\n\n### Creating a Transaction\n\nTo create a transaction, call the `DgraphClient#txn()` method, which returns a new `Txn` object.\nThis operation incurs no network overhead.\n\nIt is good practice to call `Txn#discard()` in a `finally` block after running the transaction.\nCalling `Txn#discard()` after `Txn#commit()` is a no-op and you can call `Txn#discard()` multiple\ntimes with no additional side-effects.\n\n```python\ntxn = client.txn()\ntry:\n  # Do something here\n  # ...\nfinally:\n  txn.discard()\n  # ...\n```\n\nTo create a read-only transaction, call `DgraphClient#txn(read_only=True)`. Read-only transactions\nare ideal for transactions which only involve queries. Mutations and commits are not allowed.\n\n```python\ntxn = client.txn(read_only=True)\ntry:\n  # Do some queries here\n  # ...\nfinally:\n  txn.discard()\n  # ...\n```\n\nTo create a read-only transaction that executes best-effort queries, call\n`DgraphClient#txn(read_only=True, best_effort=True)`. Best-effort queries are faster than normal\nqueries because they bypass the normal consensus protocol. For this same reason, best-effort queries\ncannot guarantee to return the latest data. Best-effort queries are only supported by read-only\ntransactions.\n\n### Running a Mutation\n\n`Txn#mutate(mu=Mutation)` runs a mutation. It takes in a `Mutation` object, which provides two main\nways to set data: JSON and RDF N-Quad. You can choose whichever way is convenient.\n\n`Txn#mutate()` provides convenience keyword arguments `set_obj` and `del_obj` for setting JSON\nvalues and `set_nquads` and `del_nquads` for setting N-Quad values. See examples below for usage.\n\nWe define a person object to represent a person and use it in a transaction.\n\n```python\n# Create data.\np = { 'name': 'Alice' }\n\n# Run mutation.\ntxn.mutate(set_obj=p)\n\n# If you want to use a mutation object, use this instead:\n# mu = pydgraph.Mutation(set_json=json.dumps(p).encode('utf8'))\n# txn.mutate(mu)\n\n# If you want to use N-Quads, use this instead:\n# txn.mutate(set_nquads='_:alice \u003cname\u003e \"Alice\" .')\n```\n\n```python\n# Delete data\n\nquery = \"\"\"query all($a: string)\n {\n   all(func: eq(name, $a))\n    {\n      uid\n    }\n  }\"\"\"\nvariables = {'$a': 'Bob'}\n\nres = txn.query(query, variables=variables)\nppl = json.loads(res.json)\n\n# For a mutation to delete a node, use this:\ntxn.mutate(del_obj=person)\n```\n\nFor a complete example with multiple fields and relationships, look at the [simple project][simple]\nin the `examples` folder.\n\nSometimes, you only want to commit a mutation, without querying anything further. In such cases, you\ncan set the keyword argument `commit_now=True` to indicate that the mutation must be immediately\ncommitted.\n\nA mutation can be executed using `txn.do_request` as well.\n\n```python\nmutation = txn.create_mutation(set_nquads='_:alice \u003cname\u003e \"Alice\" .')\nrequest = txn.create_request(mutations=[mutation], commit_now=True)\ntxn.do_request(request)\n```\n\n### Committing a Transaction\n\nA transaction can be committed using the `Txn#commit()` method. If your transaction consist solely\nof `Txn#query` or `Txn#queryWithVars` calls, and no calls to `Txn#mutate`, then calling\n`Txn#commit()` is not necessary.\n\nAn error is raised if another transaction(s) modify the same data concurrently that was modified in\nthe current transaction. It is up to the user to retry transactions when they fail.\n\n```python\ntxn = client.txn()\ntry:\n  # ...\n  # Perform any number of queries and mutations\n  # ...\n  # and finally...\n  txn.commit()\nexcept pydgraph.AbortedError:\n  # Retry or handle exception.\nfinally:\n  # Clean up. Calling this after txn.commit() is a no-op\n  # and hence safe.\n  txn.discard()\n```\n\n#### Using Transaction with Context Manager\n\nThe Python context manager will automatically perform the \"`commit`\" action after all queries and\nmutations have been done, and perform \"`discard`\" action to clean the transaction. When something\ngoes wrong in the scope of context manager, \"`commit`\" will not be called,and the \"`discard`\" action\nwill be called to drop any potential changes.\n\n```python\nwith client.begin(read_only=False, best_effort=False) as txn:\n  # Do some queries or mutations here\n```\n\nor you can directly create a transaction from the `Txn` class.\n\n```python\nwith pydgraph.Txn(client, read_only=False, best_effort=False) as txn:\n  # Do some queries or mutations here\n```\n\n\u003e `client.begin()` can only be used with \"`with-as`\" blocks, while `pydgraph.Txn` class can be\n\u003e directly called to instantiate a transaction object.\n\n### Running a Query\n\nYou can run a query by calling `Txn#query(string)`. You will need to pass in a\n[DQL](https://docs.dgraph.io/dql/) query string. If you want to pass an additional dictionary of any\nvariables that you might want to set in the query, call `Txn#query(string, variables=d)` with the\nvariables dictionary `d`.\n\nThe query response contains the `json` field, which returns the JSON response. Let’s run a query\nwith a variable `$a`, deserialize the result from JSON and print it out:\n\n```python\n# Run query.\nquery = \"\"\"query all($a: string) {\n  all(func: eq(name, $a))\n  {\n    name\n  }\n}\"\"\"\nvariables = {'$a': 'Alice'}\n\nres = txn.query(query, variables=variables)\n\n# If not doing a mutation in the same transaction, simply use:\n# res = client.txn(read_only=True).query(query, variables=variables)\n\nppl = json.loads(res.json)\n\n# Print results.\nprint('Number of people named \"Alice\": {}'.format(len(ppl['all'])))\nfor person in ppl['all']:\n  print(person)\n```\n\nThis should print:\n\n```console\nNumber of people named \"Alice\": 1\nAlice\n```\n\nYou can also use `txn.do_request` function to run the query.\n\n```python\nrequest = txn.create_request(query=query)\ntxn.do_request(request)\n```\n\n### Query with RDF response\n\nYou can get query result as a RDF response by calling `Txn#query(string)` with `resp_format` set to\n`RDF`. The response would contain a `rdf` field, which has the RDF encoded result.\n\n**Note:** If you are querying only for `uid` values, use a JSON format response.\n\n```python\nres = txn.query(query, variables=variables, resp_format=\"RDF\")\nprint(res.rdf)\n```\n\n### Running an Upsert: Query + Mutation\n\nThe `txn.do_request` function allows you to use upsert blocks. An upsert block contains one query\nblock and one or more mutation blocks, so it lets you perform queries and mutations in a single\nrequest. Variables defined in the query block can be used in the mutation blocks using the `uid` and\n`val` functions implemented by DQL.\n\nTo learn more about upsert blocks, see the\n[Upsert Block documentation](https://docs.dgraph.io/dql/dql-mutation#conditional-upsert).\n\n```python\nquery = \"\"\"{\n  u as var(func: eq(name, \"Alice\"))\n}\"\"\"\n\nnquad = \"\"\"\n  uid(u) \u003cname\u003e \"Alice\" .\n  uid(u) \u003cage\u003e \"25\" .\n\"\"\"\n\nmutation = txn.create_mutation(set_nquads=nquad)\nrequest = txn.create_request(query=query, mutations=[mutation], commit_now=True)\ntxn.do_request(request)\n```\n\n### Running a Conditional Upsert\n\nThe upsert block also allows specifying a conditional mutation block using an `@if` directive. The\nmutation is executed only when the specified condition is true. If the condition is false, the\nmutation is silently ignored.\n\nSee more about\n[conditional upserts in the Dgraph documentation](https://docs.dgraph.io/dql/dql-mutation#conditional-upsert).\n\n```python\nquery = \"\"\"\n  {\n    user as var(func: eq(email, \"wrong_email@dgraph.io\"))\n  }\n\"\"\"\n\ncond = \"@if(eq(len(user), 1))\"\nnquads = \"\"\"\n  uid(user) \u003cemail\u003e \"correct_email@dgraph.io\" .\n\"\"\"\n\nmutation = txn.create_mutation(cond=cond, set_nquads=nquads)\nrequest = txn.create_request(mutations=[mutation], query=query, commit_now=True)\ntxn.do_request(request)\n```\n\n### Cleaning Up Resources\n\nTo clean up resources, you have to call `DgraphClientStub#close()` individually for all the\ninstances of `DgraphClientStub`.\n\n```python\nSERVER_ADDR1 = \"localhost:9080\"\nSERVER_ADDR2 = \"localhost:9080\"\n\n# Create instances of DgraphClientStub.\nstub1 = pydgraph.DgraphClientStub(SERVER_ADDR1)\nstub2 = pydgraph.DgraphClientStub(SERVER_ADDR2)\n\n# Create an instance of DgraphClient.\nclient = pydgraph.DgraphClient(stub1, stub2)\n\n# Use client\n...\n\n# Clean up resources by closing all client stubs.\nstub1.close()\nstub2.close()\n```\n\n#### Use context manager to automatically clean resources\n\nUse function call:\n\n```python\nwith pydgraph.client_stub(SERVER_ADDR) as stub1:\n  with pydgraph.client_stub(SERVER_ADDR) as stub2:\n    client = pydgraph.DgraphClient(stub1, stub2)\n```\n\nUse class constructor:\n\n```python\nwith pydgraph.DgraphClientStub(SERVER_ADDR) as stub1:\n  with pydgraph.DgraphClientStub(SERVER_ADDR) as stub2:\n    client = pydgraph.DgraphClient(stub1, stub2)\n```\n\nNote: `client` should be used inside the \"`with-as`\" block. The resources related to `client` will\nbe automatically released outside the block and `client` is not usable any more.\n\n### Setting Metadata Headers\n\nMetadata headers such as authentication tokens can be set through the metadata of gRPC methods.\nBelow is an example of how to set a header named \"auth-token\".\n\n```python\n# The following piece of code shows how one can set metadata with\n# auth-token, to allow Alter operation, if the server requires it.\n# metadata is a list of arbitrary key-value pairs.\nmetadata = [(\"auth-token\", \"the-auth-token-value\")]\ndg.alter(op, metadata=metadata)\n```\n\n### Setting a timeout\n\nA timeout value representing the number of seconds can be passed to the `login`, `alter`, `query`,\nand `mutate` methods using the `timeout` keyword argument.\n\nFor example, the following alters the schema with a timeout of ten seconds:\n`dg.alter(op, timeout=10)`\n\n### Async methods\n\nThe `alter` method in the client has an asynchronous version called `async_alter`. The async methods\nreturn a future. You can directly call the `result` method on the future. However. The DgraphClient\nclass provides a static method `handle_alter_future` to handle any possible exception.\n\n```python\nalter_future = self.client.async_alter(pydgraph.Operation(schema=\"name: string @index(term) .\"))\nresponse = pydgraph.DgraphClient.handle_alter_future(alter_future)\n```\n\nThe `query` and `mutate` methods int the `Txn` class also have async versions called `async_query`\nand `async_mutation` respectively. These functions work just like `async_alter`.\n\nYou can use the `handle_query_future` and `handle_mutate_future` static methods in the `Txn` class\nto retrieve the result. A short example is given below:\n\n```python\ntxn = client.txn()\nquery = \"query body here\"\nfuture = txn.async_query()\nresponse = pydgraph.Txn.handle_query_future(future)\n```\n\nKeep in mind that due to the nature of async calls, the async functions cannot retry the request if\nthe login is invalid. You will have to check for this error and retry the login (with the function\n`retry_login` in both the `Txn` and `Client` classes). A short example is given below:\n\n```python\nclient = DgraphClient(client_stubs) # client_stubs is a list of gRPC stubs.\nalter_future = client.async_alter()\ntry:\n    response = alter_future.result()\nexcept Exception as e:\n  # You can use this function in the util package to check for JWT\n    # expired errors.\n    if pydgraph.util.is_jwt_expired(e):\n        # retry your request here.\n```\n\n### Native Async/Await Client\n\npydgraph provides a native async/await client using Python's `asyncio` library and `grpc.aio`. This\nprovides true asynchronous operations with better concurrency compared to the futures-based approach\nabove.\n\n#### Basic Usage\n\n```python\nimport asyncio\nimport pydgraph\n\nasync def main():\n    # Create async client\n    client_stub = pydgraph.AsyncDgraphClientStub('localhost:9080')\n    client = pydgraph.AsyncDgraphClient(client_stub)\n\n    try:\n        # Login\n        await client.login(\"groot\", \"password\")\n\n        # Alter schema\n        await client.alter(pydgraph.Operation(\n            schema=\"name: string @index(term) .\"\n        ))\n\n        # Run mutation\n        txn = client.txn()\n        response = await txn.mutate(\n            set_obj={\"name\": \"Alice\"},\n            commit_now=True\n        )\n\n        # Run query\n        query = '{ me(func: has(name)) { name } }'\n        txn = client.txn(read_only=True)\n        response = await txn.query(query)\n        print(response.json)\n\n    finally:\n        await client.close()\n\nasyncio.run(main())\n```\n\n#### Using Connection Strings\n\nThe async client supports the same connection string format as the sync client:\n\n```python\nimport asyncio\nimport pydgraph\n\nasync def main():\n    # Using async_open with connection string\n    async with await pydgraph.async_open(\n        \"dgraph://groot:password@localhost:9080\"\n    ) as client:\n        version = await client.check_version()\n        print(f\"Connected to Dgraph version: {version}\")\n\nasyncio.run(main())\n```\n\n#### Using Context Managers\n\nBoth the async client and transactions support async context managers for automatic resource\ncleanup:\n\n```python\nimport asyncio\nimport pydgraph\n\nasync def main():\n    # Client auto-closes on exit\n    async with await pydgraph.async_open(\"dgraph://localhost:9080\") as client:\n        await client.login(\"groot\", \"password\")\n\n        # Transaction auto-discards on exit\n        async with client.txn() as txn:\n            response = await txn.query('{ me(func: has(name)) { name } }')\n            print(response.json)\n\nasyncio.run(main())\n```\n\n#### Concurrent Operations\n\nThe async client excels at running many operations concurrently:\n\n```python\nimport asyncio\nimport pydgraph\n\nasync def run_query(client, name):\n    \"\"\"Run a single query\"\"\"\n    query = f'{{ me(func: eq(name, \"{name}\")) {{ name }} }}'\n    txn = client.txn(read_only=True)\n    return await txn.query(query)\n\nasync def main():\n    async with await pydgraph.async_open(\"dgraph://localhost:9080\") as client:\n        await client.login(\"groot\", \"password\")\n\n        # Run 100 queries concurrently\n        names = [f\"User{i}\" for i in range(100)]\n        tasks = [run_query(client, name) for name in names]\n        results = await asyncio.gather(*tasks)\n\n        print(f\"Completed {len(results)} queries concurrently\")\n\nasyncio.run(main())\n```\n\n#### JWT Refresh\n\nThe async client automatically handles JWT token refresh, just like the sync client:\n\n```python\nasync with await pydgraph.async_open(\"dgraph://groot:password@localhost:9080\") as client:\n    # JWT will be automatically refreshed if it expires during operations\n    response = await client.alter(pydgraph.Operation(schema=\"name: string .\"))\n```\n\n#### Error Handling\n\nError handling works the same as the sync client:\n\n```python\nimport pydgraph\n\nasync def main():\n    async with await pydgraph.async_open(\"dgraph://localhost:9080\") as client:\n        try:\n            await client.login(\"groot\", \"wrong_password\")\n        except Exception as e:\n            print(f\"Login failed: {e}\")\n\n        try:\n            txn = client.txn(read_only=True)\n            await txn.mutate(set_obj={\"name\": \"Alice\"})\n        except pydgraph.errors.TransactionError as e:\n            print(f\"Cannot mutate in read-only transaction: {e}\")\n\nasyncio.run(main())\n```\n\n#### Differences from Sync Client\n\n| Feature             | Sync Client                 | Async Client                      |\n| ------------------- | --------------------------- | --------------------------------- |\n| Import              | `pydgraph.DgraphClient`     | `pydgraph.AsyncDgraphClient`      |\n| Connection function | `pydgraph.open()`           | `await pydgraph.async_open()`     |\n| Method calls        | `client.query()`            | `await client.query()`            |\n| Context manager     | `with client.txn() as txn:` | `async with client.txn() as txn:` |\n| Concurrency         | Threading                   | Native asyncio                    |\n| JWT refresh         | Automatic                   | Automatic                         |\n\n## Handling Transaction Conflicts\n\nDgraph uses **optimistic concurrency control** (MVCC). When multiple transactions modify the same\ndata simultaneously, conflicts can occur and Dgraph will abort one of the transactions with an\n`AbortedError`. When this happens, the entire transaction must be retried from scratch.\n\npydgraph provides built-in retry utilities with exponential backoff to handle these conflicts\nautomatically.\n\n### Using `run_transaction` (Recommended)\n\nThe simplest approach - pass your operation as a callable:\n\n```python\nimport pydgraph\n\ndef create_user(txn):\n    \"\"\"Transaction operation that will be retried on conflict.\"\"\"\n    response = txn.mutate(set_obj={\"name\": \"Alice\", \"age\": 30})\n    txn.commit()\n    return response.uids\n\nclient = pydgraph.DgraphClient(pydgraph.DgraphClientStub(\"localhost:9080\"))\n\n# Automatically retries on AbortedError with exponential backoff\nresult = pydgraph.run_transaction(client, create_user, max_retries=5)\nprint(f\"Created user: {result}\")\n```\n\nFor async code:\n\n```python\nasync def create_user_async(txn):\n    response = await txn.mutate(set_obj={\"name\": \"Alice\", \"age\": 30})\n    await txn.commit()\n    return response.uids\n\nresult = await pydgraph.run_transaction_async(client, create_user_async)\n```\n\n### Using the Retry Decorator\n\nWrap any function that performs Dgraph operations:\n\n```python\nimport pydgraph\n\n@pydgraph.with_retry(max_retries=5, base_delay=0.1)\ndef upsert_counter(client, counter_id):\n    \"\"\"Increment a counter atomically - automatically retried on conflict.\"\"\"\n    txn = client.txn()\n    try:\n        # Query current value\n        query = f'{{ counter(func: uid({counter_id})) {{ value }} }}'\n        result = txn.query(query)\n        current = json.loads(result.json).get(\"counter\", [{}])[0].get(\"value\", 0)\n\n        # Increment and update\n        txn.mutate(set_obj={\"uid\": counter_id, \"value\": current + 1})\n        txn.commit()\n    finally:\n        txn.discard()\n\n# Called normally - retries happen transparently\nupsert_counter(client, \"0x123\")\n```\n\nFor async functions:\n\n```python\n@pydgraph.with_retry_async(max_retries=5)\nasync def upsert_counter_async(client, counter_id):\n    async with client.txn() as txn:\n        # ... async operations\n        pass\n```\n\n### Using the Retry Generator\n\nFor fine-grained control within a function:\n\n```python\nimport pydgraph\n\ndef transfer_funds(client, from_account, to_account, amount):\n    \"\"\"Transfer funds between accounts with manual retry control.\"\"\"\n    for attempt in pydgraph.retry(max_retries=5, base_delay=0.1):\n        with attempt:\n            txn = client.txn()\n            try:\n                # Perform the transfer (queries and mutations)\n                # If AbortedError is raised, retry() handles it\n                txn.commit()\n            finally:\n                txn.discard()\n```\n\nFor async code:\n\n```python\nasync def transfer_funds_async(client, from_account, to_account, amount):\n    async for attempt in pydgraph.retry_async(max_retries=5):\n        with attempt:\n            async with client.txn() as txn:\n                # ... async operations\n                pass\n```\n\n### Retry Parameters\n\nAll retry utilities accept these parameters:\n\n| Parameter     | Default | Description                                           |\n| ------------- | ------- | ----------------------------------------------------- |\n| `max_retries` | 5       | Maximum number of retry attempts                      |\n| `base_delay`  | 0.1     | Initial delay in seconds between retries              |\n| `max_delay`   | 5.0     | Maximum delay cap in seconds                          |\n| `jitter`      | 0.1     | Random jitter factor (0-1) to prevent thundering herd |\n\n### Which Errors Are Retried?\n\nOnly these errors trigger automatic retries:\n\n- `pydgraph.AbortedError` - Transaction conflict (optimistic concurrency)\n- `pydgraph.RetriableError` - Transient server errors\n\nAll other exceptions propagate immediately.\n\n### Example: High-Contention Counter\n\nHere's a complete example handling a high-contention scenario:\n\n```python\nimport json\nimport pydgraph\n\ndef increment_counter(client, counter_uid):\n    \"\"\"Atomically increment a counter, handling conflicts automatically.\"\"\"\n\n    def operation(txn):\n        # Read current value\n        query = f'{{ counter(func: uid({counter_uid})) {{ count }} }}'\n        result = txn.query(query)\n        data = json.loads(result.json)\n        current = data.get(\"counter\", [{}])[0].get(\"count\", 0)\n\n        # Increment\n        txn.mutate(set_obj={\"uid\": counter_uid, \"count\": current + 1})\n        txn.commit()\n        return current + 1\n\n    return pydgraph.run_transaction(\n        client, operation,\n        max_retries=10,   # More retries for high contention\n        base_delay=0.05,  # Start with shorter delays\n        max_delay=2.0,\n        jitter=0.25       # Higher jitter to spread out retries\n    )\n\n# Usage\nclient = pydgraph.DgraphClient(pydgraph.DgraphClientStub(\"localhost:9080\"))\nnew_value = increment_counter(client, \"0x1\")\nprint(f\"Counter is now: {new_value}\")\n```\n\n## Examples\n\n[tls]: ./examples/tls\n[parse_datetime]: ./examples/parse_datetime\n\n- [simple][]: Quickstart example of using pydgraph.\n- [tls][]: Quickstart example that uses TLS.\n- [parse_datetime]: Demonstration of converting Dgraph's DateTime strings to native python datetime.\n\n## Contributing\n\nWe welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for detailed information on:\n/\n\n- Setting up your development environment\n- Code style and standards\n- Testing procedures\n- Submitting pull requests\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdgraph-io%2Fpydgraph","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdgraph-io%2Fpydgraph","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdgraph-io%2Fpydgraph/lists"}