Dependencies

Before installing the Python grakn package, make sure the following dependencies are installed.

Installation

pip install grakn

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

pip3 install grakn

Quickstart

First make sure, the Grakn server is running.

In the interpreter or in your source, import grakn.

import grakn

Instantiate a client and open a session.

client = grakn.Grakn(uri="localhost:48555")
with client.session(keyspace="mykeyspace") as session:
  ## session is open
  pass
## session is closed

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

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

Create transactions to use for reading and writing data.

client = grakn.Grakn(uri="localhost:48555")

with client.session(keyspace="mykeyspace") as session:
  ## creating a write transaction
  with session.transaction(grakn.TxType.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(grakn.TxType.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()

Running basic retrieval and insertion queries.

import grakn

client = grakn.Grakn(uri="localhost:48555")

with client.session(keyspace="keyspace") as session:
  ## Insert a Person using a WRITE transaction
  with session.transaction(grakn.TxType.WRITE) as write_transaction:
    insert_iterator = write_transaction.query("insert $x isa person;")
    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(grakn.TxType.READ) as read_transaction
    answer_iterator = read_transaction.query("match $x isa person; limit 10; get;")

    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(grakn.TxType.READ) as read_transaction:
    answer_iterator = read_transaction.query("match $x isa person; limit 10; get;")
    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()
[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

Creating an instance of Grakn

grakn.Grakn(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 URI (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 name”)

Creates a communication channel to the given keyspace on the 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

Session

Create a transaction

session.transaction(type)

Creates a transaction to execute read and write operations on the keyspace connected to the session.

Accepts

Param Description Type Required Default

type

The type of the transaction to be created - read or write.

grakn.TxType.READ or grakn.TxType.WRITE

true

N/A

Returns

Transaction object

Close a session

session.close()

Closes the session once it is no longer being used.

Returns

None

Transaction

Lazily execute a Graql query

transaction.query(query, infer = True)

Prepare a Graql query to be executed on the keyspace where the session is connected to (answers are only computed when we ask for an answer, hence lazy).

Accepts

Param Description Type Required Default

infer

Determines if the query should apply inference.

boolean

true

true

Returns

Iterator of Answer

Commit a write transaction

transaction.commit()

Commits the inserted or deleted data instances or schema concepts to the keyspace attached to the session from which this transaction originated. The transaction is also closed on commit.

Returns

None

Close a read transaction

transaction.close()

Closes the transaction which has been used to read from the keyspace.

Returns

None

Retrieve a concept by ID

transaction.get_concept(concept_id)

Accepts

Param Description Type Required Default

concept_id

The id of the concept to retrieve

String

true

N/A

Returns

Concept object

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

datatype

The datatype of the attribute to retrieve

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

true

N/A

Returns

Create or retrievie an EntityType

transaction.put_entity_type(label)

Creates a new EntityType if none exists with the given label, or 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 RelationshipType

transaction.put_relationship_type(label)

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

Accepts

Param Description Type Required Default

label

The label of the RelationshipType to create or retrive.

String

true

N/A

Returns

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

datatype

The datatype of the attribute to create 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, or 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

then

The then body of the rule to create.

String

true

N/A

Returns

Rule object

Iterator

In addition to the methods 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

Value

aggregate group

AnswerGroup

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

Value

compute path

ConceptList

compute cluster

ConceptSet

compute centrality

ConceptSetMeasure

ConceptMap

Retrieve a map of Variable => Concept from the ConceptMap answer

answer.map()

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

Returns

Map ({variable_name: Concept})

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

Value

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

answer.answers()

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

Returns

List of Answer