Python Client

v12.0.5

The official TerminusDB Python client library for data science and backend applications. Integrate graph database capabilities into your Python workflows.

$pip install terminusdb

Client

Client for TerminusDB server.

__init__(server_url, user_agent, **kwargs)

The Client constructor.

Parameters
server_urlstrURL of the server that this client will connect to.
user_agentoptional, strUser agent header when making requests. Defaults to terminusdb-client-python with the version appended.
**kwargsExtra configuration options

_check_connection()

Raise connection InterfaceError if not connected Defaults to check if a db is connected

_generate_commit(msg, author)

Pack the specified commit info into a dict format expected by the server.

Parameters
msgstrCommit message.
authorstrCommit author.
Returns
dictFormatted commit info.
Example: Python
>>> client = Client("http://127.0.0.1:6363/")
>>> client._generate_commit("<message>", "<author>")
{'author': '<author>', 'message': '<message>'}

_get_prefixes()

Get the prefixes for a given database

_prefix_url()

Get URL for prefix operations

add_prefix(prefix_name, uri)

Add a new prefix mapping.

Parameters
prefix_namestrThe prefix name to create (must follow NCName rules).
uristrThe IRI (namespace URL) this prefix expands to.
Returns
dictAPI response with status and details.
Example: Python
>>> client.add_prefix("ex", "http://example.org/")
{'@type': 'api:PrefixAddResponse', 'api:status': 'api:success', ...}

add_role(role)

Add a new role

Parameters
roledictThe role dict
Returns
dict or None if failed
Example: Python
>>> client = Client("http://127.0.0.1:6363")
>>> client.connect(key="root", team="admin", user="admin", db="example_db")
>>> role = {
    "name": "Grand Pubah",
    "action": [
        "branch",
        "class_frame",
        "clone",
        "commit_read_access",
        "commit_write_access",
        "create_database",
        "delete_database",
        "fetch",
        "instance_read_access",
        "instance_write_access",
        "manage_capabilities",
        "meta_read_access",
        "meta_write_access",
        "push",
        "rebase",
        "schema_read_access",
        "schema_write_access"
      ]
  }
>>> client.add_role(role)

add_user(username, password)

Add a new user

Parameters
usernamestrThe username of the user
passwordstrThe user's password
Returns
dict or None if failed

apply(before_version, after_object, branch)

Diff two different commits and apply changes on branch

Parameters
before_versionstringBefore branch/commit to compare
after_objectstringAfter branch/commit to compare
branchstringBranch to apply to. Optional.

change_capabilities(capability_change)

Change the capabilities of a certain user

Parameters
capability_changedictDict for the capability change request. Example: { "operation": "revoke", "scope": "UserDatabase/f5a0ef94469b32e1aee321678436c7dfd5a96d9c476672b3282ae89a45b5200e", "user": "User/admin", "roles": [ "Role/consumer", "Role/admin" ] }
Returns
dict or None if request failed

change_role(role)

Change role actions for a particular role

Parameters
roledictRole dict
Returns
dict or None if failed
Example: Python
>>> client = Client("http://127.0.0.1:6363")
>>> client.connect(key="root", team="admin", user="admin", db="example_db")
>>> role = {
    "name": "Grand Pubah",
    "action": [
        "branch",
        "class_frame",
        "clone",
        "commit_read_access",
        "commit_write_access",
        "create_database",
        "delete_database",
        "fetch",
        "instance_read_access",
        "instance_write_access",
        "manage_capabilities",
        "meta_read_access",
        "meta_write_access",
        "push",
        "rebase",
        "schema_read_access",
        "schema_write_access"
      ]
  }
>>> client.change_role(role)

change_user_password(username, password)

Change user's password

Parameters
usernamestrThe username of the user
passwordstrThe new password
Returns
dict or None if failed

clonedb(clone_source, newid, Description, remote_auth)

Clone a remote repository and create a local copy.

Parameters
clone_sourcestrThe source url of the repo to be cloned.
newidstrIdentifier of the new repository to create.
Descriptionstr, optionalOptional description about the cloned database.
remote_authstr, optionalOptional remote authorization (uses client remote auth otherwise)
Example: Python
>>> client = Client("http://127.0.0.1:6363/")
>>> client.clonedb("http://terminusdb.com/some_user/test_db", "my_test_db")

close()

Undo connect and close the connection.

commit()

Not implementated: open transactions currently not suportted. Please check back later.

connect(team, db, remote_auth, key, user, use_token, jwt_token, api_token, branch, ref, repo, **kwargs)

Connect to a Terminus server at the given URI with an API key.

Parameters
teamstrName of the team, default to be "admin"
dboptional, strName of the database connected
remote_authoptional, dictRemote Auth setting
keyoptional, strAPI key for connecting, default to be "root"
useroptional, strName of the user, default to be "admin"
use_tokenboolUse token to connect. If both `jwt_token` and `api_token` is not provided (None), then it will use the ENV variable TERMINUSDB_ACCESS_TOKEN to connect as the API token
jwt_tokenoptional, strThe Bearer JWT token to connect. Default to be None.
api_tokenoptional, strsThe API token to connect. Default to be None.
branchoptional, strBranch to be connected, default to be "main"
refoptional, strRef setting
repooptional, strLocal or remote repo, default to be "local"
**kwargsExtra configuration options.
Example: Python
>>> client = Client("http://127.0.0.1:6363")
>>> client.connect(key="root", team="admin", user="admin", db="example_db")

copy()

Create a deep copy of this client.

Returns
ClientThe copied client instance.
Example: Python
>>> client = Client("http://127.0.0.1:6363/")
>>> clone = client.copy()
>>> assert client is not clone

create_branch(new_branch_id, empty)

Create a branch starting from the current branch.

Parameters
new_branch_idstrNew branch identifier.
emptyboolCreate an empty branch if true (no starting commit)

create_database(dbid, team, label, description, prefixes, include_schema)

Create a TerminusDB database by posting a terminus:Database document to the Terminus Server.

Parameters
dbidstrUnique identifier of the database.
teamstr, optionalID of the Team in which to create the DB (defaults to 'admin')
labelstr, optionalDatabase name.
descriptionstr, optionalDatabase description.
prefixesdict, optionalOptional dict containing ``"@base"`` and ``"@schema"`` keys. @base (str) IRI to use when ``doc:`` prefixes are expanded. Defaults to ``terminusdb:///data``. @schema (str) IRI to use when ``scm:`` prefixes are expanded. Defaults to ``terminusdb:///schema``.
include_schemaboolIf ``True``, a main schema graph will be created, otherwise only a main instance graph will be created.
Example: Python
>>> client = Client("http://127.0.0.1:6363/")
>>> client.create_database("someDB", "admin", "Database Label", "My Description")

create_organization(org)

Add a new organization

Parameters
orgstrThe id of the organization
Returns
dict or None if failed

delete_branch(branch_id)

Delete a branch

Parameters
branch_idstrBranch to delete

delete_database(dbid, team, force)

Delete a TerminusDB database.

Parameters
dbidstrID of the database to delete
teamstr, optionalthe team in which the database resides (defaults to "admin")
forcebool
Example: Python
>>> client = Client("http://127.0.0.1:6363/")
>>> client.delete_database("<database>", "<team>")

delete_document(document, graph_type, commit_msg, last_data_version)

Delete the specified document(s)

Parameters
documentstr or list of strDocument(s) (as dictionary or DocumentTemplate objects) or id(s) of document(s) to be updated.
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
commit_msgstrCommit message.
last_data_versionstrLast version before the update, used to check if the document has been changed unknowingly

delete_organization(org)

Deletes a specific organization

Parameters
orgstrThe id of the organization
Returns
dict or None if request failed

delete_prefix(prefix_name)

Delete a prefix mapping.

Parameters
prefix_namestrThe prefix name to delete.
Returns
dictAPI response with status.
Example: Python
>>> client.delete_prefix("ex")
{'@type': 'api:PrefixDeleteResponse', 'api:status': 'api:success', ...}

delete_user(username)

