Modules

stardog.connection

Connect to Stardog databases.

class stardog.connection.Connection(database, endpoint=None, username=None, password=None, auth=None, session=None)[source]

Bases: object

Database Connection.

This is the entry point for all user-related operations on a Stardog database

__init__(database, endpoint=None, username=None, password=None, auth=None, session=None)[source]

Initializes a connection to a Stardog database.

Parameters
  • database (str) – Name of the database

  • endpoint (str) – Url of the server endpoint. Defaults to http://localhost:5820

  • username (str, optional) – Username to use in the connection

  • password (str, optional) – Password to use in the connection

  • auth (requests.auth.AuthBase, optional) – requests Authentication object. Defaults to None

  • session (requests.session.Session, optional) – requests Session object. Defaults to None

Examples

>>> conn = Connection('db', endpoint='http://localhost:9999',
                      username='admin', password='admin')
add(content, graph_uri=None)[source]

Adds data to the database.

Parameters
  • content (Content) – Data to add

  • graph_uri (str, optional) – Named graph into which to add the data

Raises

stardog.exceptions.TransactionException – If not currently in a transaction

Examples

>>> conn.add(File('example.ttl'), graph_uri='urn:graph')
ask(query, **kwargs)[source]

Executes a SPARQL ask query.

Parameters
  • query (str) – SPARQL query

  • base_uri (str, optional) – Base URI for the parsing of the query

  • limit (int, optional) – Maximum number of results to return

  • offset (int, optional) – Offset into the result set

  • timeout (int, optional) – Number of ms after which the query should timeout. 0 or less implies no timeout

  • reasoning (bool, optional) – Enable reasoning for the query

  • bindings (dict, optional) – Map between query variables and their values

Returns

Result of ask query

Return type

bool

Examples

>>> conn.ask('ask {:subj :pred :obj}', reasoning=True)
begin(**kwargs)[source]

Begins a transaction.

Parameters

reasoning (bool, optional) – Enable reasoning for all queries inside the transaction. If the transaction does not have reasoning enabled, queries within will not be able to use reasoning.

Returns

Transaction ID

Return type

str

Raises

stardog.exceptions.TransactionException – If already in a transaction

clear(graph_uri=None)[source]

Removes all data from the database or specific named graph.

Parameters

graph_uri (str, optional) – Named graph from which to remove data

Raises

stardog.exceptions.TransactionException – If currently not in a transaction

Examples

clear a specific named graph

>>> conn.clear('urn:graph')

clear the whole database

>>> conn.clear()
close()[source]

Close the underlying HTTP connection.

commit()[source]

Commits the current transaction.

Raises

stardog.exceptions.TransactionException – If currently not in a transaction

docs()[source]

Makes a document storage object.

Returns

A Docs object

Return type

Docs

explain(query, base_uri=None)[source]

Explains the evaluation of a SPARQL query.

Parameters
  • query (str) – SPARQL query

  • base_uri (str, optional) – Base URI for the parsing of the query

Returns

Query explanation

Return type

str

explain_inconsistency(graph_uri=None)[source]

Explains why the database or a named graph is inconsistent.

Parameters

graph_uri (str, optional) – Named graph for which to explain inconsistency

Returns

Explanation results

Return type

dict

explain_inference(content)[source]

Explains the given inference results.

Parameters

content (Content) – Data from which to provide explanations

Returns

Explanation results

Return type

dict

Examples

>>> conn.explain_inference(File('inferences.ttl'))
export(content_type='text/turtle', stream=False, chunk_size=10240, graph_uri=None)[source]

Exports the contents of the database.

Parameters
  • content_type (str) – RDF content type. Defaults to ‘text/turtle’

  • stream (bool) – Chunk results? Defaults to False

  • chunk_size (int) – Number of bytes to read per chunk when streaming. Defaults to 10240

  • graph_uri (str, optional) – Named graph to export

Returns

If stream = False

Return type

str

Returns

If stream = True

Return type

gen

Examples

no streaming

>>> contents = conn.export()

streaming

>>> with conn.export(stream=True) as stream:
      contents = ''.join(stream)
graph(query, content_type='text/turtle', **kwargs)[source]

Executes a SPARQL graph query.

Parameters
  • query (str) – SPARQL query

  • base_uri (str, optional) – Base URI for the parsing of the query

  • limit (int, optional) – Maximum number of results to return

  • offset (int, optional) – Offset into the result set

  • timeout (int, optional) – Number of ms after which the query should timeout. 0 or less implies no timeout

  • reasoning (bool, optional) – Enable reasoning for the query

  • bindings (dict, optional) – Map between query variables and their values

  • content_type (str) – Content type for results. Defaults to ‘text/turtle’

