Edit on Github

Dependencies

Client Python Grakn Core Grakn KGMS Python
1.5.4 1.5.8 1.5.8 >= 2.7
1.5.3 1.5.2 to 1.5.7 1.5.2 to 1.5.7 >= 2.7
1.5.2 1.5.2, 1.5.3 1.5.2 >= 2.7
1.5.1 1.5.0 N/A >= 2.7
1.4.2 1.3.0 to 1.4.3 1.2.0, 1.4.3 >= 3.6
1.3.0 to 1.3.2 1.3.0 1.4.3 >= 3.6

Installation

pip install grakn-client

If multiple Python versions are available, you may wish to use

pip3 install grakn-client

Quickstart

First make sure, the Grakn server is running.

In the interpreter or in your source, import GraknClient from grakn.client.

from grakn.client import GraknClient

Instantiate a client and open a session.

from grakn.client import GraknClient

with GraknClient(uri="localhost:48555") as client:
    with client.session(keyspace="social_network") as session:
        ## session is open
        pass
    ## session is closed
## client is closed

We can also pass the credentials, as specified when configuring authentication via Grakn Console, into the client constructor as a dictionary.

client = GraknClient(uri="localhost:48555", credentials={"username": "<username>", "password": "<password>"})

Create transactions to use for reading and writing data.

from grakn.client import GraknClient

with GraknClient(uri="localhost:48555") as client:
    with client.session(keyspace="social_network") as session:
        ## creating a write transaction
        with session.transaction().write() as write_transaction:
            ## write transaction is open
            ## write transaction must always be committed (closed)
            write_transaction.commit()

        ## creating a read transaction
        with session.transaction().read() as read_transaction:
            ## read transaction is open
            ## if not using a `with` statement, we must always close the read transaction like so
            # read_transaction.close()
            pass

Running basic retrieval and insertion queries.

from grakn.client import GraknClient

with GraknClient(uri="localhost:48555") as client:
    with client.session(keyspace="social_network") as session:
        ## Insert a Person using a WRITE transaction
        with session.transaction().write() as write_transaction:
            insert_iterator = write_transaction.query('insert $x isa person, has email "x@email.com";')
            concepts = insert_iterator.collect_concepts()
            print("Inserted a person with ID: {0}".format(concepts[0].id))
            ## to persist changes, write transaction must always be committed (closed)
            write_transaction.commit()

        ## Read the person using a READ only transaction
        with session.transaction().read() as read_transaction:
            answer_iterator = read_transaction.query("match $x isa person; get; limit 10;")

            for answer in answer_iterator:
                person = answer.map().get("x")
                print("Retrieved person with id " + person.id)

        ## Or query and consume the iterator immediately collecting all the results
        with session.transaction().read() as read_transaction:
            answer_iterator = read_transaction.query("match $x isa person; get; limit 10;")
            persons = answer_iterator.collect_concepts()
            for person in persons:
                print("Retrieved person with id "+ person.id)

        ## if not using a `with` statement, then we must always close the session and the read transaction
        # read_transaction.close()
        # session.close()
        # client.close()
[Important] Remember that transactions always need to be closed. The safest way is to use the `with ...` syntax which auto-closes at the end of the `with` block. Otherwise, remember to call `transaction.close()` explicitly.

Check out the Concept API to learn about the available methods on the concepts retrieved as the answers to Graql queries.

To view examples of running various Graql queries using the Grakn Client Python, head over to their dedicated documentation pages as listed below.


API Reference

Instantiating a Grakn client

GraknClient(uri=””, credientials = {})

In order to communicate with Grakn keyspaces via sessions and transactions, we first need to instantiate a Grakn client. The created object connects our application with the running Grakn Server.

Accepts

Param Description Type Required Default

uri

The host:port on which the Grakn Server is running

String

true

localhost:48555

credentials

The username and password required for connecting to the Grakn Server

{ “username”: “”, “password”: “” }

false

N/A

Returns

Client object

Client

Create a session/keyspace

client.session(keyspace)

Opens a communication tunnel (session) to the given keyspace on the running Grakn server. If no keyspace with the given name exists, a new one is created.

Accepts

Param Description Type Required Default

keyspace

The name of the keyspace with which the session connects.

String

true

N/A

Returns

Session object

Retrieve all keyspaces

client.keyspaces().retrieve()

Retrieves the name of all keyspaces running on the Grakn server.

Returns

List of Strings

Delete a keyspace

client.keyspaces().delete(“keyspace name”)

Deletes a keyspace with the given name.

Accepts

Param Description Type Required Default

keypsace

The name of the keyspace to be deleted.

String

true

N/A

Returns

None

Close a client

client.close()

Before instantiating a new client, the currently open client should first be closed.

Returns

None

Session

Open a read transaction

session.transaction().read()

Opens a read transaction to perform read queries on the keyspace connected to the session.

Returns

Transaction object

Open a write transaction

session.transaction().write()

Opens a write transaction to perform write queries on the keyspace connected to the session.

Returns

Transaction object

Close a session

session.close()

Closes the session. Before openning a new session, the currently open session should first be closed.

Returns

None

Transaction

Lazily execute a Graql query

transaction.query(query, infer=True)

Performs a Graql query on the and retrieves answers lazily.

Accepts

Param Description Type Required Default

query

The Graql query to be executed.

String

true

N/A

infer

Determines if the query should apply inference.

boolean

true

true

Returns

Iterator of Answer

Commit a write transaction

transaction.commit()

Commits the changes made on the local keyspace (via the caller transaction), to the original keyspace. Whether or not the transaction is commited successfully, it gets closed after the commit call.

Returns

None

Close a read transaction