Delete a user

Parameters
usernamestrThe username of the user
Returns
dict or None if failed

diff()

DEPRECATED

Returns
objPatch object
Example: Python
>>> client = Client("http://127.0.0.1:6363/")
>>> client.connect(user="admin", key="root", team="admin", db="some_db")
>>> result = client.diff({ "@id" : "Person/Jane", "@type" : "Person", "name" : "Jane"}, { "@id" : "Person/Jane", "@type" : "Person", "name" : "Janine"})
>>> result.to_json = '{ "name" : { "@op" : "SwapValue", "@before" : "Jane", "@after": "Janine" }}'

diff_object(before_object, after_object)

Diff two different objects.

Parameters
before_objectstringBefore object to compare
after_objectstringAfter object to compare

diff_version(before_version, after_version)

Diff two different versions. Can either be a branch or a commit

Parameters
before_versionstringCommit or branch of the before version to compare
after_versionstringCommit or branch of the after version to compare

fetch(remote_id)

Fetch the branch from a remote repo

Parameters
remote_idstrid of the remote

get_all_branches()

Get all the branches available in the database.

get_all_documents(graph_type, skip, count, as_list, get_data_version, kwargs)

Retrieves all avalibale the documents

Parameters
graph_typeGraphType, optionalGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
skipintThe starting posiion of the returning results, default to be 0
countint or NoneThe maximum number of returned result, if None (default) it will return all of the avalible result.
as_listboolIf the result returned as list rather than an iterator.
get_data_versionboolIf the version of the document(s) should be obtained. If True, the method return the result and the version as a tuple.
kwargsAdditional boolean flags for retriving. Currently avaliable: "prefixed", "unfold"
Returns
iterableStream of dictionaries

get_available_roles()

Get the available roles for the current authenticated user

Returns
dict or None if failed

get_class_frame(class_name)

Get the frame of the class of class_name. Provide information about all the avaliable properties of that class.

Parameters
class_namestrName of the class
Returns
dictDictionary containing information

get_commit_history(max_history)

Get the whole commit history. Commit history - Commit id, author of the commit, commit message and the commit time, in the current branch from the current commit, ordered backwards in time, will be returned in a dictionary in the follow format: ``` { "commit_id": { "author": "commit_author", "message": "commit_message", "timestamp: <datetime object of the timestamp>" } } ```

Parameters
max_historyint, optionalmaximum number of commit that would return, counting backwards from your current commit. Default is set to 500. It needs to be nop-negative, if input is 0 it will still give the last commit.
Returns
list

get_database()

Returns metadata (id, organization, label, comment) about the requested database Parameters ---------- dbid : str The id of the database team : str The organization of the database (default self.team)

Returns
dict

get_databases()

Returns a list of database metadata records for all databases the user has access to

Returns
list of dicts

get_document(iri_id, graph_type, get_data_version, kwargs)

Retrieves the document of the iri_id

Parameters
iri_idstrIri id for the document that is to be retrieved
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
get_data_versionboolIf the data version of the document(s) should be obtained. If True, the method return the result and the version as a tuple.
kwargsAdditional boolean flags for retriving. Currently avaliable: "prefixed", "minimized", "unfold"
Returns
dict

get_document_history(doc_id, team, db, start, count, created, updated)

Get the commit history for a specific document

Parameters
doc_idstrThe document ID (IRI) to retrieve history for (e.g., "Person/alice")
teamstr, optionalThe team from which the database is. Defaults to the class property.
dbstr, optionalThe database. Defaults to the class property.
startint, optionalStarting index for pagination. Defaults to 0.
countint, optionalMaximum number of history entries to return. Defaults to 10.
createdbool, optionalIf True, return only the creation time. Defaults to False.
updatedbool, optionalIf True, return only the last update time. Defaults to False.
Returns
listList of history entry dictionaries containing commit information for the specified document: ``` [ { "author": "admin", "identifier": "tbn15yq6rw1l4e9bgboyu3vwcoxgri5", "message": "Updated document", "timestamp": datetime.datetime(2023, 4, 6, 19, 1, 14, 324928) }, { "author": "admin", "identifier": "3v3naa8jrt8612dg5zryu4vjqwa2w9s", "message": "Created document", "timestamp": datetime.datetime(2023, 4, 6, 19, 0, 47, 406387) } ] ```

get_documents_by_type(doc_type, graph_type, skip, count, as_list, get_data_version, kwargs)

Retrieves the documents by type

Parameters
doc_typestrSpecific type for the docuemnts that is retriving
graph_typeGraphType, optionalGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
skipintThe starting posiion of the returning results, default to be 0
countint or NoneThe maximum number of returned result, if None (default) it will return all of the avalible result.
as_listboolIf the result returned as list rather than an iterator.
get_data_versionboolIf the version of the document(s) should be obtained. If True, the method return the result and the version as a tuple.
kwargsAdditional boolean flags for retriving. Currently avaliable: "prefixed", "unfold"
Returns
iterableStream of dictionaries

get_existing_classes()

Get all the existing classes (only ids) in a database.

get_organization(org)

Returns a specific organization

Parameters
orgstrThe id of the organization
Returns
dict or None if not found

get_organization_user(org, username)

Returns user info related to an organization.

Parameters
orgstr
usernamestr
Returns
dict or None if not found

get_organization_user_databases(org, username)

Returns the databases available to a user which are inside an organization

Parameters
orgstr
usernamestr
Returns
dict or None if not found

get_organization_users(org)

Returns a list of users in an organization.

Parameters
orgstr
Returns
dict or None if not found

get_organizations()

Returns a list of organizations in the database.

Returns
dict or None if not found

get_prefix(prefix_name)

Get a single prefix IRI by name.

Parameters
prefix_namestrThe prefix name to retrieve.
Returns
strThe IRI (namespace URL) this prefix expands to.
Example: Python
>>> client.get_prefix("schema")
'http://schema.org/'

get_triples(graph_type)

Retrieves the contents of the specified graph as triples encoded in turtle format

Parameters
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
Returns
str

get_user(username)

Get a user

Parameters
usernamestrThe username of the user
Returns
dict or None if failed

get_users()

Get all users

Returns
dict or None if failed

has_database(dbid, team)

Check whether a database exists

Parameters
dbidstrThe id of the database
teamstrThe organization of the database (default self.team)
Returns
True or False if not found

has_doc(doc_id, graph_type)

Check if a certain document exist in a database

Parameters
doc_idstrId of document to be checked.
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
Returns
Boolif the document exist

info()

Get info of a TerminusDB database server

Returns
dictDict with version information: ``` { "@type": "api:InfoResponse", "api:info": { "authority": "anonymous", "storage": { "version": "1" }, "terminusdb": { "git_hash": "53acb38f9aedeec6c524f5679965488788e6ccf5", "version": "10.1.5" }, "terminusdb_store": { "version": "0.19.8" } }, "api:status": "api:success" } ```

insert_document(document, graph_type, full_replace, commit_msg, last_data_version, compress, raw_json)

Inserts the specified document(s)

Parameters
documentdict or list of dictDocument(s) to be inserted.
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
full_replaceboolIf True then the whole graph will be replaced. WARNING: you should also supply the context object as the first element in the list of documents if using this option.
commit_msgstrCommit message.
last_data_versionstrLast version before the update, used to check if the document has been changed unknowingly
compressstr or intIf it is an integer, size of the data larger than this (in bytes) will be compress with gzip in the request (assume encoding as UTF-8, 0 = always compress). If it is `never` it will never compress the data.
raw_jsonboolUpdate as raw json
Returns
listlist of ids of the inseted docuemnts

insert_triples(graph_type, content, commit_msg)

Inserts into the specified graph with the triples encoded in turtle format.

Parameters
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
contentValid set of triples in Turtle or Trig format.
commit_msgstrCommit message.

list_databases()

Returns a list of database ids for all databases the user has access to

Returns
list of dicts

log()