Returns

Results in format given by content_type

Return type

str

Examples

>>> conn.graph('construct {?s ?p ?o} where {?s ?p ?o}',
               offset=100, limit=100, reasoning=True)

bindings

>>> conn.graph('construct {?s ?p ?o} where {?s ?p ?o}',
               bindings={'o': '<urn:a>'})
graphql()[source]

Makes a GraphQL object.

Returns

A GraphQL object

Return type

GraphQL

icv()[source]

Makes an integrity constraint validation object.

Returns

An ICV object

Return type

ICV

is_consistent(graph_uri=None)[source]

Checks if the database or named graph is consistent wrt its schema.

Parameters

graph_uri (str, optional) – Named graph from which to check consistency

Returns

Database consistency state

Return type

bool

paths(query, content_type='application/sparql-results+json', **kwargs)[source]

Executes a SPARQL paths query.

Parameters
  • query (str) – SPARQL query

  • base_uri (str, optional) – Base URI for the parsing of the query

  • limit (int, optional) – Maximum number of results to return

  • offset (int, optional) – Offset into the result set

  • timeout (int, optional) – Number of ms after which the query should timeout. 0 or less implies no timeout

  • reasoning (bool, optional) – Enable reasoning for the query

  • bindings (dict, optional) – Map between query variables and their values

  • content_type (str) – Content type for results. Defaults to ‘application/sparql-results+json’

Returns

if content_type=’application/sparql-results+json’.

Return type

dict

Returns

other content types.

Return type

str

Examples

>>> conn.paths('paths start ?x = :subj end ?y = :obj via ?p',
               reasoning=True)
remove(content, graph_uri=None)[source]

Removes data from the database.

Parameters
  • content (Content) – Data to add

  • graph_uri (str, optional) – Named graph from which to remove the data

Raises

stardog.exceptions.TransactionException – If currently not in a transaction

Examples

>>> conn.remove(File('example.ttl'), graph_uri='urn:graph')
rollback()[source]

Rolls back the current transaction.

Raises

stardog.exceptions.TransactionException – If currently not in a transaction

select(query, content_type='application/sparql-results+json', **kwargs)[source]

Executes a SPARQL select query.

Parameters
  • query (str) – SPARQL query

  • base_uri (str, optional) – Base URI for the parsing of the query

  • limit (int, optional) – Maximum number of results to return

  • offset (int, optional) – Offset into the result set

  • timeout (int, optional) – Number of ms after which the query should timeout. 0 or less implies no timeout

  • reasoning (bool, optional) – Enable reasoning for the query

  • bindings (dict, optional) – Map between query variables and their values

  • content_type (str, optional) – Content type for results. Defaults to ‘application/sparql-results+json’

Returns

If content_type=’application/sparql-results+json’

Return type

dict

Returns

Other content types

Return type

str

Examples

>>> conn.select('select * {?s ?p ?o}',
                offset=100, limit=100, reasoning=True)

bindings

>>> conn.select('select * {?s ?p ?o}', bindings={'o': '<urn:a>'})
size(exact=False)[source]

Database size.

Parameters

exact (bool, optional) – Calculate the size exactly. Defaults to False

Returns

The number of elements in database

Return type

int

update(query, **kwargs)[source]

Executes a SPARQL update query.

Parameters
  • query (str) – SPARQL query

  • base_uri (str, optional) – Base URI for the parsing of the query

  • limit (int, optional) – Maximum number of results to return

  • offset (int, optional) – Offset into the result set

  • timeout (int, optional) – Number of ms after which the query should timeout. 0 or less implies no timeout

  • reasoning (bool, optional) – Enable reasoning for the query

  • bindings (dict, optional) – Map between query variables and their values

Examples

>>> conn.update('delete where {?s ?p ?o}')
class stardog.connection.Docs(client)[source]

Bases: object

BITES: Document Storage.

__init__(client)[source]

Initializes a Docs.

Use stardog.connection.Connection.docs() instead of constructing manually.

add(name, content)[source]

Adds a document to the store.

Parameters
  • name (str) – Name of the document

  • content (Content) – Contents of the document

Examples

>>> docs.add('example', File('example.pdf'))
clear()[source]

Removes all documents from the store.

delete(name)[source]

Deletes a document from the store.

Parameters

name (str) – Name of the document