transaction.close()

Closes the transaction. The currently open transaction must always be closed before opening another one.

Returns

None

Retrieve a concept by id

transaction.get_concept(id)

Retrieves the concept that has the given Grakn id. The concept in question, may be a concept type or an instance of one.

Accepts

Param Description Type Required Default

id

The id of the concept to retrieve.

String

true

N/A

Returns

Concept object or None

Retrieve a schema concept by label

transaction.get_schema_concept(label)

Accepts

Param Description Type Required Default

label

The label of the schema concept to retrieve.

String

true

N/A

Returns

Type object

Retrieve an attribute by value

transaction.get_attributes_by_value(value, datatype)

Accepts

Param Description Type Required Default

value

The value of the attribute to retrieve.

String, long, double, boolean or date

true

N/A

datatype

The datatype of the attribute to retrieve

grakn.DataType.STRING | LONG | DOUBLE | BOOLEAN | DATE

true

N/A

Returns

Iterator of Attributes

Create or retrieve an EntityType

transaction.put_entity_type(label)

Creates a new EntityType if none exists with the given label, otherwise retrieves the existing one.

Accepts

Param Description Type Required Default

label

The label of the EntityType to create or retrive.

String

true

N/A

Returns

EntityType object

Create or retrieve a RelationType

transaction.put_relation_type(label)

Creates a new RelationType if none exists with the given label, otherwise retrieves the existing one.

Accepts

Param Description Type Required Default

label

The label of the RelationType to create or retrive.

String

true

N/A

Returns

RelationType object

Create or retrieve an AttributeType

transaction.put_attribute_type(label)

Creates a new AttributeType if none exists with the given label, or retrieves the existing one.

Accepts

Param Description Type Required Default

label

The label of the AttributeType to create or retrive.

String

true

N/A

datatype

The datatype of the attribute to create or retrieve.

grakn.DataType.STRING | LONG | DOUBLE | BOOLEAN | DATE

true

N/A

Returns

AttributeType object

Create or retrieve a Role

transaction.put_role(label)

Creates a new Role if none exists with the given label, otherwise retrieves the existing one.

Accepts

Param Description Type Required Default

label

The label of the Role to create or retrive.

String

true

N/A

Returns

Role object

Create or retrieve a Rule

transaction.put_rule(label, when, then)

Creates a new Rule if none exists with the given label, or retrieves the existing one.

Accepts

Param Description Type Required Default

label

The label of the Rule to create or retrive.

String

true

N/A

when

The when body of the rule to create.

String

true

N/A

then

The then body of the rule to create.

String

true

N/A

Returns

Rule object

Iterator

Transaction queries return iterators of answers. In addition to the method below, the items in an Iterator can be consumed individually using next(iterator) method.

Consume the iterator eagerly

iterator.collect_concepts();

Consumes the iterator and collects all Concepts into a list.

Returns

List of Concept

Answer

The type of answers contained in the iterator depends on the type of the query that has returned the iterator. The table below illustrates the answer types mapped to query types.

Query Type Answer Type
define

ConceptMap

undefine

ConceptMap

get

ConceptMap

insert

ConceptMap

delete

ConceptMap

aggregate count/min/max/sum/mean/std

Numeric

aggregate group

AnswerGroup

compute count/min/max/sum/mean/std

Numeric

compute path

ConceptList

compute cluster

ConceptSet

compute centrality

ConceptSetMeasure

ConceptMap

Retrieve a mapping of variables to concepts

answer.map()

Produces a dictionary where keys are variable names and values are concepts

Returns

Dictionary of String to Concept

Retrieve a concept corresponding to a specific variable

answer.get(var)

Retrieve a concept for a given variable name without explicitly retriving the map

Accepts

Param Description Type Required Default

var

The string representation of a variable

String

Returns

Explaining an inferred answer

answer.explanation()

Provides an explanation on the inference of the concept in the answer, if the concept is in fact inferred.

Returns

Explanation

|

null

Numeric

Retrieve nummeric value of an aggregate/computed answer

answer.number()

Returns

int

|

float

Explaining an inferred answer

answer.explanation()

Provides an explanation on the inference of the concept in the answer, if the concept is in fact inferred.

Returns

Explanation

|

null

ConceptList

Retrieve ids of all concepts in a ConceptList answer

answer.list()

Returns

List of String

Explaining an inferred answer

answer.explanation()

Provides an explanation on the inference of the concept in the answer, if the concept is in fact inferred.

Returns

Explanation

|

null

ConceptSet

Retrieve set of ids of concepts after a cluster computation

answer.set()

Returns

Set of String

Explaining an inferred answer

answer.explanation()

Provides an explanation on the inference of the concept in the answer, if the concept is in fact inferred.

Returns

Explanation

|

null

ConceptSetMeasure

Retrieve the numeric value of a centrality computation

answer.measurement()

Returns

int

|

float

Retrieve a set of ids of concepts after a centrality computation

answer.set()

Returns

Set of String

Explaining an inferred answer

answer.explanation()

Provides an explanation on the inference of the concept in the answer, if the concept is in fact inferred.

Returns

Explanation

|

null

AnswerGroup

Retrieve the concept that is the group owner

answer.owner()

Returns

Retrieve the answers of the group

answer.answers()

Returns

List of Answer

Explaining an inferred answer

answer.explanation()

Provides an explanation on the inference of the concept in the answer, if the concept is in fact inferred.

Returns

Explanation

|

null

Explanation

Retrieve a Graql explanation of the answer

answer.query_pattern()

Returns

String

Retrieve source facts of inference

explanation.answers()

Provides a list of answers from which the inferred answer is derived.

Returns

List of ConceptMap