Alter Schema using DQL in Python Client

import datetime
import json
import requests
import pydgraph
import time

# Create a client stub.
def create_client_stub():
    return pydgraph.DgraphClientStub('localhost:9080')

# Create a client.
def create_client(client_stub):
    return pydgraph.DgraphClient(client_stub)

# Drop All - discard all data and start from a clean slate.
def drop_all(client):
    return client.alter(pydgraph.Operation(drop_all=True))

# Set schema.
def set_schema(client):
    schema = """
    name: string @index(hash) .
    age: string .
    type TypeName {
        name: string
        age: string
        hasPet: [uid]
    }
    """
    return client.alter(pydgraph.Operation(schema=schema))

def create_data(client):
    # Create a new transaction.
    txn = client.txn()
    try:
        data_nquads = """
        <1> <name> "Anurag" .
        <1> <age> "10" .
        <1> <dgraph.type> "TypeName" .

        <2> <name> "Brad" .
        <2> <age> "20" .
        <2> <dgraph.type> "TypeName" .
        """
        # Run mutation.
        response = txn.mutate(set_nquads=data_nquads)

        # Commit transaction.
        txn.commit()
    finally:
        # Clean up. Calling this after txn.commit() is a no-op and hence safe.
        txn.discard()

def query(client):
    query = """query{
    q1(func: eq(name, "Anurag")) {
       uid
       name
       age
       }
    }"""
    res = client.txn(read_only=True).query(query)
    ppl = json.loads(res.json)
    prettyprint = json.dumps(ppl, indent=2)
    print(prettyprint)

def main():
    client_stub = create_client_stub()

    client = create_client(client_stub)
    drop_all(client)
    set_schema(client)
    create_date(client)
    query(client)
    client_stub.close()


if __name__ == '__main__':
    try:
        main()
        #print('DONE!')
    except Exception as e:
        print('Error: {}'.format(e))

You can use the above template for accessing dgraph via python client.

1 Like