get(name, stream=False, chunk_size=10240)[source]

Gets a document from the store.

Parameters
  • name (str) – Name of the document

  • stream (bool) – If document should come in chunks or as a whole. Defaults to False

  • chunk_size (int) – Number of bytes to read per chunk when streaming. Defaults to 10240

Returns

If stream=False

Return type

str

Returns

If stream=True

Return type

gen

Examples

no streaming

>>> contents = docs.get('example')

streaming

>>> with docs.get('example', stream=True) as stream:
                  contents = ''.join(stream)
size()[source]

Calculates document store size.

Returns

Number of documents in the store

Return type

int

class stardog.connection.GraphQL(conn)[source]

Bases: object

__init__(conn)[source]

Initializes a GraphQL.

Use stardog.connection.Connection.graphql() instead of constructing manually.

add_schema(name, content)[source]

Adds a schema to the database.

Parameters
  • name (str) – Name of the schema

  • content (Content) – Schema data

Examples

>>> gql.add_schema('people', content=File('people.graphql'))
clear_schemas()[source]

Deletes all schemas.

query(query, variables=None)[source]

Executes a GraphQL query.

Parameters
  • query (str) – GraphQL query

  • variables (dict, optional) – GraphQL variables. Keys: @reasoning’ (bool) to enable reasoning, @schema’ (str) to define schemas

Returns

Query results

Return type

dict

Examples

with schema and reasoning

>>> gql.query('{ Person {name} }',
              variables={'@reasoning': True, '@schema': 'people'})

with named variables

>>> gql.query(
      'query getPerson($id: Integer) { Person(id: $id) {name} }',
      variables={'id': 1000})
remove_schema(name)[source]

Removes a schema from the database.

Parameters

name (str) – Name of the schema

schema(name)[source]

Gets schema information.

Parameters

name (str) – Name of the schema

Returns

GraphQL schema

Return type

dict

schemas()[source]

Retrieves all available schemas.

Returns

All schemas

Return type

dict

class stardog.connection.ICV(conn)[source]

Bases: object

Integrity Constraint Validation.

__init__(conn)[source]

Initializes an ICV.

Use stardog.connection.Connection.icv() instead of constructing manually.

add(content)[source]

Adds integrity constraints to the database.

Parameters

content (Content) – Data to add

Examples

>>> icv.add(File('constraints.ttl'))
clear()[source]

Removes all integrity constraints from the database.

convert(content, graph_uri=None)[source]

Converts given integrity constraints to a SPARQL query.

Parameters
  • content (Content) – Integrity constraints

  • graph_uri (str, optional) – Named graph from which to apply constraints

Returns

SPARQL query

Return type

str

Examples

>>> icv.convert(File('constraints.ttl'), graph_uri='urn:graph')
explain_violations(content, graph_uri=None)[source]

Explains violations of the given integrity constraints.

Parameters
  • content (Content) – Data to check for violations

  • graph_uri (str, optional) – Named graph from which to check for validations

Returns

Integrity constraint violations

Return type

dict

Examples

>>> icv.explain_violations(File('constraints.ttl'),
                           graph_uri='urn:graph')
is_valid(content, graph_uri=None)[source]

Checks if given integrity constraints are valid.

Parameters
  • content (Content) – Data to check for validity

  • graph_uri (str, optional) – Named graph to check for validity

Returns

Integrity constraint validity

Return type

bool

Examples

>>> icv.is_valid(File('constraints.ttl'), graph_uri='urn:graph')
list()[source]

List all integrity constraints from the database.

remove(content)[source]

Removes integrity constraints from the database.

Parameters

content (Content) – Data to remove

Examples

>>> icv.remove(File('constraints.ttl'))

stardog.admin

Administer a Stardog server.

class stardog.admin.Admin(endpoint=None, username=None, password=None, auth=None)[source]

Bases: object

Admin Connection.

This is the entry point for admin-related operations on a Stardog server.

__init__(endpoint=None, username=None, password=None, auth=None)[source]

Initializes an admin connection to a Stardog server.

Parameters
  • endpoint (str, optional) – Url of the server endpoint. Defaults to http://localhost:5820

  • username (str, optional) – Username to use in the connection. Defaults to admin

  • password (str, optional) – Password to use in the connection. Defaults to admin

auth (requests.auth.AuthBase, optional): requests Authentication object.

Defaults to None

auth and username/password should not be used together. If the are the value of auth will take precedent. .. rubric:: Examples

