Alter Schema using DQL in Python Client

Hi there,

When getting started with Dgraph I’ve been trying to use the Python client in order to alter the db schema. However when trying to use the DQL language shown in the docs the syntax is not accepted. It seems only GraphQL syntax is accepted.

This syntax does not work

type Person {
   name: String! @search(by: exact)
   friends: [Person]
}

This syntax does

name: string @index(exact) .
friends: [uid] .

type Person {
   name
   friends
}

Can anybody confirm that this is the case? Are they planning on changing this? Or is it possible I’m using it wrong?

I followed the little documentation on the Python client, but it’s not very informative and the part with the schema alteration in the examples is too trivial to be of help.

This syntax is GraphQL not DQL. GraphQL just works in GraphQL applications and libs. Like Apollo GraphQL and others. You won’t use GraphQL in Dgraph’s clients.

For sure there is some popular GraphQL client for Py.

Cheers.

1 Like
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