Edit on Github

Installation

To use this client, you need a compatible Grakn Server running. Visit our Compatibility Table

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 everything from grakn.client.

from grakn.client import *

Instantiate a client and open a session.

from grakn.client import *

with Grakn.core_client("localhost:1729") as client:
    with client.session("social_network", SessionType.DATA) as session:
        ## session is open
        pass
    ## session is closed
## client is closed

Create transactions to use for reading and writing data.

from grakn.client import *

with Grakn.core_client("localhost:1729") as client:
    with client.session("social_network", SessionType.DATA) as session:
        ## creating a write transaction
        with session.transaction(TransactionType.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(TransactionType.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 *

with Grakn.core_client("localhost:1729") as client:
    with client.session("social_network", SessionType.DATA) as session:
        ## Insert a Person using a WRITE transaction
        with session.transaction(TransactionType.WRITE) as write_transaction:
            insert_iterator = write_transaction.query().insert('insert $x isa person, has email "[email protected]";')
            concepts = [ans.get("x") for ans in insert_iterator]
            print("Inserted a person with ID: {0}".format(concepts[0].get_iid()))
            ## to persist changes, write transaction must always be committed (closed)
            write_transaction.commit()

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

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

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

        ## 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 Core client

Grakn.core_client(address, parallelisation)

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

Accepts

Param Description Type Required Default

address

The address (host:port) on which the Grakn Server is running

String

true

parallelisation

The number of threads to use for server communication

int

false

2

Returns

Instantiating a Grakn Cluster client

Grakn.cluster_client(addresses, parallelisation)

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

Accepts

Param Description Type Required Default

addresses

All addresses (host:port) on which Grakn Cluster nodes are running

list of String

true

parallelisation

The number of threads to use for server communication

int

false

2

Returns

Client

Create a session for a database

client.session(database, session_type, options)

Opens a communication tunnel (session) to the given database on the running Grakn server.

Accepts

Param Description Type Required Default

database

The name of the database with which the session connects.

String

true

N/A

type

The type of session to be created (DATA or SCHEMA)

SessionType

true

N/A

options

Options for the session.

GraknOptions

false

N/A

Returns

Retrieve all databases

client.databases().all()

Retrieves all databases running on the Grakn server.

Returns

list of Database

Check if a database exists

client.databases().contains(database)

Checks if a database with the given name exists

Accepts

Param Description Type Required Default

database

The database name to be checked.

String

true

N/A

Create a database

client.databases().create(“database name”)

Create a database with the given name.

Accepts

Param Description Type Required Default

database

The name of the database to be created.

String

true

N/A

Returns

None

Retrieve a database

client.databases().get(“database name”);

Retrieve a database with the given name.

Accepts

Param Description Type Required Default

database

The name of the database to retrieve.

String

true

N/A

Returns

Database

Delete a database

client.databases().get(“database name”).delete()

Deletes a database with the given name.

Accepts

Param Description Type Required Default

database

The name of the database to be deleted.

String

true

N/A

Returns

None

Close a client

client.close()

Closes the client. Before instantiating a new client, the client that’s currently open should first be closed.

Returns

None

Session

Open a transaction

session.transaction(transaction_type, options)

Opens a transaction to perform read or write queries on the database connected to the session.

Accepts

Param Description Type Required Default

transactionType

The type of transaction to be created (READ or WRITE).

Transaction.Type

true

options

Options for the session.

GraknOptions

false

N/A

Returns

Check if a session is open

session.is_open()

Checks whether a session is presently open.

Returns

boolean

Check the session's type

session.session_type()

Checks the current session’s type (SCHEMA or DATA)

Returns

SessionType

Check the session's database

session.database()

Returns a string indicating what database the session is operating over.

Returns

String

Close a session

session.close()

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

Returns

None

Options

The transaction query options object GraknOptions can be used to override the default server behaviour query processing. Use GraknOptions.core() to create a new Grakn Core options object, or GraknOptions.cluster() for Grakn Cluster.

The options are:

  • infer: whether to enable inference for the provided query (only settable at transaction level and above) (default: False)
  • explain: whether to enable explanations for the provided query (default: False)
  • parallel: whether the server should use parallel or single-threaded execution (default: True)
  • batch_size: a guideline number of answers that the server should send before the client issues a fresh request (default: 50)
  • trace_inference: if enabled, outputs reasoning tracing graphs in the logging directory. Should be used with parallel = False. (default: False)
  • prefetch: if enabled, the first batch of answers is streamed to the client even without an explicit request for it (default: True if query type is match, otherwise False)
  • session_idle_timeout_millis: this timeout allows the server to close sessions if a client terminates or becomes unresponsive (default: 10000)
  • schema_lock_timeout_acquire_millis: how long the client should wait if opening a session or transaction is blocked by a schema write lock (default: 10000)

GraknClusterOptions has an additional option:

  • read_any_replica: enables reading data from any replica, potentially boosting read throughput (default: False)

Transaction

Check the transaction's type

transaction.transaction_type()

Checks the transaction’s type (READ or WRITE)

Returns

TransactionType

Check if the transaction is open

transaction.is_open()

Returns

boolean

Access Concept API methods

transaction.concepts();

Gets the ConceptManager for this Transaction, providing access to all Concept API methods.

Returns

Access Concept API - Logic methods

transaction.logic();

Gets the LogicManager for this Transaction, providing access to all Concept API - Logic methods.

Returns

Access Query API methods

transaction.query();

Gets the QueryManager for this Transaction, from which any Graql query can be executed.

Returns

Commit a write transaction

transaction.commit()

Commits the changes made via this transaction to the Grakn database. Whether or not the transaction is commited successfully, it gets closed after the commit call.

Returns

None

Rollback a write transaction

transaction.rollback()

Rolls back the uncommitted changes made via this transaction.

Returns

None

Close a read transaction

transaction.close()

Closes the transaction.

Returns

None

QueryManager

Execute a Graql Match query

transaction.query().match(query, options)

Performs a Graql Match query in the transaction.

Accepts

Param Description Type Required Default

query

The Graql Match query to be executed.

string

true

N/A

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Iterator of ConceptMap

Execute a Graql Match Aggregate query

transaction.query().match_aggregate(query, options)

Performs a Graql Match Aggregate query in the transaction.

Accepts

Param Description Type Required Default

query

The Graql Match Aggregate query to be executed.

string

true

N/A

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Execute a Graql Match Group query

transaction.query().match_group(query, options)

Performs a Graql Match Group query in the transaction.

Accepts

Param Description Type Required Default

query

The Graql Match Group query to be executed.

string

true

N/A

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Iterator of ConceptMapGroup

Execute a Graql Match Group Aggregate query

transaction.query().match_group_aggregate(query, options)

Performs a Graql Match Group Aggregate query in the transaction.

Accepts

Param Description Type Required Default

query

The Graql Match Group Aggregate query to be executed.

string

true

N/A

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Iterator of NumericGroup

Execute a Graql Insert query

transaction.query().insert(query, options)

Performs a Graql Insert query in the transaction.

Accepts

Param Description Type Required Default

query

The Graql Insert query to be executed.

string

true

N/A

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Iterator of ConceptMap

Execute a Graql Delete query

transaction.query().delete(query, options)

Performs a Graql Delete query in the transaction.

Accepts

Param Description Type Required Default

query

The Graql Delete query to be executed.

string

true

N/A

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Execute a Graql Update query

transaction.query().update(query, options)

Performs a Graql Update query in the transaction.

Accepts

Param Description Type Required Default

query

The Graql Update query to be executed.

string

true

N/A

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Iterator of ConceptMap

Execute a Graql Explain query

transaction.query().explain(explainable, options)

Performs a Graql Explain query in the transaction.

Accepts

Param Description Type Required Default

explainable

The Explainable to be explained.

ConceptMap.Explainable

true

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Iterator of Explanation

Execute a Graql Define query

transaction.query().define(query, options)

Performs a Graql Define query in the transaction.

Accepts

Param Description Type Required Default

query

The Graql Define query to be executed.

string

true

N/A

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Execute a Graql Undefine query

transaction.query().undefine(query, options)

Performs a Graql Undefine query in the transaction.

Accepts

Param Description Type Required Default

query

The Graql Undefine query to be executed.

string

true

N/A

options

Specify query options

GraknOptions

false

default GraknOptions - uses server defaults

Returns

Answer

The type of answers returned by execution of a query depends on the type of query executed. The table below illustrates the answer types mapped to query types.

Query Type Answer Type
match

Stream/Iterator of ConceptMap

match aggregate (count/min/max/sum/mean/std)

QueryFuture of Numeric

match group

Stream/Iterator of ConceptMapGroup

match group aggregate

Stream/Iterator of NumericGroup

insert

Stream/Iterator of ConceptMap

delete

QueryFuture

update

Stream/Iterator of ConceptMap

explain

Stream/Iterator of Explanation

define

QueryFuture

undefine

QueryFuture

ConceptMap

Retrieve a mapping of variables to concepts

concept_map.map()

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

Returns

Dictionary of String to Concept

Retrieve concepts

concept_map.concepts()

Return an iterable collection of all the concepts in this ConceptMap.

Returns

Iterable of Concept

Retrieve a concept corresponding to a specific variable

conceptMap.get(var)

Retrieve a concept for a given variable name

Accepts

Param Description Type Required Default

var

The string representation of a variable

String

Returns

Retrieve explainable concepts

conceptMap.explainables()

Gets the Explainables object for this ConceptMap, exposing which of the Concepts in this ConceptMap are explainable

Returns

Numeric

Retrieve numeric value of an aggregate answer as an integer

numeric.as_int();

Returns

int

Retrieve numeric value of an aggregate answer as a float

numeric.as_float();

Returns

float

Checks if the type of an aggregate answer is an integer

numeric.is_int();

Returns

boolean

Checks if the type of an aggregate answer is a float

numeric.is_float();

Returns

boolean

Checks if the type of an aggregate answer is not a number

concept_map_group.is_NaN()

Returns

boolean

ConceptMapGroup

Retrieve the concept that is the group owner

concept_map_group.owner()

Returns

Retrieve the ConceptMaps of the group

concept_map_group.concept_maps();

Returns

List of ConceptMaps

Explainables

Retrieve explainable relation

concept_map.explainables().relation(variable);

Retrieves the explainable relation with the given variable name.

Accepts

Param Description Type Required Default

variable

The string representation of a variable

String

Returns

Retrieve explainable attribute

concept_map.explainables().attribute(variable);

Retrieves the explainable attribute with the given variable name.

Accepts

Param Description Type Required Default

variable

The string representation of a variable

String

Returns

Retrieve explainable ownership

concept_map.explainables().ownership(variable);

Retrieves the explainable attribute ownership with the given variable name.

Accepts

Param Description Type Required Default

variable

The string representation of a variable

String

Returns

Retrieve explainable relations

concept_map.explainables().relations();

Retrieves all of this ConceptMap’s explainable relations.

Returns

Dictionary of String to ConceptMap.Explainable

Retrieve explainable attributes

concept_map.explainables().attributes();

Retrieves all of this ConceptMap’s explainable attributes.

Returns

Dictionary of String to ConceptMap.Explainable

Retrieve explainable ownerships

concept_map.explainables().ownerships();

Retrieves all of this ConceptMap’s explainable attribute ownerships.

Returns

Dictionary of String to ConceptMap.Explainable

Explainable

Retrieve conjunction

explainable.conjunction()

Retrieves the subquery of the original query that is actually being explained.

Returns

String

Retrieve ID

explainable.explainable_id()

Retrieves the unique ID that identifies this Explainable.

Returns

int

Explanation

Retrieve the rule

explanation.rule()

Retrieves the Rule for this Explanation.

Returns

Rule

Retrieve the conclusion

explanation.conclusion()

Retrieves the Conclusion for this Explanation.

Returns

ConceptMap

Retrieve the condition

explanation.condition()

Retrieves the Condition for this Explanation.

Returns

ConceptMap

Retrieve the variable mapping

explanation.variable_mapping()

Retrieves the mapping between rule variables and query variables for this Explanation.

Returns

Map<String, Set>

QueryFuture

Transaction queries that return single answers or empty responses are executed asynchronously on the server. To wait for a query to finish execution, and return its result if there is one, use the ‘get()’ function.

Get the query result

future.get()

Waits for the query to finish execution, and returns its result, if present.

Returns

Returns according to type of query executed

Map the query result

future.map(function)

Transforms the QueryFuture into a new QueryFuture by running the supplied function on the query result when it is returned.

Returns

Return type of supplied function

Version Compatibility

Client Python Grakn Core Grakn Cluster Python
2.0.1 2.0.2 2.0.2 >= 3.6
2.0.0 2.0.0, 2.0.1 2.0.0, 2.0.1 >= 3.6
1.8.0 1.8.0 to 1.8.4 N/A >= 3.5, < 3.8
1.7.2 1.7.1, 1.7.2 N/A >= 2.7
1.7.1 1.7.1 N/A >= 2.7
1.7.0 1.7.1 N/A >= 2.7
1.6.0 to 1.6.1 1.6.0 to 1.6.2 1.6.2 >= 2.7
1.5.4 1.5.8, 1.5.9 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