>>> admin = Admin(endpoint='http://localhost:9999',
                  username='admin', password='admin')
alive()[source]

Determine whether the server is running :return: Returns True if server is alive :rtype: bool

backup_all(location=None)[source]

Create a backup of all databases on the server

cache(name)[source]

Retrieve an object representing a cached dataset.

Returns

The requested cache

Return type

Cache

cache_status(*names)[source]

Retrieves the status of one or more cached graphs or queries.

Parameters

*names – (str): Names of the cached graphs or queries

Returns

List of statuses

Return type

list[str]

cache_targets()[source]

Retrieves all cache targets.

Returns

A list of CacheTarget objects

Return type

list[CacheTarget]

cached_graphs()[source]

Retrieves all cached graphs.

Returns

A list of Cache objects

Return type

list[Cache]

cached_queries()[source]

Retrieves all cached queries.

Returns

A list of Cache objects

Return type

list[Cache]

clear_stored_queries()[source]

Remove all stored queries on the server.

cluster_coordinator_check()[source]

Determine if a specific cluster node is the cluster coordinator :return: True if the node is a coordinator, false if not. :rtype: Bool

cluster_info()[source]

Prints info about the nodes in the Stardog Pack cluster.

Returns

Nodes of the cluster

Return type

dict

cluster_join()[source]

Instruct a standby node to join its cluster as a full node

cluster_list_standby_nodes()[source]

List standby nodes :return: Returns the registry ID for the standby nodes. :rtype: dict

cluster_revoke_standby_access(registry_id)[source]

Instruct a standby node to stop syncing :param *registry_id: (string): Id of the standby node to stop syncing.

cluster_shutdown()[source]

Shutdown all nodes :return: True if the cluster got shutdown successfully. :rtype: bool

cluster_start_readonly()[source]

Start read only mode

cluster_status()[source]

Prints status information for each node in the cluster

Returns

Nodes of the cluster and extra information

Return type

dict

cluster_stop_readonly()[source]

Stops read only mode

database(name)[source]

Retrieves an object representing a database.

Parameters

name (str) – The database name

Returns

The requested database

Return type

Database

databases()[source]

Retrieves all databases.

Returns

A list of database objects

Return type

list[Database]

datasource(name)[source]

Retrieves an object representing a DataSource.

Parameters

name (str) – The name of the data source

Returns

The DataSource object

Return type

DataSource

datasources()[source]

Retrieves all data sources.

Returns

A list of DataSources

Return type

list[DataSources]

datasources_info()[source]

List data sources info

Returns

A list of data sources info

Return type

list

get_all_metadata_properties()[source]

Get information on all database metadata properties, including description and example values :return: Metadata properties :rtype: dict

get_prometheus_metrics()[source]
get_server_metrics()[source]

Return metric information from the registry in JSON format https://stardog-union.github.io/http-docs/#operation/status :return: Server metrics :rtype: dict

get_server_properties()[source]

Get the value of any set server-level properties

Returns

dict: Server properties

healthcheck()[source]

Determine whether the server is running and able to accept traffic :return: Returns true if server is able to accept traffic :rtype: bool

import_virtual_graph(db, mappings, named_graph, remove_all, options)[source]

Import (materialize) a virtual graph directly into the local knowledge graph.

Parameters

Examples

>>> admin.import_virtual_graph(
      'db-name', mappings=File('mappings.ttl'),
      named_graph='my-graph', remove_all=True, options={'jdbc.driver': 'com.mysql.jdbc.Driver'}
    )
kill_query(id)[source]

Kills a running query.

Parameters

id (str) – ID of the query to kill

new_cache_target(name, hostname, port, username, password, use_existing_db=False)[source]

Creates a new cache target.

Parameters
  • name (str) – The name of the cache target

  • hostname (str) – The hostname of the cache target server

  • port (int) – The port of the cache target server

  • username (int) – The username for the cache target

  • password (int) – The password for the cache target

  • use_existing_db (bool) – If true, check for an existing cache database to use before creating a new one

Returns

The new CacheTarget

Return type

CacheTarget

new_cached_graph(name, target, graph, database=None, refresh_script=None, register_only=False)[source]

Creates a new cached graph.

Parameters
  • name (str) – The name (URI) of the cached query

  • target (str) – The name (URI) of the cache target

  • graph (str) – The name of the graph to cache

  • database (str) – The name of the database. Optional for virtual graphs, mandatory for named graphs.

  • refresh_script (str) – An optional SPARQL Insert query to run when refreshing the cache.

  • register_only (bool) – An optional value that if true, register a cached dataset without loading data from the source graph or query into the cache target’s databases.