Get commit history of a database Parameters ---------- team : str, optional The team from which the database is. Defaults to the class property. db : str, optional The database. Defaults to the class property. start : int, optional Commit index to start from. Defaults to 0. count : int, optional Amount of commits to get. Defaults to -1 which gets all.

Returns
listList of the following commit objects: ``` { "@id":"InitialCommit/hpl18q42dbnab4vzq8me4bg1xn8p2a0", "@type":"InitialCommit", "author":"system", "identifier":"hpl18q42dbnab4vzq8me4bg1xn8p2a0", "message":"create initial schema", "schema":"layer_data:Layer_4234adfe377fa9563a17ad764ac37f5dcb14de13668ea725ef0748248229a91b", "timestamp":1660919664.9129035 } ```

ok()

Check whether the TerminusDB server is still OK. Status is not OK when this function returns false or throws an exception (mostly ConnectTimeout)

Returns
bool

optimize(path)

Optimize the specified path.

Parameters
pathstringPath to optimize, for instance admin/database/_meta for the repo graph.
Example: Python
>>> client = Client("http://127.0.0.1:6363/")
>>> client.optimize('admin/database') # optimise database branch (here main)
>>> client.optimize('admin/database/_meta') # optimise the repository graph (actually creates a squashed flat layer)
>>> client.optimize('admin/database/local/_commits') # commit graph is optimised

patch(before, patch)

Apply the patch object to the before object and return an after object. Note that this change does not commit changes to the graph.