Returns

The new Cache

Return type

Cache

new_cached_query(name, target, query, database, refresh_script=None, register_only=False)[source]

Creates a new cached query.

Parameters
  • name (str) – The name (URI) of the cached query

  • target (str) – The name (URI) of the cache target

  • query (str) – The query to cache

  • database (str) – The name of the database

  • refresh_script (str, optional) – A SPARQL insert query to run when refreshing the cache

  • register_only (bool) – Default: false. If true, register a cached dataset without loading data from the source graph or query into the cache target’s databases

Returns

The new Cache

Return type

Cache

new_database(name, options=None, *contents, **kwargs)[source]

Creates a new database.

Parameters
  • name (str) – the database name

  • options (dict) – Dictionary with database options (optional)

  • *contents (Content or (Content, str), optional) – Datasets to perform bulk-load with. Named graphs are made with tuples of Content and the name.

  • **kwargs – Allows to set copy_to_server. If true, sends the files to the Stardog server, and replicates them to the rest of nodes.

Returns

The database object

Return type

Database

Examples

Options

>>> admin.new_database('db', {'search.enabled': True})

bulk-load

>>> admin.new_database('db', {},
                       File('example.ttl'), File('test.rdf'))

bulk-load to named graph

>>> admin.new_database('db', {}, (File('test.rdf'), 'urn:context'))
new_datasource(name, options)[source]

Creates a new DataSource.

Parameters
  • name (str) – The name of the data source

  • options (dict) – Data source options

Returns

The new DataSource object

Return type

User

new_role(name)[source]

Creates a new role.

Parameters

name (str) – The name of the new Role

Returns

The new Role object

Return type

Role

new_stored_query(name, query, options=None)[source]

Creates a new Stored Query.

Parameters
  • name (str) – The name of the stored query

  • query (str) – The query text

  • options (dict, optional) – Additional options

Returns

the new StoredQuery

Return type

StoredQuery

Examples

>>> admin.new_stored_query('all triples',
      'select * where { ?s ?p ?o . }',
      { 'database': 'mydb' }
    )
new_user(username, password, superuser=False)[source]

Creates a new user.

Parameters
  • username (str) – The username

  • password (str) – The password

  • superuser (bool) – Should the user be super? Defaults to false.

Returns

The new User object

Return type

User

new_virtual_graph(name, mappings, options=None, datasource=None, db=None)[source]

Creates a new Virtual Graph.

Parameters
  • name (str) – The name of the virtual graph.

  • mappings (Content) – New mapping contents.

  • options (dict, Optional) – Options for the new virtual graph. If not passed, then a datasource must be specified.

  • datasource (str, Optional) – Name of the datasource to use. If not passed, options with a datasource must be set.

  • db (str, Optional) – Name of the database to associate the VG. If not passed, will be associated to all databases.

Returns

the new VirtualGraph

Return type

VirtualGraph

Examples

>>> admin.new_virtual_graph(
      'users', File('mappings.ttl'),
      {'jdbc.driver': 'com.mysql.jdbc.Driver'}
    )
queries()[source]

Gets information about all running queries.

Returns

Query information

Return type

dict

query(id)[source]

Gets information about a running query.

Parameters

id (str) – Query ID

Returns

Query information

Return type

dict

restore(from_path, *, name=None, force=False)[source]

Restore a database.

Parameters
  • from_path (str) – the full path on the server to the backup

  • name (str, optional) – the name of the database to restore to if different from the backup

  • force (boolean, optional) – a backup will not be restored over an existing database of the same name; the force flag should be used to overwrite the database

Examples

>>> admin.restore("/data/stardog/.backup/db/2019-12-01")
>>> admin.restore("/data/stardog/.backup/db/2019-11-05",
                  name="db2", force=True)
role(name)[source]

Retrieves an object representing a role.

Parameters

name (str) – The name of the Role

Returns

The Role object

Return type

Role

roles()[source]

Retrieves all roles.

Returns

A list of Role objects

Return type

list[Role]

shutdown()[source]

Shuts down the server.

standby_node_pause(pause)[source]

Pause/Unpause standby node :param *pause: (boolean): True for pause, False for unpause

Returns

Returns True if the pause status was modified successfully, false if it failed.

Return type

bool

standby_node_pause_status()[source]

Get the pause status of a standby node https://stardog-union.github.io/http-docs/#operation/getPauseState :return: Pause status of a standby node, possible values are: “WAITING”, “SYNCING”, “PAUSING”, “PAUSED” :rtype: Dict

stored_queries()[source]

Retrieves all stored queries.

Returns

A list of StoredQuery objects

Return type

list[StoredQuery]

stored_query(name)[source]

Retrieves a Stored Query.

Parameters

name (str) – The name of the Stored Query to retrieve

Returns

The StoredQuery object

Return type

StoredQuery

user(name)[source]

Retrieves an object representing a user.

Parameters

name (str) – The name of the user

Returns

The User object

Return type

User

users()[source]

Retrieves all users.

Returns

A list of User objects

Return type

list[User]

validate()[source]

Validates an admin connection.

Returns

The connection state

Return type

bool

virtual_graph(name)[source]

Retrieves a Virtual Graph.

Parameters

name (str) – The name of the Virtual Graph to retrieve

Returns

The VirtualGraph object

Return type

VirtualGraph

virtual_graphs()[source]

Retrieves all virtual graphs.

Returns

A list of VirtualGraph objects

Return type

list[VirtualGraph]

class stardog.admin.Cache(name, client)[source]

Bases: object

Cached data

A cached dataset from a query or named/virtual graph.

__init__(name, client)[source]

Initializes a new cached dataset from a query or named/virtual graph.

Use stardog.admin.Admin.new_cached_graph() or stardog.admin.Admin.new_cached_query() instead of constructing manually.

drop()[source]

Drops the cache.

refresh()[source]

Refreshes the cache.

status()[source]

Retrieves the status of the cache.

class stardog.admin.CacheTarget(name, client)[source]

Bases: object

Cache Target Server

__init__(name, client)[source]

Initializes a cache target.

Use stardog.admin.Admin.new_cache_target() instead of constructing manually.

info()[source]

Get info for the cache target

Returns

Info

Return type

dict

property name

The name (URI) of the cache target.

orphan()[source]

Orphans the cache target but do not destroy its contents.

remove()[source]

Removes the cache target and destroy its contents.

class stardog.admin.DataSource(name, client)[source]

Bases: object

Initializes a DataSource

__init__(name, client)[source]

Initializes a DataSource.

Use stardog.admin.Admin.data_source(), stardog.admin.Admin.data_sources(), or stardog.admin.Admin.new_data_source() instead of constructing manually.

available()[source]

Checks if the data source is available.

Returns

Availability state

Return type

bool

delete()[source]

Deletes a data source

get_options()[source]

Get data source options

info()[source]

Get data source info

Returns

Info

Return type

dict

property name

The name of the data source.

online()[source]

Online a data source

refresh_count(meta=None)[source]

Refresh table row-count estimates

refresh_metadata(meta=None)[source]

Refresh metadata

share()[source]

Share data source

update(options=None)[source]

Update data source

class stardog.admin.Database(name, client)[source]

Bases: object

Database Admin

__init__(name, client)[source]

Initializes a Database.

Use stardog.admin.Admin.database(), stardog.admin.Admin.databases(), or stardog.admin.Admin.new_database() instead of constructing manually.

add_namespace(prefix, iri)[source]

Adds a specific namespace to a database :return: True if the operation succeeded. :rtype: Bool

backup(*, to=None)[source]

Create a backup of a database on the server.

Parameters

to (string, optional) – specify a path on the server to store the backup

copy(to)[source]

Makes a copy of this database under another name.

The database must be offline.

Parameters

to (str) – Name of the new database to be created

Returns

The new Database

Return type

Database

drop()[source]

Drops the database.

get_all_options()[source]

Get the value of every metadata option for a database

Returns

Dict detailing all database metadata

Return type

Dict

get_options(*options)[source]

Get the value of specific metadata options for a database

Parameters

*options (str) – Database option names

Returns

Database options

Return type

dict

Examples
>>> db.get_options('search.enabled', 'spatial.enabled')
import_namespaces(content)[source]
Parameters

content (Content) – RDF File containing prefix declarations Imports namespace prefixes from an RDF file that contains prefix declarations into the database, overriding any previous mappings for those prefixes. Only the prefix declarations in the file are processed, the rest of the file is not parsed.

Returns

Dictionary with all namespaces after import

Return type

Dict

property name

The name of the database.

namespaces()[source]

Retrieve the namespaces stored in the database https://stardog-union.github.io/http-docs/#operation/getNamespaces :return: A dict listing the prefixes and IRIs of the stored namespaces :rtype: Dict

offline()[source]

Sets a database to offline state.