Parameters
beforedictObject before to patch
patchPatchPatch object to apply to the dict
Returns
dictAfter object
Example: Python
>>> client = Client("http://127.0.0.1:6363/")
>>> client.connect(user="admin", key="root", team="admin", db="some_db")
>>> patch_obj = Patch(json='{"name" : { "@op" : "ValueSwap", "@before" : "Jane", "@after": "Janine" }}')
>>> result = client.patch({ "@id" : "Person/Jane", "@type" : Person", "name" : "Jane"}, patch_obj)
>>> print(result)
'{ "@id" : "Person/Jane", "@type" : Person", "name" : "Janine"}'

patch_resource()

Apply the patch object to the given resource

Returns
dictAfter object
Example: Python
>>> client = Client("http://127.0.0.1:6363/")
>>> client.connect(user="admin", key="root", team="admin", db="some_db")
>>> patch_obj = Patch(json='{"name" : { "@op" : "ValueSwap", "@before" : "Jane", "@after": "Janine" }}')
>>> result = client.patch_resource(patch_obj,branch="main")
>>> print(result)
'["Person/Jane"]'

pull(remote, remote_branch, message, author)

Pull updates from a remote repository to the current database.

Parameters
remotestrremote to pull from, default "origin"
remote_branchstr, optionalremote branch to pull from, default to be your current barnch
messagestr, optionaloptional commit message
authorstr, optionaloption to overide the author of the operation
Returns
dict
Example: Python
>>> client = Client("http://127.0.0.1:6363/")
>>> client.pull()

push(remote, remote_branch, message, author, remote_auth)

Push changes from a branch to a remote repo

Parameters
remotestrremote to push to, default "origin"
remote_branchstr, optionalremote branch to push to, default to be your current barnch
messagestr, optionaloptional commit message
authorstr, optionaloption to overide the author of the operation
remote_authdict, optionaloptional remote authorization (uses client remote auth otherwise)
Returns
dict
Example: Python
>>> Client(server="http://localhost:6363").push(remote="origin", remote_branch = "main", author = "admin", message = "commit message"})

query(woql_query, commit_mg, get_data_version, last_data_version, file_dict)

Updates the contents of the specified graph with the triples encoded in turtle format Replaces the entire graph contents

Parameters
woql_querydict or WOQLQuery objectA woql query as an object or dict
commit_mgstrA message that will be written to the commit log to describe the change
get_data_versionboolIf the data version of the query result(s) should be obtained. If True, the method return the result and the version as a tuple.
last_data_versionstrLast version before the update, used to check if the document has been changed unknowingly
file_dict**deprecated**File dictionary to be associated with post name => filename, for multipart POST
Returns
dict
Example: Python
>>> Client(server="http://localhost:6363").query(woql, "updating graph")

query_document(document_template, graph_type, as_list, get_data_version)

Retrieves all documents that match a given document template

Parameters
document_templatedictTemplate for the document that is being retrived
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
as_listboolIf the result returned as list rather than an iterator.
get_data_versionboolIf the data version of the document(s) should be obtained. If True, the method return the result and the version as a tuple.
Returns
Iterable

rebase(branch, rebase_source, message, author)

Rebase the current branch onto the specified remote branch. Need to specify one of 'branch','commit' or the 'rebase_source'.

Parameters
branchstr, optionalthe branch for the rebase
rebase_sourcestr, optionalthe source branch for the rebase
messagestr, optionalthe commit message
authorstr, optionalthe commit author
Returns
dict
Example: Python
>>> client = Client("http://127.0.0.1:6363/")
>>> client.rebase("the_branch")

replace_document(document, graph_type, commit_msg, last_data_version, compress, create, raw_json)

Updates the specified document(s)

Parameters
documentdict or list of dictDocument(s) to be updated.
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
commit_msgstrCommit message.
last_data_versionstrLast version before the update, used to check if the document has been changed unknowingly
compressstr or intIf it is an integer, size of the data larger than this (in bytes) will be compress with gzip in the request (assume encoding as UTF-8, 0 = always compress). If it is `never` it will never compress the data.
createboolCreate the document if it does not yet exist.
raw_jsonboolUpdate as raw json

reset(commit, soft, use_path)

Reset the current branch HEAD to the specified commit path. If `soft` is not True, it will be a hard reset, meaning reset to that commit in the backend and newer commit will be wipped out. If `soft` is True, the client will only reference to that commit and can be reset to the newest commit when done.

Parameters
commitstringCommit id or path to the commit (if use_path is True), for instance '234980523ffaf93' or 'admin/database/local/commit/234980523ffaf93'. If not provided, it will reset to the newest commit (useful when need to go back after a soft reset).
softboolFlag indicating if the reset if soft, that is referencing to a previous commit instead of resetting to a previous commit in the backend and wipping newer commits.
use_pathboolWheather or not the commit given is an id or path. Default using id and use_path is False.
Example: Python
>>> client = Client("http://127.0.0.1:6363/")
>>> client.reset('234980523ffaf93')
>>> client.reset('admin/database/local/commit/234980523ffaf93', use_path=True)

rollback()

Curently not implementated. Please check back later.

set_db(dbid, team)

Set the connection to another database. This will reset the connection.

Parameters
dbidstrDatabase identifer to set in the config.
teamstrTeam identifer to set in the config. If not passed in, it will use the current one.
Returns
strThe current database identifier.
Example: Python
>>> client = Client("http://127.0.0.1:6363")
>>> client.set_db("database1")
'database1'

squash(message, author, reset)

Squash the current branch HEAD into a commit

Parameters
messagestringMessage for the newly created squash commit
authorstringAuthor of the commit
resetboolPerform reset after squash
Returns
strcommit id to be reset
Example: Python
>>> client = Client("http://127.0.0.1:6363/")
>>> client.connect(user="admin", key="root", team="admin", db="some_db")
>>> client.squash('This is a squash commit message!')

update_document(document, graph_type, commit_msg, last_data_version, compress)

Updates the specified document(s). Add the document if not existed.

Parameters
documentdict or list of dictDocument(s) to be updated.
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
commit_msgstrCommit message.
last_data_versionstrLast version before the update, used to check if the document has been changed unknowingly
compressstr or intIf it is an integer, size of the data larger than this (in bytes) will be compress with gzip in the request (assume encoding as UTF-8, 0 = always compress). If it is `never` it will never compress the data.

update_prefix(prefix_name, uri)

Update an existing prefix mapping.

Parameters
prefix_namestrThe prefix name to update.
uristrThe new IRI for this prefix.
Returns
dictAPI response with status and details.
Example: Python
>>> client.update_prefix("ex", "http://example.com/")
{'@type': 'api:PrefixUpdateResponse', 'api:status': 'api:success', ...}

update_triples(graph_type, content, commit_msg)

Updates the contents of the specified graph with the triples encoded in turtle format. Replaces the entire graph contents

Parameters
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
contentValid set of triples in Turtle or Trig format.
commit_msgstrCommit message.

upsert_prefix(prefix_name, uri)

Create or update a prefix mapping (upsert).

Parameters
prefix_namestrThe prefix name.
uristrThe IRI for this prefix.
Returns
dictAPI response with status and details.
Example: Python
>>> client.upsert_prefix("ex", "http://example.org/")
{'@type': 'api:PrefixUpdateResponse', 'api:status': 'api:success', ...}

WOQLQuery

__add__(other)

Creates a logical AND with the argument passed, for WOQLQueries.

Parameters
otherWOQLQuery object
Returns
WOQLQuery objectquery object that can be chained and/or execute

__and__(other)

Creates a logical AND with the argument passed, for WOQLQueries.

Parameters
otherWOQLQuery object
Returns
WOQLQuery objectquery object that can be chained and/or execute

__init__(query: dict, graph: str)

defines the internal functions of the woql query object - the language API is defined in WOQLQuery

Parameters
query: dictjson-ld query for initialisation
graph: strgraph that this query is appled to, default to be schema/main

__invert__(other)

Creates a logical Not with the argument passed, for WOQLQueries.

Parameters
otherWOQLQuery object
Returns
WOQLQuery objectquery object that can be chained and/or execute

__or__(other)

Creates a logical OR with the argument passed, for WOQLQueries.

Parameters
otherWOQLQuery object
Returns
WOQLQuery objectquery object that can be chained and/or execute

_add_partial(s, p, o, g)

Adds the query based on action given in builder context.

Parameters
sstrtarget subject
pstrtarget predicate
ostrtarget object
gstrgraphIRI
Returns
WOQLQuery objectquery object that can be chained and/or execute

_add_sub_query()

Internal library function which adds a subquery and sets the cursor

_arop()

Wraps arithmetic operators in the appropriate json-ld

_asv()

Wraps the elements of an AS variable in the appropriate json-ld

_clean_arithmetic_value()

Transforms whatever is passed in as the object of a triple into the appropriate json-ld form (variable, literal or id)

_clean_data_value()

Transforms whatever is passed in as the object of a triple into the appropriate json-ld form (variable, literal or id)

_clean_graph()

Transforms a graph filter by doing nothing

_clean_node_value()

Transforms whatever is passed in as the object of a triple into the appropriate json-ld form (variable, literal or id)

_clean_object()

Transforms whatever is passed in as the object of a triple into the appropriate json-ld form (variable, literal or id)

_clean_predicate()

Transforms whatever is passed in as the predicate (id or variable) into the appropriate json-ld form

_clean_subject()

Transforms whatever is passed in as the subject into the appropriate json-ld for variable or id

_coerce_to_dict()

Transforms a object representation of a query into a dictionary object if needs be

_compile_path_pattern()

Turns a textual path pattern into a JSON-LD description

_contains_update_check()

Does this query contain an update

_data_list()

takes input that can be either a string (variable name) or an array - each element of the array is a member of the list

_data_value_list()

DEPRECATED: Dead code - never called anywhere in the codebase.

_expand_variable(varname, always)

Transforms strings that start with v: into variable json-ld structures

Parameters
varnamestrwill be transformed if it starts with 'v:'
alwaysboolif True it will be transformed no matter it starts with 'v:' or not. Default to be False

_find_last_property(json)

Finds the last woql property that has a subject in it and returns the json for that used for triplebuilder to chain further calls - when they may be inside ands or ors or subqueries

Parameters
jsondictdictionary that representing the query in josn-ld

_find_last_subject(json)

Finds the last woql element that has a subject in it and returns the json for that used for triplebuilder to chain further calls - when they may be inside ands or ors or subqueries

Parameters
jsondictdictionary that representing the query in josn-ld

_get_object(s: str, p: str)

Function to get the object for the given subject and predicate.

Parameters
s: strSubject of the object
p: strPredicate of the object
Returns
WOQLQuery objectquery object that can be chained and/or execute

_jlt()

Wraps the passed value in a json-ld literal carriage

_json()

converts back and forward from json if the argument is present, the current query is set to it, if the argument is not present, the current json version of this query is returned

_same_entry(a, b)

A function to check the given two objects, which can be of different types (str, dict), are equal or not. When both the passed objects are dicts, deep comparison is done to check for the equality.

Parameters
astr or dict
bstr or dict
Returns
bool

_string_matches_object(s, obj)

A function to check if the given string is present in the passed dict or not.

Parameters
sstr
objdict
Returns
bool

_updated()

Called to inidicate that this query will cause an update to the DB

_value_list()

takes input that can be either a string (variable name) or an array - each element of the array is a member of the list

_vlist()

Wraps value lists in the appropriate json-ld

_wfrom()

JSON LD Format Descriptor

add_quad(subject, predicate, object_or_literal, graph)

Adds quads according to the pattern [subject, predicate, object, graph]

Parameters
subjectstrSubject
predicatestrPredicate
object_or_literalstrObject or Literal
graphstrGraph
Returns
WOQLQuery objectquery object that can be chained and/or execute

add_triple(subject, predicate, object_or_literal)

Adds triples according to the the pattern [subject, predicate, object]

Parameters
subjectstrSubject
predicatestrPredicate
object_or_literalstrObject or Literal
Returns
WOQLQuery objectquery object that can be chained and/or execute
Example: Python
This example adds a triple for a comment predicate and a certain value to the document identified by doc:X:
>>> update = WOQLQuery().add_triple("doc:X", "comment", "my comment")
>>> qry = WOQLQuery().when(True, update)
>>> client.update(qry.json(), 'MyDatabaseId')

added_quad(sub, pre, obj, gra, opt)

Creates a pattern matching rule for the quad [S, P, O, G] (Subject, Predicate, Object, Graph) added to the current commit.

Parameters
substrSubject
prestrPredicate
objstrObject
grastrGraph
optboolweather or not this quad is optional, default to be False
Returns
WOQLQuery objectquery object that can be chained and/or execute

added_triple(sub, pred, obj, opt)

Creates a triple pattern matching rule for the triple [S, P, O] (Subject, Predicate, Object) added to the current commit.

Parameters
substrSubject
predstrPredicate
objstrObject
optboolweather or not this triple is optional, default to be False
Returns
WOQLQuery objectquery object that can be chained and/or execute

all(subj, pred, obj, graph)

Calls the star method and returns the result of the same.

Parameters
subjstr, optionaltarget subject
predstr, optionaltarget predicate
objstr, optionaltarget object
graphstrgraphIRI
Returns
WOQLQuery objectquery object that can be chained and/or execute

boolean(input_bool)

Transforms the given bool object into the proper json-ld form

Parameters
input_boolboolthe given input string
Returns
dict

cast(val, user_type, result: str, literal_type: str, optional)

Changes the type of va to type and saves the return in vb

Parameters
valstroriginal variable
user_typestrtype to be changed
result: strsave the return variable
literal_type: str, optionalliteral type of`val`, can be used to treat `val` as a literal rather than an object or variable in the WOQL query. If literal type is "owl:Thing" or "node", `val` will be treated as object in the graph
Returns
WOQLQuery objectquery object that can be chained and/or execute

collect(template, into, query)

Collects all solutions of a sub-query into a list.

Parameters
templatestr or listA variable or list of variables specifying what to collect from each solution
intostrVariable that will be bound to the collected list
queryWOQLQuery, optionalThe query whose solutions will be collected
Returns
WOQLQuery objectquery object that can be chained and/or execute

comment(comment, Returns, -------, WOQLQuery object)

Adds a text comment to a query - can also be used to wrap any part of a query to turn it off

Parameters
commentstrtext comment
Returns
-------
WOQLQuery objectquery object that can be chained and/or execute

concat(concat_list, result)

Concatenates the list of variables into a string and saves the result in v

Parameters
concat_listlistlist of variables to concatenate
resultstrsaves the results
Returns
WOQLQuery objectquery object that can be chained and/or execute

count(result, query)

Counds the number of solutions in the given query

Parameters
resultA variable or non-negative integer with the count
queryThe query from which to count the number of results
Returns
WOQLQuery objectquery object that can be chained and/or executed

date(input_obj)

Transforms the given date object into the proper json-ld form

Parameters
input_objstrthe given input date object or a date string format YYYY-MM-DD
Returns
dict

date_duration(start, end, duration)

Tri-directional duration arithmetic for dates and dateTimes. Given any two of start, end, and duration, computes the third. Uses EOM preservation: last day of month maps to last day of target month. Accepts xsd:date or xsd:dateTime for start/end, xsd:duration for duration.

Parameters
startstr or dictthe start date or dateTime
endstr or dictthe end date or dateTime
durationstr or dictthe xsd:duration between start and end
Returns
WOQLQuery objectquery object that can be chained and/or execute

datetime(input_obj)

Transforms the given datetime object into the proper json-ld form

Parameters
input_objstrthe given input dateTime object or a datetime string format YYYY-MM-DDThh-mm-ssZ
Returns
dict

day_after(date, next_date)

Computes the calendar day after the given date. Bidirectional.

Parameters
datestr or dictthe input date
next_datestr or dictthe next calendar day
Returns
WOQLQuery objectquery object that can be chained and/or execute

day_before(date, previous)

Computes the calendar day before the given date. Bidirectional.

Parameters
datestr or dictthe input date
previousstr or dictthe previous calendar day
Returns
WOQLQuery objectquery object that can be chained and/or execute

delete_document(docjson, json_or_iri, Returns, -------, WOQLQuery object)

Delete a document into the database

Parameters
docjsonJSONobject to be deleted
json_or_iristrthe output ID, or a JSON to compare the ID against
Returns
-------
WOQLQuery objectquery object that can be chained and/or execute

delete_quad(subject, predicate, object_or_literal, graph)

Deletes any quads that match the rule [subject, predicate, object, graph]

Parameters
subjectstrSubject
predicatestrPredicate
object_or_literalstrObject or Literal
graphstrGraph
Returns
WOQLQuery objectquery object that can be chained and/or execute

delete_triple(subject, predicate, object_or_literal)

Deletes any triples that match the rule [subject, predicate, object]

Parameters
subjectstrSubject
predicatestrPredicate
object_or_literalstrObject or Literal
Returns
WOQLQuery objectquery object that can be chained and/or execute

distinct(args)

Ensures that the solutions for the variables [V1...Vn] are distinct

Parameters
argsThe variables to make distinct with the final argument being a query.
Returns
WOQLQuery objectquery object that can be chained and/or execute

div(args)

Division - integer division - args are divided left to right

Parameters
argsint or floatnumbers for division
Returns
WOQLQueryquery object that can be chained and/or execute

divide(args)

Divides numbers N1...Nn by each other left, to right precedence

Parameters
argsint or floatnumbers to be divided
Returns
WOQLQuery objectquery object that can be chained and/or execute

dot(dictionary, field, value)

Iterates through a list and returns a value for each member

Parameters
dictionarya WOQL dictionary or variable representing a dictionary
fieldstra string representing the field or key to access the dictionary
valuea WOQL value representing the result
Returns
WOQLQuery objectquery object that can be chained and/or execute

eq()

Matches if a is equal to b Parameters ---------- left : str object in the graph right : str object in the graph Returns ------- WOQLQuery object query object that can be chained and/or execute

eval(arith, res)

Evaluates the Arithmetic Expression Arith and copies the output to variable V

Parameters
arithWOQLQuery or dictquery or JSON-LD representing the query
resstroutput variable
Returns
WOQLQuery objectquery object that can be chained and/or execute

execute(client: Client object, commit_msg: str, file_dict:)

Executes the query using the passed client to connect to a server

Parameters
client: Client objectclient that provide connection to the database for the query to execute.
commit_msg: stroptional, commit message for this query. Recommended for query that carrries an update.
file_dict:File dictionary to be associated with post name => filename, for multipart POST

exp(first, second)

Raises A to the power of B

Parameters
firstint or floatbase number
secondint or floatpower of
Returns
WOQLQuery objectquery object that can be chained and/or execute

file(fpath, opts)

Provides details of a file source in a JSON format that includes a URL property

Parameters
fpathdict or strfile data source in a JSON format or file path
optsinput optionsoptional
Returns
WOQLQuery objectquery object that can be chained and/or execute

floor(user_input)

The floor function of a real number x denotes the greatest integer less than or equal to x.

Parameters
user_inputint or floatnumber whose floor needs to be calculated
Returns
WOQLQuery objectquery object that can be chained and/or execute

from_dict()

Set a query from a dictionary that represents the query in JSON-LD format.

from_json()

Set a query from a JSON-LD json string

get()

Takes an as structure

graph()

Used to specify that the rest of the query should use the graph g in calls to add_quad, quad, etc Parameters ---------- g : str target graph Returns ------- WOQLQuery object query object that can be chained and/or execute

greater(left, right)

Compares the value of v1 against v2 and returns true if v1 is greater than v2

Parameters
leftstr or numberfirst variable to compare
rightstr or numbersecond variable to compare
Returns
WOQLQuery objectquery object that can be chained and/or execute

group_by(group_vars, template, output, groupquery)

Groups the results of groupquery together by the list of variables group_vars, using the variable template as a grouping and saves the result into variable output.

Parameters
group_varslist or str or Var objectlist of variables to group
templatedict or list or strtemplate of data to group with free variable(s)
outputstr, optionaloutput variable
groupquerydict, optional
Returns
WOQLQuery objectquery object that can be chained and/or execute

gte()

Compares two values using greater-than-or-equal ordering. Parameters ---------- left : str or number the greater or equal value right : str or number the lesser or equal value Returns ------- WOQLQuery object query object that can be chained and/or execute

idgen(prefix, input_var_list, output_var)

Generates an ID for a node as a function of the passed VariableList with a specific prefix (URL base). If the values of the passed variables are the same, the output will be the same

Parameters
prefixstrprefix for the id
input_var_liststr or listvariable to generate id for
output_varstrthe variable to hold the id
Returns
WOQLQuery objectquery object that can be chained and/or execute

idgen_random(prefix, uri)

Generates a unique ID with cryptographically secure random suffix.

Parameters
prefixstrA prefix for the IDs to be generated (e.g. "Person/")
uristrVariable name or output target for the generated ID
Returns
WOQLQuery objectquery object that can be chained and/or executed

immediately(query)

Immediately runs side-effects without backtracking

Parameters
queryWOQLQuery object, optional
Returns
WOQLQuery objectquery object that can be chained and/or executed

in_range(value, start, end)

Tests whether a value falls within a half-open range [start, end). Succeeds if start <= value < end.

Parameters
valuestr or numberthe value to test
startstr or numberthe inclusive lower bound
endstr or numberthe exclusive upper bound
Returns
WOQLQuery objectquery object that can be chained and/or execute

insert_document(docjson, json_or_iri, Returns, -------, WOQLQuery object)

Insert a document into the database

Parameters
docjsonJSONobject to be inserted
json_or_iristrthe output ID, or a JSON to compare the ID against
Returns
-------
WOQLQuery objectquery object that can be chained and/or execute

interval(start, end, interval_val)

Constructs or deconstructs a half-open xdd:dateTimeInterval [start, end).

Parameters
startstr or dictinclusive start date
endstr or dictexclusive end date
interval_valstr or dictthe xdd:dateTimeInterval value
Returns
WOQLQuery objectquery object that can be chained and/or execute

interval_duration_end(duration, end, interval_val)

Relates an xdd:dateTimeInterval to its end endpoint and precise xsd:duration.

Parameters
durationstr or dictthe xsd:duration between start and end
endstr or dictexclusive end date or dateTime
interval_valstr or dictthe xdd:dateTimeInterval value
Returns
WOQLQuery objectquery object that can be chained and/or execute

interval_relation(relation, x_start, x_end, y_start, y_end)

Allen's Interval Algebra: classifies or validates the relationship between two half-open intervals [x_start, x_end) and [y_start, y_end).

Parameters
relationstr or dictrelation name (e.g. "before") or variable for classification
x_startstr or dictinclusive start of interval X
x_endstr or dictexclusive end of interval X
y_startstr or dictinclusive start of interval Y
y_endstr or dictexclusive end of interval Y
Returns
WOQLQuery objectquery object that can be chained and/or execute

interval_relation_typed(relation, x, y)

Allen's Interval Algebra on xdd:dateTimeInterval values.

Parameters
relationstr or dictrelation name (e.g. "before") or variable for classification
xstr or dictfirst xdd:dateTimeInterval value
ystr or dictsecond xdd:dateTimeInterval value
Returns
WOQLQuery objectquery object that can be chained and/or execute

interval_start_duration(start, duration, interval_val)

Relates an xdd:dateTimeInterval to its start endpoint and precise xsd:duration.

Parameters
startstr or dictinclusive start date or dateTime
durationstr or dictthe xsd:duration between start and end
interval_valstr or dictthe xdd:dateTimeInterval value
Returns
WOQLQuery objectquery object that can be chained and/or execute

into(graph_descriptor, query)

Sets the current output graph for writing output to.

Parameters
graph_descriptorstroutput graph
queryWOQLQuery object, optional
Returns
WOQLQuery objectquery object that can be chained and/or execute

isa(element, of_type)

Matches if element is a member of a certain type, according to the current state of the DB

Parameters
elementstrelement to be checked
of_typestrtype to be checked
Returns
bool

iso_week(date, year, week)

Computes the ISO 8601 week-numbering year and week number for a date. Accepts xsd:date or xsd:dateTime. Date must be ground. The ISO year may differ from the calendar year at year boundaries.

Parameters
datestr or dictthe input date or dateTime
yearstr or intthe ISO week-numbering year
weekstr or intthe ISO week number (1-53)
Returns
WOQLQuery objectquery object that can be chained and/or execute

join(user_input, glue, output)

Joins a list variable together (input) into a string variable (output) by glueing the strings together with glue

Parameters
user_inputlista list of variables
glue strjioining character(s)
outputstrvariable that sotres output
Returns
WOQLQuery objectquery object that can be chained and/or execute

length(var_list, var_len)

Length Calculates the length of a list

Parameters
var_listlistlist of elements
var_lennumnumber of eleemnts
Returns
WOQLQuery objectquery object that can be chained and/or execute

less(left, right)

Compares the value of v1 against v2 and returns true if v1 is less than v2

Parameters
leftstr or numberfirst variable to compare
rightstr or numbersecond variable to compare
Returns
WOQLQuery objectquery object that can be chained and/or execute

lib()

Returns the WOQL library instance for RDFList operations and other library functions.

Returns
WOQLLibraryLibrary object with rdflist_* methods

like(left, right, dist, Returns, -------, WOQLQuery object)

Matches left string to right string with a distance

Parameters
leftstrfirst string to compare
rightstrsecond string to compare
diststrHamming distance between left and right
Returns
-------
WOQLQuery objectquery object that can be chained and/or execute

limit(limit, query)

Specifies that only the first Number of rows will be returned

Parameters
limitintnumber of maximum results returned
queryWOQLQuery object, optional
Returns
WOQLQuery objectquery object that can be chained and/or execute

list_to_set(input_list, result_set)

Converts a list to a set (removes duplicates and sorts)

Parameters
input_liststr or listInput list or variable
result_setstrVariable to store the resulting set
Returns
WOQLQuery objectquery object that can be chained and/or execute

load_vocabulary()

Queries the schema graph and loads all the ids found there as vocabulary that can be used without prefixes ignoring blank node ids

localize(param_spec)

Build a localized scope for variables to prevent leaking local variables to outer scope.

Parameters
param_specdictObject mapping parameter names to values (or None for local vars)
Returns
tuple(localized_fn, v) where localized_fn wraps queries and v contains unique vars

lower(left, right)

Changes a string to lower-case - input is in u, output in l

Parameters
leftstrinput string
rightstrstores output
Returns
WOQLQuery objectquery object that can be chained and/or execute

lte()

Compares two values using less-than-or-equal ordering. Parameters ---------- left : str or number the lesser or equal value right : str or number the greater or equal value Returns ------- WOQLQuery object query object that can be chained and/or execute

member(member, mem_list)

Iterates through a list and returns a value for each member

Parameters
memberstra WOQL variable representing an element of the list
mem_liststra WOQL list variable
Returns
WOQLQuery objectquery object that can be chained and/or execute

minus(args)

Adds numbers N1...Nn together

Parameters
argsint or floatnumbers to add together
Returns
WOQLQuery objectquery object that can be chained and/or execute

month_end_date(year_month, date)

Computes the last day of the month for a given xsd:gYearMonth. Handles leap years correctly.

Parameters
year_monthstr or dicta gYearMonth value (e.g. 2024-02) or variable
datestr or dictthe resulting xsd:date or variable
Returns
WOQLQuery objectquery object that can be chained and/or execute

month_end_dates(date, start, end)

Generator: produces every last-of-month date in [start, end).

Parameters
datestrvariable for the generated last-of-month date
startstr or dictthe inclusive start date
endstr or dictthe exclusive end date
Returns
WOQLQuery objectquery object that can be chained and/or execute

month_start_date(year_month, date)

Computes the first day of the month for a given xsd:gYearMonth.

Parameters
year_monthstr or dicta gYearMonth value (e.g. 2024-01) or variable
datestr or dictthe resulting xsd:date or variable
Returns
WOQLQuery objectquery object that can be chained and/or execute

month_start_dates(date, start, end)

Generator: produces every first-of-month date in [start, end).

Parameters
datestrvariable for the generated first-of-month date
startstr or dictthe inclusive start date
endstr or dictthe exclusive end date
Returns
WOQLQuery objectquery object that can be chained and/or execute

once(query)

Obtains only one result from subquery

Parameters
queryWOQLQuery object, optional
Returns
WOQLQuery objectquery object that can be chained and/or executed

opt(query)

The Query in the Optional argument is specified as optional

Parameters
queryWOQLQuery object
Returns
WOQLQuery objectquery object that can be chained and/or execute

order_by(gvarlist, query)

Orders the results by the list of variables including in gvarlist, asc_or_desc is a WOQL.asc or WOQ.desc list of variables

Parameters
gvarlistlist or dict of WOQLQuery().asc or WOQLQuery().desc objects
queryWOQLQuery object, optional
Returns
WOQLQuery objectquery object that can be chained and/or execute

pad(user_input, pad, length, output)

Pads out the string input to be exactly len long by appending the pad character pad to form output

Parameters
user_inputstrinput string
padstrpadding character(s)
length intlength to pad
outputstrstores output
Returns
WOQLQuery objectquery object that can be chained and/or execute

path(subject, pattern, obj, path: str)

Create a path object constructed by the rules specified with pattern.

Parameters
subjectstra woql subject, the node that the path started
patternstra pattern which specified the edges the path is consisted of. It uses pattern construction syntax such as: * '(scm:edge1, scm:edge2)+' for repeated pattern, * 'scm:edge1|scm:edge2' for 'or' pattern, * '<scm:edge' for reverse pattern, and * '(scm:edge1)[n,m] for pattern between n and m times'
objstra woql object, the node that the path ended
path: stroutput variable
Returns
WOQLQuery objectquery object that can be chained and/or execute

plus(args)

Adds numbers N1...Nn together

Parameters
argsint or floatnumbers to add together
Returns
WOQLQuery objectquery object that can be chained and/or execute

post(fpath, opts)

Specifies a file to be posted as part of the request for processing.

Parameters
fpathstr or dictfile path/identifier or dict with file details
optsdict, optionaladditional options for file processing
Returns
WOQLQuery objectquery object that can be chained and/or execute

put()

Takes an array of variables, an optional array of column names

quad(sub, pre, obj, gra, opt)

Creates a pattern matching rule for the quad [S, P, O, G] (Subject, Predicate, Object, Graph)

Parameters
substrSubject
prestrPredicate
objstrObject
grastrGraph
optboolweather or not this quad is optional, default to be False
Returns
WOQLQuery objectquery object that can be chained and/or execute

quad_next(sub, pred, obj, next_val, graph)

Finds the next object value with an explicit graph selector.

Parameters
substrSubject, has to be a node (URI) or variable
predstrPredicate, can be variable (prefix with "v:") or node
objstrObject value or variable
next_valobjectNext object value or variable
graphstrGraph resource identifier (e.g. 'instance' or 'schema')
Returns
WOQLQuery objectquery object that can be chained and/or execute

quad_previous(sub, pred, obj, prev_val, graph)

Finds the previous object value with an explicit graph selector.

Parameters
substrSubject, has to be a node (URI) or variable
predstrPredicate, can be variable (prefix with "v:") or node
objstrObject value or variable
prev_valobjectPrevious object value or variable
graphstrGraph resource identifier (e.g. 'instance' or 'schema')
Returns
WOQLQuery objectquery object that can be chained and/or execute

quad_slice(sub, pred, obj, low, high, graph)

Creates a triple pattern matching rule for [S, P, O, G] with a half-open value range [low, high) on the object and an explicit graph selector.

Parameters
substrSubject, has to be a node (URI) or variable
predstrPredicate, can be variable (prefix with "v:") or node
objstrObject, can be variable or node or value
lowobjectThe inclusive lower bound as a typed value
highobjectThe exclusive upper bound as a typed value
graphstrGraph resource identifier (e.g. 'instance' or 'schema')
Returns
WOQLQuery objectquery object that can be chained and/or execute

quad_slice_rev(sub, pred, obj, low, high, graph)

Creates a triple pattern matching rule for [S, P, O, G] with a half-open value range [low, high) on the object in reverse order, with an explicit graph selector.

Parameters
substrSubject, has to be a node (URI) or variable
predstrPredicate, can be variable (prefix with "v:") or node
objstrObject, can be variable or node or value
lowobjectThe inclusive lower bound as a typed value
highobjectThe exclusive upper bound as a typed value
graphstrGraph resource identifier (e.g. 'instance' or 'schema')
Returns
WOQLQuery objectquery object that can be chained and/or execute

random_idgen(prefix, uri)

Generates a unique ID with cryptographically secure random suffix (alias for idgen_random).

Parameters
prefixstrA prefix for the IDs to be generated (e.g. "Person/")
uristrVariable name or output target for the generated ID
Returns
WOQLQuery objectquery object that can be chained and/or executed

range_max(input_list, result)

Find the maximum value in a list using the standard ordering.

Parameters
input_listlist or str or dictthe list of values to search
resultstr or dictvariable or value for the maximum
Returns
WOQLQuery objectquery object that can be chained and/or execute

range_min(input_list, result)

Find the minimum value in a list using the standard ordering.

Parameters
input_listlist or str or dictthe list of values to search
resultstr or dictvariable or value for the minimum
Returns
WOQLQuery objectquery object that can be chained and/or execute

read_document(iri, output_var, Returns, -------, WOQLQuery object, Example, -------, >>> query = (WOQLQuery().triple('v:TermId', 'rdf:type', '@schema:Term') &)

Read a document from the database

Parameters
iristrobject to be deleted
output_varstrthe document as JSON
Returns
-------
WOQLQuery objectquery object that can be chained and/or execute
Example
-------
>>> query = (WOQLQuery().triple('v:TermId', 'rdf:type', '@schema:Term') &WOQLQuery().triple('v:TermCountId','term','v:TermId') & WOQLQuery().triple('v:DocumentId', 'terms', 'v:TermCountId') & WOQLQuery().read_document('v:TermId','v:TermDoc'))

regexp(pattern, reg_str, reg_list)

Regular Expression Call pattern is a regex pattern (.*) using normal regular expression syntax, the only unusual thing is that special characters have to be escaped twice, s is the string to be matched and m is a list of matches: e.g. WOQLQuery().regexp("(.).*", "hello", ["v:All", "v:Sub"])

Parameters
patternstrregex pattern
reg_strstrstring to be matched
reg_liststr or list or dictstore list of matches
Returns
WOQLQuery objectquery object that can be chained and/or execute

remote(uri, opts)

Provides details of a remote data source in a JSON format that includes a URL property

Parameters
uristrremote data source
optsinput optionsoptional
Returns
WOQLQuery objectquery object that can be chained and/or execute

removed_quad(sub, pre, obj, gra, opt)

Creates a pattern matching rule for the quad [S, P, O, G] (Subject, Predicate, Object, Graph) added to the current commit.

Parameters
substrSubject
prestrPredicate
objstrObject
grastrGraph
optboolweather or not this quad is optional, default to be False
Returns
WOQLQuery objectquery object that can be chained and/or execute

removed_triple(sub, pred, obj, opt)

Creates a triple pattern matching rule for the triple [S, P, O] (Subject, Predicate, Object) added to the current commit.

Parameters
substrSubject
predstrPredicate
objstrObject
optboolweather or not this triple is optional, default to be False
Returns
WOQLQuery objectquery object that can be chained and/or execute

select(args)

Filters the query so that only the variables included in [V1...Vn] are returned in the bindings

Parameters
argsonly these variables are returned
Returns
WOQLQuery objectquery object that can be chained and/or execute

sequence(value, start, end, step, count)

Generates a sequence of values in the half-open range [start, end). When value is unbound, produces each value via backtracking.

Parameters
valuestr or numberthe generated sequence value (or variable)
startstr or numberthe inclusive start of the sequence
endstr or numberthe exclusive end of the sequence
stepstr or number, optionalincrement per step
countstr or number, optionaltotal count (validates if bound, unifies if unbound)
Returns
WOQLQuery objectquery object that can be chained and/or execute

set_difference(list_a, list_b, result)

Computes the set difference between two lists (elements in list_a but not in list_b)

Parameters
list_astr or listFirst list or variable
list_bstr or listSecond list or variable
resultstrVariable to store the result
Returns
WOQLQuery objectquery object that can be chained and/or execute

set_intersection(list_a, list_b, result)

Computes the set intersection of two lists (elements in both list_a and list_b)

Parameters
list_astr or listFirst list or variable
list_bstr or listSecond list or variable
resultstrVariable to store the result
Returns
WOQLQuery objectquery object that can be chained and/or execute

set_member(element, set_list)

Checks if an element is a member of a set (efficient O(log n) lookup)

Parameters
elementanyElement to check
set_liststr or listSet (list) to check membership in
Returns
WOQLQuery objectquery object that can be chained and/or execute

set_union(list_a, list_b, result)

Computes the set union of two lists (all unique elements from both lists)

Parameters
list_astr or listFirst list or variable
list_bstr or listSecond list or variable
resultstrVariable to store the result
Returns
WOQLQuery objectquery object that can be chained and/or execute

size(graph: Graph which needs to be set as resource, size: Size which needs to be set)

Sets the given graph and size for cursor.

Parameters
graph: Graph which needs to be set as resource
size: Size which needs to be set
Returns
WOQLQuery objectquery object that can be chained and/or execute

slice(input_list, result, start, end)

Extracts a contiguous subsequence from a list, following slice() semantics.

Parameters
input_listlist or strA list of values or a variable representing a list
resultstrA variable that stores the sliced result
startint or strThe start index (0-based, supports negative indices)
endint or str, optionalThe end index (exclusive). If omitted, takes the rest of the list
Returns
WOQLQuery objectquery object that can be chained and/or execute
Example: Python
>>> WOQLQuery().slice(["a", "b", "c", "d"], "v:Result", 1, 3)  # ["b", "c"]
>>> WOQLQuery().slice(["a", "b", "c", "d"], "v:Result", -2)    # ["c", "d"]

split(user_input, glue, output)

Splits a variable apart (input) into a list of variables (output) by separating the strings together with separator

Parameters
user_inputstrinput string or WOQL variable "v:"
gluestrcharacter string to separate string into list
outputstrWOQL variable that stores output list
Returns
WOQLQuery objectquery object that can be chained and/or execute

star(GraphIRI, Subj, Pred, Obj)

Selects everything as triples in the graph identified by GraphIRI into variables Subj, Pred, Obj - by default they are "v:Subject", "v:Predicate", "v:Object"

Parameters
GraphIRIstrgraphIRI
Subjstr, optionaltarget subject
Predstr, optionaltarget predicate
Objstr, optionaltarget object
Returns
WOQLQuery objectquery object that can be chained and/or execute

start(start, query)

Specifies that the start of the query returned

Parameters
startintindex of the frist result got returned
queryWOQLQuery object, optional
Returns
WOQLQuery objectquery object that can be chained and/or execute

string(input_str)

Transforms the given string into the proper json-ld form

Parameters
input_strstrthe given input string
Returns
dict

sub(parent, child)

Returns true if child is a sub-class of parent, according to the current DB schema

Parameters
parentstrthe parent class to be checked
childstr, optionalthe child class to be checked
Returns
bool

sum(user_input, output)

Joins a list variable containing numbers together (input) into a single number containing the sum.

Parameters
user_inputlista variable containing a list of numbers
outputstra variable that stores the output
Returns
WOQLQuery objectquery object that can be chained and/or execute

times(args)

Multiplies numbers N1...Nn together

Parameters
argsint or floatnumbers to be multiplied
Returns
WOQLQuery objectquery object that can be chained and/or execute

to_dict()

Give the dictionary that represents the query in JSON-LD format.

to_json()

Dumps the JSON-LD format of the query in a json string

trim(untrimmed, trimmed)

A trimmed version of untrimmed (with leading and trailing whitespace removed) is copied into trimmed

Parameters
untrimmedstroriginal string
trimmedstrWOQL varible storing the result string
Returns
WOQLQuery objectquery object that can be chained and/or execute

triple(sub, pred, obj, opt)

Creates a triple pattern matching rule for the triple [S, P, O] (Subject, Predicate, Object)

Parameters
substrSubject, has to be a node (URI)
predstrPredicate, can be variable (prefix with "v:") or node
objstrObject, can be variable or node or value
optboolwhether or not this triple is optional, default to be False
Returns
WOQLQuery objectquery object that can be chained and/or execute

triple_count(graph: Graph which needs to be set as resource, triple_count: Triple count which needs to be set)

Sets the given triple count and size for cursor.

Parameters
graph: Graph which needs to be set as resource
triple_count: Triple count which needs to be set
Returns
WOQLQuery objectquery object that can be chained and/or execute

triple_next(sub, pred, obj, next_val)

Finds the next object value after a reference for a given subject-predicate pair. When object is bound and next is free, finds the smallest next > object. When next is bound and object is free, finds the largest object < next.

Parameters
substrSubject, has to be a node (URI) or variable
predstrPredicate, can be variable (prefix with "v:") or node
objstrObject value or variable
next_valobjectNext object value or variable
Returns
WOQLQuery objectquery object that can be chained and/or execute

triple_previous(sub, pred, obj, prev_val)

Finds the previous object value before a reference for a given subject-predicate pair. When object is bound and previous is free, finds the largest previous < object. When previous is bound and object is free, finds the smallest object > previous.

Parameters
substrSubject, has to be a node (URI) or variable
predstrPredicate, can be variable (prefix with "v:") or node
objstrObject value or variable
prev_valobjectPrevious object value or variable
Returns
WOQLQuery objectquery object that can be chained and/or execute

triple_slice(sub, pred, obj, low, high)

Creates a triple pattern matching rule for [S, P, O] with a half-open value range [low, high) on the object. Returns triples whose typed object value falls within the specified range.

Parameters
substrSubject, has to be a node (URI) or variable
predstrPredicate, can be variable (prefix with "v:") or node
objstrObject, can be variable or node or value
lowobjectThe inclusive lower bound as a typed value
highobjectThe exclusive upper bound as a typed value
Returns
WOQLQuery objectquery object that can be chained and/or execute

triple_slice_rev(sub, pred, obj, low, high)

Creates a triple pattern matching rule for [S, P, O] with a half-open value range [low, high) on the object, returning results in reverse (descending) object order. Same semantics as triple_slice but iterates from highest to lowest value.

Parameters
substrSubject, has to be a node (URI) or variable
predstrPredicate, can be variable (prefix with "v:") or node
objstrObject, can be variable or node or value
lowobjectThe inclusive lower bound as a typed value
highobjectThe exclusive upper bound as a typed value
Returns
WOQLQuery objectquery object that can be chained and/or execute

true()

Sets true for cursor type.

Returns
WOQLQuery objectquery object that can be chained and/or execute

type_of(value, vtype)

Sets the given value and type for cursor.

Parameters
valuestrValue which needs to be set
vtypetypeType which needs to be set
Returns
WOQLQuery objectquery object that can be chained and/or execute

unique(prefix, key_list, uri)

Generates an ID for a node as a function of the passed VariableList with a specific prefix (URL base)(A.K.A Hashing) If the values of the passed variables are the same, the output will be the same

Parameters
prefixstrprefix for the id
key_liststrvariable to generate id for
uristrthe variable to hold the id
Returns
WOQLQuery objectquery object that can be chained and/or execute

update_document(docjson, json_or_iri, Returns, -------, WOQLQuery object)

Update a document in the database

Parameters
docjsonJSONobject to be updated
json_or_iristrthe output ID, or a JSON to compare the ID against
Returns
-------
WOQLQuery objectquery object that can be chained and/or execute

upper(left, right)

Changes a string to upper-case - input is in left, output in right

Parameters
leftstrinput string
rightstrstores output
Returns
WOQLQuery objectquery object that can be chained and/or execute

using(collection, Returns, -------, WOQLQuery object)

Use a specific data product for the enclosed query

Parameters
collectionstrthe name of the data product
Returns
-------
WOQLQuery objectquery object that can be chained and/or execute

variables()

Generate variables to be used in WOQLQueries Parameters ---------- args string arguments Returns ------- tuple/string args prefixed with "v:"

vars()

Generate variables to be used in WOQLQueries Parameters ---------- args string arguments Returns ------- tuple/string args prefixed with "v:"

weekday(date, weekday)

Computes the ISO 8601 weekday number (Monday=1, Sunday=7) for a date. Accepts xsd:date or xsd:dateTime. Date must be ground.

Parameters
datestr or dictthe input date or dateTime
weekdaystr or intthe ISO weekday number (1=Monday, 7=Sunday)
Returns
WOQLQuery objectquery object that can be chained and/or execute

weekday_sunday_start(date, weekday)

Computes the US-convention weekday number (Sunday=1, Saturday=7) for a date. Accepts xsd:date or xsd:dateTime. Date must be ground.

Parameters
datestr or dictthe input date or dateTime
weekdaystr or intthe US weekday number (1=Sunday, 7=Saturday)
Returns
WOQLQuery objectquery object that can be chained and/or execute

woql_and(args, Returns, -------, WOQLQuery object)

Creates a logical AND of the arguments Commonly used to combine WOQLQueries.

Parameters
argsWOQLQuery objects
Returns
-------
WOQLQuery objectquery object that can be chained and/or execute

woql_from(graph, query)

Specifies the database URL that will be the default database for the enclosed query

Parameters
graphstrurl of the database
queryWOQLQuery object, optional
Returns
WOQLQuery objectquery object that can be chained and/or execute

woql_not(query)

Creates a logical NOT of the arguments

Parameters
queryWOQLQuery object, optional
Returns
WOQLQuery objectquery object that can be chained and/or executed

woql_or(args)

Creates a logical OR of the arguments

Parameters
argsWOQLQuery objects
Returns
WOQLQuery objectquery object that can be chained and/or execute