online()[source]

Sets a database to online state.

optimize()[source]

Optimizes a database.

remove_namespace(prefix)[source]

Removes a specific namespace from a database :return: True if the operation succeeded. :rtype: Bool

repair()[source]

Attempt to recover a corrupted database.

The database must be offline.

set_options(options)[source]

Sets database options.

The database must be offline.

Parameters

options (dict) – Database options

Examples
>>> db.set_options({'spatial.enabled': False})
verify()[source]

verifies a database.

class stardog.admin.Role(name, client)[source]

Bases: object

__init__(name, client)[source]

Initializes a Role.

Use stardog.admin.Admin.role(), stardog.admin.Admin.roles(), or stardog.admin.Admin.new_role() instead of constructing manually.

add_permission(action, resource_type, resource)[source]

Adds a permission to the role.

Parameters
  • action (str) – Action type (e.g., ‘read’, ‘write’)

  • resource_type (str) – Resource type (e.g., ‘user’, ‘db’)

  • resource (str) – Target resource (e.g., ‘username’, ‘*’)

Examples

>>> role.add_permission('read', 'user', 'username')
>>> role.add_permission('write', '*', '*')
delete(force=None)[source]

Deletes the role.

Parameters

force (bool) – Force deletion of the role

property name

The name of the Role.

permissions()[source]

Gets the role permissions.

Returns

Role permissions

Return type

dict

remove_permission(action, resource_type, resource)[source]

Removes a permission from the role.

Parameters
  • action (str) – Action type (e.g., ‘read’, ‘write’)

  • resource_type (str) – Resource type (e.g., ‘user’, ‘db’)

  • resource (str) – Target resource (e.g., ‘username’, ‘*’)

Examples

>>> role.remove_permission('read', 'user', 'username')
>>> role.remove_permission('write', '*', '*')
users()[source]

Lists the users for this role.

Returns

list[User]

class stardog.admin.StoredQuery(name, client)[source]

Bases: object

Stored Query

__init__(name, client)[source]

Initializes a stored query.

Use stardog.admin.Admin.stored_query(), stardog.admin.Admin.stored_queries(), or stardog.admin.Admin.new_stored_query() instead of constructing manually.

property creator

The creator of the stored query.

property database

The database the stored query applies to.

delete()[source]

Deletes the Stored Query.

property description

The description of the stored query.

property name

The name of the stored query.

property query

The text of the stored query.

property reasoning

The value of the reasoning property.

property shared

The value of the shared property.

update(**options)[source]

Updates the Stored Query.

Parameters

**options (str) – Named arguments to update.

Examples

Update description

>>> stored_query.update(description='this query finds all the relevant...')
class stardog.admin.User(name, client)[source]

Bases: object

__init__(name, client)[source]

Initializes a User.

Use stardog.admin.Admin.user(), stardog.admin.Admin.users(), or stardog.admin.Admin.new_user() instead of constructing manually.

add_permission(action, resource_type, resource)[source]

Add a permission to the user.

Parameters
  • action (str) – Action type (e.g., ‘read’, ‘write’)

  • resource_type (str) – Resource type (e.g., ‘user’, ‘db’)

  • resource (str) – Target resource (e.g., ‘username’, ‘*’)

Examples
>>> user.add_permission('read', 'user', 'username')
>>> user.add_permission('write', '*', '*')
add_role(role)[source]

Adds an existing role to the user.

Parameters

role (str or Role) – The role to add or its name

Examples

>>> user.add_role('reader')
>>> user.add_role(admin.role('reader'))
delete()[source]

Deletes the user.

effective_permissions()[source]

Gets the user’s effective permissions.

Returns

User effective permissions

Return type

dict

is_enabled()[source]

Checks if the user is enabled.

Returns

User activation state

Return type

bool

is_superuser()[source]

Checks if the user is a super user.

Returns

Superuser state

Return type

bool

property name

The user name.

Type

str

permissions()[source]

Gets the user permissions.

Returns

User permissions

Return type

dict

remove_permission(action, resource_type, resource)[source]

Removes a permission from the user.

Parameters
  • action (str) – Action type (e.g., ‘read’, ‘write’)

  • resource_type (str) – Resource type (e.g., ‘user’, ‘db’)

  • resource (str) – Target resource (e.g., ‘username’, ‘*’)

Examples
>>> user.remove_permission('read', 'user', 'username')
>>> user.remove_permission('write', '*', '*')
remove_role(role)[source]

Removes a role from the user.

Parameters

role (str or Role) – The role to remove or its name

Examples
>>> user.remove_role('reader')
>>> user.remove_role(admin.role('reader'))
roles()[source]

Gets all the User’s roles.

Returns

list[Role]

set_enabled(enabled)[source]

Enables or disables the user.

Parameters

enabled (bool) – Desired User state

set_password(password)[source]

Sets a new password.

Parameters

password (str) –

set_roles(*roles)[source]

Sets the roles of the user.

Parameters

*roles (str or Role) – The roles to add the User to

Examples
>>> user.set_roles('reader', admin.role('writer'))
class stardog.admin.VirtualGraph(name, client)[source]

Bases: object

Virtual Graph

__init__(name, client)[source]

Initializes a virtual graph.

Use stardog.admin.Admin.virtual_graph(), stardog.admin.Admin.virtual_graphs(), or stardog.admin.Admin.new_virtual_graph() instead of constructing manually.

available()[source]

Checks if the Virtual Graph is available.

Returns

Availability state

Return type

bool

delete()[source]

Deletes the Virtual Graph.

get_database()[source]

Gets database associated with the VirtualGraph.

Returns

Database name

Return type

string

info()[source]

Gets Virtual Graph info.

Returns

Info

Return type

dict

mappings(content_type='text/turtle')[source]

Gets the Virtual Graph mappings (Deprecated, see mappings_string instead).

Parameters
  • content_type (str) – Content type for results.

  • 'text/turtle' (Defaults to) –

Returns

Mappings in given content type

Return type

bytes

mappings_string(syntax='STARDOG')[source]

Returns graph mappings as RDF :param syntax: The desired RDF syntax of the mappings (STARDOG, R2RML, or SMS2). :type syntax: str :param Defaults to ‘STARDOG’:

Returns

Mappings in given content type

Return type

string

property name

The name of the virtual graph.

options()[source]

Gets Virtual Graph options.

Returns

Options

Return type

dict

update(name, mappings, options={}, datasource=None, db=None)[source]

Updates the Virtual Graph.

Parameters
  • name (str) – The new name

  • mappings (Content) – New mapping contents

  • options (dict) – New options

Examples

>>> vg.update('users', File('mappings.ttl'),
             {'jdbc.driver': 'com.mysql.jdbc.Driver'})

stardog.content

Content that can be loaded into Stardog.

class stardog.content.Content[source]

Bases: object

Content base class.

class stardog.content.File(fname, content_type=None, content_encoding=None, name=None)[source]

Bases: stardog.content.Content

File-based content.

__init__(fname, content_type=None, content_encoding=None, name=None)[source]

Initializes a File object.

Parameters
  • fname (str) – Filename

  • content_type (str, optional) – Content type. It will be automatically detected from the filename

  • content_encoding (str, optional) – Content encoding. It will be automatically detected from the filename

  • name (str, optional) – Object name. It will be automatically detected from the filename

Examples

>>> File('data.ttl')
>>> File('data.doc', 'application/msword')
data()[source]
class stardog.content.Raw(content, content_type=None, content_encoding=None, name=None)[source]

Bases: stardog.content.Content

User-defined content.

__init__(content, content_type=None, content_encoding=None, name=None)[source]

Initializes a Raw object.

Parameters
  • content (obj) – Object representing the content (e.g., str, file)

  • content_type (str, optional) – Content type

  • content_encoding (str, optional) – Content encoding

  • name (str, optional) – Object name

Examples

>>> Raw(':luke a :Human', 'text/turtle', name='data.ttl')
>>> Raw(':βüãäoñr̈ a :Employee .'.encode('utf-8'), 'text/turtle')
data()[source]
class stardog.content.URL(url, content_type=None, content_encoding=None, name=None)[source]

Bases: stardog.content.Content

Url-based content.

__init__(url, content_type=None, content_encoding=None, name=None)[source]

Initializes a URL object.

Parameters
  • url (str) – Url

  • content_type (str, optional) – Content type. It will be automatically detected from the url

  • content_encoding (str, optional) – Content encoding. It will be automatically detected from the filename

  • name (str, optional) – Object name. It will be automatically detected from the url

Examples

>>> URL('http://example.com/data.ttl')
>>> URL('http://example.com/data.doc', 'application/msword')
data()[source]

stardog.exceptions

exception stardog.exceptions.StardogException[source]

Bases: Exception

General Stardog Exceptions

exception stardog.exceptions.TransactionException[source]

Bases: stardog.exceptions.StardogException

Transaction Exceptions