Modules
stardog.connection
Connect to Stardog databases.
- class stardog.connection.CommitResult(*args, **kwargs)[source]
Bases:
dictThe result of committing a transaction.
Represents the outcome of a transaction commit operation, including the counts of added and removed triples.
-
added:
int The amount of triples added in the transaction
-
removed:
int The amount of triples removed in the transaction
-
added:
- class stardog.connection.Connection(database, endpoint='http://localhost:5820', username='admin', password='admin', auth=None, session=None, run_as=None)[source]
Bases:
objectDatabase Connection.
This is the entry point for all user-related operations on a Stardog database
- __init__(database, endpoint='http://localhost:5820', username='admin', password='admin', auth=None, session=None, run_as=None)[source]
Initializes a connection to a Stardog database.
- Parameters:
database (
str) – Name of the databaseendpoint (
Optional[str], default:'http://localhost:5820') – URL of the Stardog server endpoint.username (
Optional[str], default:'admin') – Username to use in the connection.password (
Optional[str], default:'admin') – Password to use in the connection.auth (
Optional[AuthBase], default:None) –requests.auth.AuthBaseobject. Used as an alternative authentication scheme. If not provided, HTTP Basic auth will be attempted with theusernameandpassword.session (
Optional[Session], default:None) –requests.session.Sessionobjectrun_as (
Optional[str], default:None) – The user to impersonate.
Examples
>>> conn = Connection('db', endpoint='http://localhost:9999', username='admin', password='admin')
- add(content, graph_uri=None, server_side=False)[source]
Adds data to the database.
- Parameters:
content (
Union[Content,str]) – Data to add to a graph.graph_uri (
Optional[str], default:None) – Named graph into which to add the data. If no named graph is provided, the data will be loaded into the default graph.server_side (
bool, default:False) – Whether the file to load is located on the same file system as the Stardog server.
- Return type:
None- Raises:
stardog.exceptions.TransactionException – If currently not in a transaction
Examples
Loads
example.ttlfrom the current directory>>> conn.add(File('example.ttl'), graph_uri='urn:graph')
Loads
/tmp/example.ttlwhich exists on the same file system as the Stardog server, and loads it in the default graph.>>> conn.add(File('/tmp/example.ttl'), server_side=True)
- ask(query, base_uri=None, limit=None, offset=None, timeout=None, reasoning=None, bindings=None, default_graph_uri=None, named_graph_uri=None, **kwargs)[source]
Executes a SPARQL
ASKquery.- Parameters:
query (
str) – SPARQL querybase_uri (
Optional[str], default:None) – Base URI for the parsing of the querylimit (
Optional[int], default:None) – Maximum number of results to returnoffset (
Optional[int], default:None) – Offset into the result settimeout (
Optional[int], default:None) – Number of ms after which the query should timeout.0or less implies no timeoutreasoning (
Optional[bool], default:None) – Enable reasoning for the querybindings (
Optional[Dict[str,str]], default:None) – Map between query variables and their valuesdefault_graph_uri (
Optional[List[str]], default:None) – URI(s) to be used as the default graph (equivalent toFROM)named_graph_uri (
Optional[List[str]], default:None) – URI(s) to be used as named graphs (equivalent toFROM NAMED)
- Return type:
bool- Returns:
whether the query pattern has a solution or not
Examples:
ASKquery withreasoningenabled.pattern_exists = conn.ask('ask {:subj :pred :obj}', reasoning=True)
See also
- 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 (
Optional[str], default:None) – Named graph from which to remove data.- Return type:
None
Warning
If no
graph_uriis specified, the entire database will be cleared.- 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()
- commit()[source]
Commits the current transaction.
- Return type:
- Raises:
stardog.exceptions.TransactionException – If currently not in a transaction
- explain(query, base_uri=None)[source]
Explains the evaluation of a SPARQL query.
- Parameters:
query (
str) – the SPARQL query to explainbase_uri (
Optional[str], default:None) – base URI for the parsing of thequery
- Return type:
str- Returns:
Query explanation
- explain_inconsistency(graph_uri=None)[source]
Explains why the database or a named graph is inconsistent.
- Parameters:
graph_uri (
Optional[str], default:None) – the URI of the named graph for which to explain inconsistency- Return type:
dict- Returns:
explanation results
- explain_inference(content)[source]
Explains the given inference results.
- Parameters:
content (
Content) – data from which to provide explanations- Return type:
dict- Returns:
explanation results
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, default:'text/turtle') – RDF content type.stream (
bool, default:False) – Stream and chunk results?. See the note below for additional information.chunk_size (
int, default:10240) – Number of bytes to read per chunk when streaming.graph_uri (
Optional[str], default:None) – URI of the named graph to export
- Return type:
Union[str,Iterator[bytes]]
Note
If
stream=False(default), the contents of the database or named graph will be returned as astr. Ifstream=True, an iterable that yields chunks of content asbyteswill be returned.Examples
No streaming
>>> contents = conn.export()
Streaming
>>> with conn.export(stream=True) as stream: contents = ''.join(stream)
- graph(query, base_uri=None, limit=None, offset=None, timeout=None, reasoning=None, bindings=None, content_type='text/turtle', default_graph_uri=None, named_graph_uri=None, **kwargs)[source]
Executes a SPARQL graph (
CONSTRUCT) query.- Parameters:
query (
str) – SPARQL querybase_uri (
Optional[str], default:None) – Base URI for the parsing of the querylimit (
Optional[int], default:None) – Maximum number of results to returnoffset (
Optional[int], default:None) – Offset into the result settimeout (
Optional[int], default:None) – Number of ms after which the query should timeout.0or less implies no timeoutreasoning (
Optional[bool], default:None) – Enable reasoning for the querybindings (
Optional[Dict[str,str]], default:None) – Map between query variables and their valuescontent_type (default:
'text/turtle') – Content type for results.default_graph_uri (
Optional[List[str]], default:None) – URI(s) to be used as the default graph (equivalent toFROM)named_graph_uri (
Optional[List[str]], default:None) – URI(s) to be used as named graphs (equivalent toFROM NAMED)
- Return type:
bytes- Returns:
the query results
Examples:
SimpleCONSTRUCT(graph) query utilizinglimitandoffsetto restrict the result set withreasoningenabled.results = conn.graph('select * {?s ?p ?o}', offset=100, limit=100, reasoning=True )
CONSTRUCT(graph) query utilizingbindingsto bind the query variableoto a value of<urn:a>.results = conn.graph('select * {?s ?p ?o}', bindings={'o': '<urn:a>'})
- is_consistent(graph_uri=None)[source]
Checks if the database or named graph is consistent with respect to its schema.
- Parameters:
graph_uri (
Optional[str], default:None) – the URI of the graph to check- Return type:
bool- Returns:
database consistency state
- paths(query, base_uri=None, limit=None, offset=None, timeout=None, reasoning=None, bindings=None, content_type='application/sparql-results+json', default_graph_uri=None, named_graph_uri=None, **kwargs)[source]
Executes a SPARQL paths query.
- Parameters:
query (
str) – SPARQL querybase_uri (
Optional[str], default:None) – Base URI for the parsing of the querylimit (
Optional[int], default:None) – Maximum number of results to returnoffset (
Optional[int], default:None) – Offset into the result settimeout (
Optional[int], default:None) – Number of ms after which the query should timeout.0or less implies no timeoutreasoning (
Optional[bool], default:None) – Enable reasoning for the querybindings (
Optional[Dict[str,str]], default:None) – Map between query variables and their valuescontent_type (default:
'application/sparql-results+json') – Content type for results.default_graph_uri (
Optional[List[str]], default:None) – URI(s) to be used as the default graph (equivalent toFROM)named_graph_uri (
Optional[List[str]], default:None) – URI(s) to be used as named graphs (equivalent toFROM NAMED)
- Return type:
Union[Dict,bytes]- Returns:
If
content_type='application/sparql-results+json', results will be returned as a Dict , else results will be returned as bytes.
Examples:
SimplePATHSquery withreasoningenabled.results = conn.paths('paths start ?x = :subj end ?y = :obj via ?p', reasoning=True)
See also
- 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, base_uri=None, limit=None, offset=None, timeout=None, reasoning=None, bindings=None, content_type='application/sparql-results+json', default_graph_uri=None, named_graph_uri=None, **kwargs)[source]
Executes a SPARQL select query.
- Parameters:
query (
str) – SPARQL querybase_uri (
Optional[str], default:None) – Base URI for the parsing of the querylimit (
Optional[int], default:None) – Maximum number of results to returnoffset (
Optional[int], default:None) – Offset into the result settimeout (
Optional[int], default:None) – Number of ms after which the query should timeout.0or less implies no timeoutreasoning (
Optional[bool], default:None) – Enable reasoning for the querybindings (
Optional[Dict[str,str]], default:None) – Map between query variables and their valuescontent_type (
str, default:'application/sparql-results+json') – Content type for results.default_graph_uri (
Optional[List[str]], default:None) – URI(s) to be used as the default graph (equivalent toFROM)named_graph_uri (
Optional[List[str]], default:None) – URI(s) to be used as named graphs (equivalent toFROM NAMED)
- Return type:
Union[bytes,Dict]- Returns:
If
content_type='application/sparql-results+json', results will be returned as a Dict, else results will be returned as bytes.
Examples:
SimpleSELECTquery utilizinglimitandoffsetto restrict the result set withreasoningenabled.results = conn.select('select * {?s ?p ?o}', offset=100, limit=100, reasoning=True )
Query utilizingbindingsto bind the query variableoto a value of<urn:a>.results = conn.select('select * {?s ?p ?o}', bindings={'o': '<urn:a>'})
- size(exact=False)[source]
Calculate the size of the database.
- Parameters:
exact (
bool, default:False) – calculate the size of the database exactly. IfFalse(default), the size will be an estimate; this should take less time to calculate especially if the database is large.- Return type:
int- Returns:
the number of triples in the database
- update(query, base_uri=None, limit=None, offset=None, timeout=None, reasoning=None, bindings=None, using_graph_uri=None, using_named_graph_uri=None, remove_graph_uri=None, insert_graph_uri=None, **kwargs)[source]
Executes a SPARQL update query.
- Parameters:
query (
str) – SPARQL querybase_uri (
Optional[str], default:None) – Base URI for the parsing of the querylimit (
Optional[int], default:None) – Maximum number of results to returnoffset (
Optional[int], default:None) – Offset into the result settimeout (
Optional[int], default:None) – Number of ms after which the query should timeout.0or less implies no timeoutreasoning (
Optional[bool], default:None) – Enable reasoning for the querybindings (
Optional[Dict[str,str]], default:None) – Map between query variables and their valuesusing_graph_uri (
Optional[List[str]], default:None) – URI(s) to be used as the default graph (equivalent toUSING)using_named_graph_uri (
Optional[List[str]], default:None) – URI(s) to be used as named graphs (equivalent toUSING NAMED)remove_graph_uri (
Optional[str], default:None) – URI of the graph to be removed frominsert_graph_uri (
Optional[str], default:None) – URI of the graph to be inserted into
- Return type:
None
Examples
>>> conn.update('delete where {?s ?p ?o}')
- class stardog.connection.Docs(client)[source]
Bases:
objectBITES: Document Storage.
See also
- __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 documentcontent (
Content) – Contents of the document
- Return type:
None
Examples
>>> docs.add('example', File('example.pdf'))
- delete(name)[source]
Deletes a document from the store.
- Parameters:
name (
str) – Name of the document to delete- Return type:
None
- get(name, stream=False, chunk_size=10240)[source]
Gets a document from the store.
- Parameters:
name (
str) – Name of the documentstream (
bool, default:False) – If document should be streamed back as chunks of bytes or as one string .chunk_size (
int, default:10240) – Number of bytes to read per chunk when streaming.
- Return type:
Union[str,Iterator[bytes]]
Note
If
stream=False, the contents of the document will be returned as astr. Ifstream=True, an iterable that yields chunks of content asbyteswill be returned.Examples
No streaming
>>> contents = docs.get('example')
Streaming
>>> with docs.get('example', stream=True) as stream: contents = ''.join(stream)
- class stardog.connection.GraphQL(conn)[source]
Bases:
objectSee also
- __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 schemacontent (
Content) – Schema data
- Return type:
None
Examples
>>> gql.add_schema('people', content=File('people.graphql'))
- query(query, variables=None)[source]
Executes a GraphQL query.
- Parameters:
query (
str) – GraphQL queryvariables (
Optional[dict], default:None) – GraphQL variables. Keys:@reasoning(bool) to enable reasoning,@schema(str) to define schemas
- Return type:
dict- Returns:
Query results
Examples
with schema and reasoning
>>> gql.query('{ Person {name} }', variables={'@reasoning': True, '@schema': 'people'})
with named variables
>>> gql.query( 'query getPerson($id: Int) { Person(id: $id) {name} }', variables={'id': 1000})
- remove_schema(name)[source]
Removes a schema from the database.
- Parameters:
name (
str) – Name of the schema- Return type:
None
- class stardog.connection.ICV(conn)[source]
Bases:
objectIntegrity 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- Return type:
None
Warning
Deprecated:
stardog.connection.Connection.add()should be preferred.stardog.connection.ICV.add()will be removed in the next major version.Examples
>>> icv.add(File('constraints.ttl'))
- convert(content, graph_uri=None)[source]
Converts given integrity constraints to a SPARQL query.
- Parameters:
content (
Content) – Integrity constraints- Graph_uri:
Named graph from which to apply constraints
- Return type:
str- Returns:
SPARQL query
Warning
Deprecated:
stardog.connection.ICV.convert()was meant as a debugging tool, and will be removed in the next major version.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 containing constraints- Graph_uri:
Named graph from which to check for violations
- Return type:
Dict- Returns:
the violations
Warning
Deprecated:
stardog.connection.ICV.report()should be preferred.stardog.connection.ICV.explain_violations()will be removed in the next major version.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 validity (with respect to constraints) againstgraph_uri (
Optional[str], default:None) – URI of the named graph to check for validity
- Return type:
bool- Returns:
whether the data is valid with respect to the constraints
Examples
>>> icv.is_valid(File('constraints.ttl'), graph_uri='urn:graph')
- remove(content)[source]
Removes integrity constraints from the database.
- Parameters:
content (
Content) – Data to remove- Return type:
None
Warning
Deprecated:
stardog.connection.Connection.remove()should be preferred.stardog.connection.ICV.remove()will be removed in the next major version.Examples
>>> icv.remove(File('constraints.ttl'))
- report(**kwargs)[source]
Produces a SHACL validation report.
- Keyword Arguments:
shapes (str, optional) – SHACL shapes to validate
shacl.shape.graphs (str, optional) – SHACL shape graphs to validate
nodes (str, optional) – SHACL focus node(s) to validate
countLimit (str, optional) – Maximum number of violations to report
shacl.targetClass.simple (bool, optional) – If
True,sh:targetClasswill be evaluated based onrdf:typetriples only, without followingrdfs:subClassOfrelationsshacl.violation.limit.shape (str, optional) – number of violation limits per SHACL shapes
graph-uri (str, optional) – Named Graph
reasoning (bool, optional) – If
True, enable reasoning.
- Return type:
str- Returns:
SHACL validation report
Examples
>>> icv.report()
stardog.admin
Administer a Stardog server.
- class stardog.admin.Admin(endpoint='http://localhost:5820', username='admin', password='admin', auth=None, run_as=None)[source]
Bases:
objectAdmin Connection.
This is the entry point for admin-related operations on a Stardog server. .. seealso:: Stardog Docs - Operating Stardog
- __init__(endpoint='http://localhost:5820', username='admin', password='admin', auth=None, run_as=None)[source]
Initializes an admin connection to a Stardog server.
- Parameters:
endpoint (
Optional[str], default:'http://localhost:5820') – URL of the Stardog server endpoint.username (
Optional[str], default:'admin') – Username to use in the connection.password (
Optional[str], default:'admin') – Password to use in the connection.auth (
Optional[AuthBase], default:None) –requests.auth.AuthBaseobject. Used as an alternative authentication scheme. If not provided, HTTP Basic auth will be attempted with theusernameandpassword.run_as (
Optional[str], default:None) – the user to impersonate
Note
authandusername/passwordshould not be used together. If they are, the value ofauthwill take precedent.Examples
>>> admin = Admin(endpoint='http://localhost:9999', username='admin', password='admin')
- alive()[source]
Determine whether the server is running
- Return type:
bool- Returns:
is the server alive?
- backup_all(location=None)[source]
Create a backup of all databases on the server. This is also known as a server backup.
- Parameters:
location (
Optional[str], default:None) – where to write the server backup to on the Stardog server’s file system.
Note
By default, backups are stored in the
.backupdirectory in$STARDOG_HOME, but you can use thebackup.dirproperty in yourstardog.propertiesfile to specify a different location for backups or you can override it using thelocationparameter.
- cache(name)[source]
Retrieve an object representing a cached dataset.
- Parameters:
name (
str) – the name of the cache to retrieve- Return type:
- cache_status(*names)[source]
Retrieves the status of one or more cached graphs.
- Parameters:
names (
str) – Names of the cached graphs to retrieve status for- Return type:
List[Dict]- Returns:
list of statuses
- cache_targets()[source]
Retrieves all cache targets.
- Return type:
List[CacheTarget]
- cached_queries()[source]
Retrieves all cached queries.
Warning
This method is deprecated in Stardog 8+
- Return type:
List[Cache]- Returns:
cached queries
- cluster_coordinator_check()[source]
Determine if a specific cluster node is the cluster coordinator
- Return type:
bool- Returns:
whether the node is a coordinator or not.
- cluster_info()[source]
Prints info about the nodes in the Stardog cluster.
- Return type:
Dict- Returns:
information about nodes in the cluster
- cluster_join()[source]
Instruct a standby node to join its cluster as a full node
- Return type:
None
- cluster_list_standby_nodes()[source]
List standby nodes
- Return type:
Dict- Returns:
all standby nodes in the cluster
- cluster_revoke_standby_access(registry_id)[source]
Instruct a standby node to stop syncing
- Parameters:
registry_id (
str) – ID of the standby node.- Return type:
None
- cluster_shutdown()[source]
Shutdown all nodes in the cluster
- Return type:
bool- Returns:
whether the cluster was shutdown successfully or not.
- cluster_status()[source]
Prints status information for each node in the cluster
- Return type:
Dict- Returns:
status information about each node in the cluster
- database(name)[source]
Retrieves an object representing a database.
- Parameters:
name (
str) – The database name- Return type:
- Returns:
the database
- datasource(name)[source]
Retrieves an object representing a DataSource.
- Parameters:
name (
str) – The name of the data source- Return type:
- datasources()[source]
Retrieves all data sources.
- Return type:
List[DataSource]
- datasources_info()[source]
List all data sources with their details
- Return type:
List[Dict]- Returns:
a list of data sources with their details
- get_all_metadata_properties()[source]
Get information on all database metadata properties, including description and example values
- Return type:
Dict- Returns:
Metadata properties
- get_server_metrics()[source]
Returns metric information from the registry in JSON format
- Return type:
Dict- Returns:
Server metrics
See also
- get_server_properties()[source]
Get the value of any set server-level properties
- Return type:
Dict- Returns:
server properties
- healthcheck()[source]
Determine whether the server is running and able to accept traffic
- Return type:
bool- Returns:
is the server accepting traffic?
- import_file(db, mappings, input_file, options=None, named_graph=None)[source]
Import a JSON or CSV file.
- Parameters:
db (
str) – Name of the database to import the datamappings (
Union[MappingRaw,MappingFile]) – Mappings specifying how to import the data contained in the CSV/JSON.input_file (
Union[ImportFile,ImportRaw]) – the JSON or CSV file to importoptions (
Optional[Dict], default:None) – Options for the import.named_graph (
Optional[str], default:None) – The named graph to import the mapped CSV/JSON into.
- Return type:
bool- Returns:
was the import successful?
- import_virtual_graph(db, mappings, named_graph, remove_all, options)[source]
Import (materialize) a virtual graph directly into the Stardog database.
Warning
Deprecated:
stardog.admin.Admin.materialize_virtual_graph()should be preferred.- Parameters:
db (
str) – The database into which to import the graphmappings (
Union[MappingRaw,MappingFile,str]) – New mapping contents. An empty string can be passed for autogenerated mappings.named_graph (
str) – Name of the graph to import the virtual graph into.remove_all (
Optional[bool]) – Should the target named graph be cleared before importing?options (
Dict) – Options for the new virtual graph. See Stardog Docs - Virtual Graph Properties for all available options.
- Return type:
None
Examples:
Import a MySQL virtual graph into thedb-namedatabase using the mappings specified inmappings.ttl. The virtual graph will be imported into the named graphmy-graphand prior to the import will have its contents cleared.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- Return type:
None
- materialize_virtual_graph(db, mappings, data_source=None, options=None, named_graph='tag:stardog:api:context:default', remove_all=False)[source]
Import (materialize) a virtual graph directly into a database.
- Parameters:
db (
str) – The database into which to import the graphmappings (
Union[MappingFile,MappingRaw,str]) – New mapping contents. An empty string can be passed for autogenerated mappings.data_source (
Optional[str], default:None) – The datasource to load fromoptions (
Optional[Dict], default:None) –Options for the new virtual graph, See Stardog Docs - Virtual Graph Properties for all available options.
named_graph (
Optional[str], default:'tag:stardog:api:context:default') – Name of the graph into which import the virtual graph.remove_all (
bool, default:False) – Should the target named graph be cleared before importing?
Note
data_sourceoroptionsmust be provided.
- 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 targethostname (
str) – The hostname of the cache target serverport (
int) – The port of the cache target serverusername (
str) – The username for the cache targetpassword (
str) – The password for the cache targetuse_existing_db (
bool, default:False) – IfTrue, check for an existing cache database to use before creating a new one
- Return type:
- Returns:
the new 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 querytarget (
str) – The name (URI) of the cache targetgraph (
str) – The name of the graph to cachedatabase (
Optional[str], default:None) – The name of the database. Optional for virtual graphs, required for named graphs.refresh_script (
Optional[str], default:None) – An optional SPARQL update query to run when refreshing the cache.register_only (
bool, default:False) – An optional value that ifTrue, register a cached dataset without loading data from the source graph or query into the cache target’s databases.
- Return type:
- Returns:
The new Cache
- new_cached_query(name, target, query, database, refresh_script=None, register_only=False)[source]
Creates a new cached query.
Warning
This method is deprecated in Stardog 8+
- Parameters:
name (
str) – The name (URI) of the cached querytarget (
str) – The name (URI) of the cache targetquery (
str) – The query to cachedatabase (
str) – The name of the databaserefresh_script (
Optional[str], default:None) – A SPARQL insert query to run when refreshing the cacheregister_only (
bool, default:False) – IfTrue, register a cached dataset without loading data from the source graph or query into the cache target’s databases
- Return type:
- Returns:
the new Cache
- new_database(name, options=None, *contents, **kwargs)[source]
Creates a new database.
- Parameters:
- Keyword Arguments:
copy_to_server – . If
True, sends the files to the Stardog server; if running as a cluster, data will be replicated to all nodes in the cluster.- Return type:
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 sourceoptions (
Dict) – Data Source options
- Return type:
- Returns:
The new DataSource object
- new_role(name)[source]
Creates a new role.
- Parameters:
name (
str) – the name of the new role- Returns:
the new Role object
- new_stored_query(name, query, options=None)[source]
Creates a new Stored Query.
- Parameters:
name (
str) – the name of the stored queryquery (
str) – the query to storeoptions (
Optional[Dict], default:None) – Additional options (e.g.{"shared": True, "database": "myDb" })
- Return type:
- Returns:
the new StoredQuery object
Examples:
Create a new stored query namedall triplesand make it only executable against the databasemydb.new_stored_query = 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 usernamepassword (
str) – The passwordsuperuser (
bool, default:False) – Create the user as a superuser. Only superusers can make other superusers.
- Return type:
- Returns:
The new User object
- new_virtual_graph(name, mappings=None, options=None, datasource=None, db=None)[source]
Creates a new Virtual Graph.
- Parameters:
name (
str) – The name of the virtual graph.mappings (
Union[MappingFile,MappingRaw,None], default:None) – New mapping contents. IfNoneprovided, mappings will be autogenerated.options (
Optional[Dict], default:None) – Options for the new virtual graph. IfNoneprovided, then adatasourcemust be specified.datasource (
Optional[str], default:None) – Name of the datasource to use. IfNoneprovided,optionswith adatasourcekey must be set.db (
Optional[str], default:None) – Name of the database to associate the virtual graph. IfNoneprovided, the virtual graph will be associated with all databases.
- Return type:
- Returns:
the new VirtualGraph
Examples:
Create a new virtual graph namedusersand associate it with all databases. The SMS2 mappings are provided in themappings.ttlfile.new_vg = admin.new_virtual_graph( name='users', mappings=MappingFile('mappings.ttl','SMS2'), datasource='my_datasource' )
- queries()[source]
Gets information about all running queries.
- Return type:
Dict- Returns:
information about all running queries
- query(id)[source]
Gets information about a running query.
- Parameters:
id (
str) – Query ID- Return type:
Dict- Returns:
Query information
- restore(from_path, *, name=None, force=False)[source]
Restore a database.
- Parameters:
from_path (
str) – the full path on the server’s file system to the backupname (
Optional[str], default:None) – the name of the database to restore to if different from the backupforce (
Optional[bool], default:False) – by default, a backup will not be restored in place of an existing database of the same name; theforceparameter should be used to overwrite the database
- Return type:
None
Examples:
simple restoreadmin.restore("/data/stardog/.backup/db/2019-12-01")
restore the backup and overwritedb2databaseadmin.restore("/data/stardog/.backup/db/2019-11-05", name="db2", force=True)
- standby_node_pause(pause)[source]
Pause/Unpause standby node
- Parameters:
pause (
bool) –Trueshould be provided to pause the standby node.Falseshould be provided to unpause.- Return type:
bool- Returns:
whether the pause status was successfully changed or not.
- standby_node_pause_status()[source]
Get the pause status of a standby node
- Return type:
Dict- Returns:
Pause status of a standby node, possible values are:
WAITING,SYNCING,PAUSING,PAUSED
- stored_queries()[source]
Retrieves all stored queries.
- Return type:
List[StoredQuery]
- stored_query(name)[source]
Retrieves a Stored Query.
- Parameters:
name (
str) – The name of the stored query to retrieve- Return type:
- user(name)[source]
Retrieves a User object.
- Parameters:
name (
str) – The name of the user- Return type:
- validate()[source]
Validates an admin connection.
- Return type:
bool- Returns:
whether the connection is valid or not
- virtual_graph(name)[source]
Retrieves a Virtual Graph.
- Parameters:
name (
str) – The name of the virtual graph to retrieve- Return type:
- virtual_graphs()[source]
Retrieves all virtual graphs.
- Return type:
List[VirtualGraph]
- class stardog.admin.Cache(name, client)[source]
Bases:
objectCached data
A cached dataset from a query or named/virtual graph.
See also
- __init__(name, client)[source]
Initializes a new cached dataset from a query or named/virtual graph.
Use
stardog.admin.Admin.new_cached_graph()orstardog.admin.Admin.new_cached_query()instead of constructing manually.
- class stardog.admin.CacheTarget(name, client)[source]
Bases:
objectCache Target Server
- __init__(name, client)[source]
Initializes a cache target.
Use
stardog.admin.Admin.new_cache_target()instead of constructing manually.
- property name
The name (URI) of the cache target.
- class stardog.admin.DataSource(name, client)[source]
Bases:
objectInitializes a DataSource
See also
- __init__(name, client)[source]
Initializes a DataSource.
Use
stardog.admin.Admin.data_source(),stardog.admin.Admin.data_sources(), orstardog.admin.Admin.new_data_source()instead of constructing manually.
- available()[source]
Checks if the data source is available.
- Return type:
bool- Returns:
whether the data source is available or not
- property name: str
The name of the data source.
- refresh_count(meta=None)[source]
Refresh table row-count estimates
- Parameters:
meta (
Optional[Dict], default:None) – dict containing the table to refresh. Examples:{"name": "catalog.schema.table"},{"name": "schema.table"},{"name": "table"}- Return type:
None
- refresh_metadata(meta=None)[source]
Refresh metadata for one or all tables that are accessible to a data source. Will clear the saved metadata for a data source and reload all of its dependent virtual graphs with fresh metadata.
- Parameters:
meta (
Optional[Dict], default:None) – dict containing the table to refresh. Examples:{"name": "catalog.schema.table"},{"name": "schema.table"},{"name": "table"}- Return type:
None
Share a private data source. When a virtual graph is created without specifying a data source name, a private data source is created for that, and only that virtual graph. This methods makes the data source available to other virtual graphs, as well as decouples the data source life cycle from the original virtual graph.
- Return type:
None
- update(options=None, force=False)[source]
Update data source
- Parameters:
options (
Optional[Dict], default:None) – Dict with data source optionsforce (
bool, default:False) – a data source will not be updated while in use unlessforce=True
- Return type:
None
Examples
>>> admin.update({"sql.dialect": "MYSQL"}) >>> admin.update({"sql.dialect": "MYSQL"}, force=True)
See also
- class stardog.admin.Database(name, client)[source]
Bases:
objectRepresents a Stardog database.
- __init__(name, client)[source]
Initializes a Database.
Use
stardog.admin.Admin.database(),stardog.admin.Admin.databases(), orstardog.admin.Admin.new_database()instead of constructing manually.
- add_namespace(prefix, iri)[source]
Adds a specific namespace to a database
- Parameters:
prefix (
str) – the prefix of the namespace to be addediri (
str) – the iri associated with theprefixto be added
- Return type:
bool- Returns:
whether the operation succeeded or not.
- backup(*, to=None)[source]
Create a backup of a database on the server.
- Parameters:
to (
Optional[str], default:None) – specify a path on the Stardog server’s file system to store the backup- Return type:
None
See also
- copy(to)[source]
Makes a copy of this database under another name.
Warning
This method is deprecated and not valid for Stardog versions 6+.
The database must be offline.
- Parameters:
to (str) – Name of the new database to be created
- Returns:
The new Database
- Return type:
- get_all_options()[source]
Get the value of every metadata option for a database
- Return type:
Dict- Returns:
All database metadata
- get_options(*options)[source]
Get the value of specific metadata options for a database
- Parameters:
options (
str) – Database option names- Return type:
Dict- Returns:
Database options
- Examples
>>> db.get_options('search.enabled', 'spatial.enabled')
- import_namespaces(content)[source]
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.
- Parameters:
content (
Content) – RDF File containing prefix declarations- Return type:
Dict- Returns:
Dictionary with all namespaces after import
- property name: str
The name of the database.
- namespaces()[source]
Retrieve the namespaces stored in the database
- Return type:
Dict- Returns:
A dict listing the prefixes and IRIs of the stored namespaces
See also
- remove_namespace(prefix)[source]
Removes a specific namespace from a database
- Parameters:
prefix (
str) – the prefix of the namespace to be removed- Return type:
bool- Returns:
whether the operation succeeded or not.
- repair()[source]
Attempt to recover a corrupted database.
Note
The database must be offline.
- Return type:
bool- Returns:
whether the database was successfully repaired or not
- class stardog.admin.Role(name, client)[source]
Bases:
objectSee also
- __init__(name, client)[source]
Initializes a Role.
Use
stardog.admin.Admin.role(),stardog.admin.Admin.roles(), orstardog.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', '*', '*')
- property name
The name of the Role.
- permissions()[source]
Gets the role permissions.
See also
- Returns:
Role permissions
- Return type:
dict
- remove_permission(action, resource_type, resource)[source]
Removes a permission from the role.
See also
- 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', '*', '*')
- class stardog.admin.StoredQuery(name, client, details=None)[source]
Bases:
objectStored Query
See also
- __init__(name, client, details=None)[source]
Initializes a stored query.
Use
stardog.admin.Admin.stored_query(),stardog.admin.Admin.stored_queries(), orstardog.admin.Admin.new_stored_query()instead of constructing manually.
- property creator: str
The creator of the stored query.
- property database: str
The database the stored query applies to.
- property description: str
The description of the stored query.
- property name: str
The name of the stored query.
- property query: str
The text of the stored query.
- property reasoning: bool
The value of the reasoning property.
The value of the shared property.
- class stardog.admin.User(name, client)[source]
Bases:
objectRepresents a Stardog user
- __init__(name, client)[source]
Initializes a User.
Use
stardog.admin.Admin.user(),stardog.admin.Admin.users(), orstardog.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,*)
- Return type:
None
- Examples
>>> user.add_permission('read', 'user', 'username') >>> user.add_permission('write', '*', '*')
- add_role(role)[source]
Adds an existing role to the user.
- Parameters:
role (
Union[Role,str]) – Thestardog.admin.Roleor name of the role to add- Return type:
None
Examples
>>> user.add_role('reader') >>> user.add_role(admin.role('reader'))
- effective_permissions()[source]
Gets the user’s effective permissions.
- Return type:
Dict- Returns:
User’s effective permissions
- is_enabled()[source]
Checks if the user is enabled.
- Return type:
bool- Returns:
whether the user is enabled or not
- is_superuser()[source]
Checks if the user is a superuser.
- Return type:
bool- Returns:
whether the user is a superuser or not.
- property name: str
The username.
- permissions()[source]
Gets the user permissions.
See also
- Return type:
Dict- Returns:
user permissions
- 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,*)
See also
Examples
>>> user.remove_permission('read', 'user', 'username') >>> user.remove_permission('write', '*', '*')
- remove_role(role)[source]
Removes a role from the user.
- Parameters:
role (
Union[str,Role]) – Thestardog.admin.Roleor name of the role to remove- Return type:
None
- Examples
>>> user.remove_role('reader') >>> user.remove_role(admin.role('reader'))
- set_enabled(enabled)[source]
Enables or disables the user.
- Parameters:
enabled (
bool) – Desired state.Truefor enabled,Falsefor disabled.- Return type:
None
- set_password(password)[source]
Sets a new password.
- Parameters:
password (
str) – the new password for the user- Return type:
None
- set_roles(*roles)[source]
Sets the roles of the user.
- Parameters:
roles (
Union[str,Role]) – Thestardog.admin.Role(s) or name of the role(s) to add to the user- Return type:
None
- Examples
>>> user.set_roles('reader', admin.role('writer'))
- class stardog.admin.VirtualGraph(name, client)[source]
Bases:
objectVirtual Graph
See also
- __init__(name, client)[source]
Initializes a virtual graph.
Use
stardog.admin.Admin.virtual_graph(),stardog.admin.Admin.virtual_graphs(), orstardog.admin.Admin.new_virtual_graph()instead of constructing manually.
- available()[source]
Checks if the virtual graph is available.
- Return type:
bool- Returns:
whether the virtual graph is available or not
- get_database()[source]
Gets database associated with the virtual graph.
- Return type:
str- Returns:
the database name
- get_datasource()[source]
Gets datasource associated with the virtual graph
- Return type:
str- Returns:
datasource name with
data-source://prefix removed
- mappings(content_type='text/turtle')[source]
Gets the Virtual Graph mappings
Warning
Deprecated:
stardog.admin.VirtualGraph.mappings_string()should be preferred.- Parameters:
content_type (
str, default:'text/turtle') – Content type for mappings.- Return type:
bytes- Returns:
Mappings in given content type
- mappings_string(syntax='SMS')[source]
Returns graph mappings from virtual graph
- Parameters:
syntax (
str, default:'SMS') – The desired syntax of the mappings ('STARDOG','R2RML', or'SMS2').- Returns:
Mappings in desired
syntax
- property name: str
The name of the virtual graph.
- update(name, mappings, options={}, datasource=None, db=None)[source]
Updates the Virtual Graph.
- Parameters:
name (
str) – The new namemappings (
Content) – New mapping contentsoptions (
Dict, default:{}) – New virtual graph optionsdatasource (
Optional[str], default:None) – new data source for the virtual graphdb (
Optional[str], default:None) – the database to associate with the virtual graph
- Return type:
None
Examples:
vg.update( name='users', mappings=File('mappings.ttl'), options={'jdbc.driver': 'com.mysql.jdbc.Driver'} )
stardog.content
Content that can be loaded into Stardog.
- class stardog.content.File(file=None, content_type=None, content_encoding=None, name=None, fname=None)[source]
Bases:
ContentFile-based content.
- __init__(file=None, content_type=None, content_encoding=None, name=None, fname=None)[source]
Initializes a File object.
- Parameters:
file (
Optional[str], default:None) – the filename/path of the filecontent_type (
Optional[str], default:None) – Content type. It will be automatically detected from the filenamecontent_encoding (
Optional[str], default:None) – Content encoding. It will be automatically detected from the filenamename (
Optional[str], default:None) – Name of the file object. It will be automatically detected from the filenamefname (
Optional[str], default:None) – backward compatible parameter forfile
Examples
>>> File('data.ttl') >>> File('data.doc', 'application/msword')
- class stardog.content.ImportFile(file, input_type=None, content_type=None, content_encoding=None, separator=None, name=None, iri=None)[source]
Bases:
ContentFile-based content for Delimited and JSON file.
- __init__(file, input_type=None, content_type=None, content_encoding=None, separator=None, name=None, iri=None)[source]
Initializes a File object.
- Parameters:
file (
str) – filename/path of the fileinput_type (
Optional[str], default:None) –'DELIMITED'or'JSON'content_type (
Optional[str], default:None) – Content typecontent_encoding (
Optional[str], default:None) – Content encodingseparator (
Optional[str], default:None) – Required ifinput_typeis'DELIMITED'. Use','for a CSV. Use\\tfor a TSV.name (
Optional[str], default:None) – Object name. It will be automatically detected from thefileif omitted.iri (
Optional[str], default:None) – IRI that uniquely identifies this file. It will default to “file://name” if omitted.
Note
If
filehas a recognized extension (i.e.'data.csv','data.tsv', or'data.json'), it will auto-detect most required parameters (input_type,separator,content_type,content_encoding) - otherwise you must specify them.Examples
>>> ImportFile('data.csv') >>> ImportFile('data.tsv') >>> ImportFile('data.txt','DELIMITED',"\\t" ) >>> ImportFile('data.json')
- class stardog.content.ImportRaw(content, input_type=None, separator=None, content_type=None, content_encoding=None, name=None, iri=None)[source]
Bases:
ContentUser-defined content.
- __init__(content, input_type=None, separator=None, content_type=None, content_encoding=None, name=None, iri=None)[source]
Initializes a Raw object.
- Parameters:
content (
object) – Object representing the content (e.g., str, file)input_type (
Optional[str], default:None) –'DELIMITED'or'JSON'separator (
Optional[str], default:None) – Required ifinput_typeis'DELIMITED'. Use','for a CSV. Use\\tfor a TSV.content_type (
Optional[str], default:None) – Content typecontent_encoding (
Optional[str], default:None) – Content encodingname (
Optional[str], default:None) – Object nameiri (
Optional[str], default:None) – IRI that uniquely identifies this content. It will default to “file://name” if omitted.
Note
if
nameis provided like a pseudo filename (i.e.'data.csv','data.tsv', or'data.json'), it will auto-detect most required parameters (input_type,separator,content_type,content_encoding) - otherwise you must specify them.Examples
>>> ImportRaw('a,b,c', name='data.csv') >>> ImportRaw('a b c', name='data.tsv') >>> ImportRaw({'foo':'bar'}, name='data.json')
- class stardog.content.MappingFile(file, syntax=None, name=None)[source]
Bases:
ContentFile-based content.
- __init__(file, syntax=None, name=None)[source]
Initializes a File object.
- Parameters:
file (
str) – the filename/path of the filesyntax (
Optional[str], default:None) – The mapping syntax ('STARDOG','R2RML', or'SMS2') If not provided, it will try to detect it from thefile’s extension.name (
Optional[str], default:None) – the name of the object. If not provided, will fall back to the basename of thefile.
Examples
>>> MappingFile('data.sms') >>> MappingFile('data.sms2') >>> MappingFile('data.rq') >>> MappingFile('data.r2rml')
- class stardog.content.MappingRaw(content, syntax=None, name=None)[source]
Bases:
ContentUser-defined Mapping.
- __init__(content, syntax=None, name=None)[source]
Initializes a MappingRaw object.
- Parameters:
content (
str) – the actual mapping content (e.g.'MAPPING\n FROM SQL ...')syntax (
Optional[str], default:None) – The mapping syntax ('STARDOG','R2RML', or'SMS2') If not provided, it will try to detect it fromnameif provided, otherwise from the content itselfname (
Optional[str], default:None) – name of object
Examples
>>> mapping = ''' MAPPING FROM SQL { SELECT * FROM `benchmark`.`person` } TO { ?subject rdf:type :person } WHERE { BIND(template("http://api.stardog.com/person/nr={nr}") AS ?subject) } ''' >>> MappingRaw(mapping)
- class stardog.content.Raw(content, content_type=None, content_encoding=None, name=None)[source]
Bases:
ContentUser-defined content.
- __init__(content, content_type=None, content_encoding=None, name=None)[source]
Initializes a Raw object.
- Parameters:
content (
object) – Object representing the content (e.g., str, file)content_type (
Optional[str], default:None) – Content typecontent_encoding (
Optional[str], default:None) – Content encodingname (
Optional[str], default:None) – Object name
Examples
>>> Raw(':luke a :Human', 'text/turtle', name='data.ttl') >>> Raw(':βüãäoñr̈ a :Employee .'.encode('utf-8'), 'text/turtle')
- class stardog.content.URL(url, content_type=None, content_encoding=None, name=None)[source]
Bases:
ContentUrl-based content.
- __init__(url, content_type=None, content_encoding=None, name=None)[source]
Initializes a URL object.
- Parameters:
url (
str) – URL to the contentcontent_type (
Optional[str], default:None) – Content type. It will be automatically detected from theurlif not provided.content_encoding (
Optional[str], default:None) – Content encoding. It will be automatically detected from theurlif not provided.name (
Optional[str], default:None) – Object name. It will be automatically detected from theurlif not provided.
Examples
>>> URL('http://example.com/data.ttl') >>> URL('http://example.com/data.doc', 'application/msword')
stardog.results
Module for working with query results.
- class stardog.results.BindingSet(bindings)[source]
Bases:
UserDictRepresents a single result row (solution) from a SPARQL SELECT query.
A
BindingSetencapsulates a set of variable bindings, where each binding associates a variable name with an RDF term (URI, literal, or blank node). It provides a convenient interface for accessing these bindings, supporting both attribute-style and dictionary-style access.Note
You typically shouldn’t instantiate the
BindingSetclass directly. Instead, it is meant to be used as part of aSelectQueryResultobject, which handles the conversion of SPARQL query results intoBindingSetinstances. To access the result bindings, use theSelectQueryResultclass, which provides a more convenient interface for handling SPARQL SELECT query results.Note
The typical accessors (e.g.,
binding_set.sorbinding_set['s']) return the convertedrdflibequivalents, such asrdflib.term.URIRef,rdflib.term.BNode, orrdflib.term.Literal. These converted objects can be used within therdflibecosystem for further manipulation or queries.If you need access to the raw RDF term exactly as it appears in the original SPARQL results JSON (before conversion), you can use the
get_rawmethod. This allows you to retrieve the JSON representation of the RDF term, which includes details like type and value.Access bindings using attribute-style access>>> results = SelectQueryResult(conn.select('select * {?s ?p ?o} limit 10')) >>> for binding_set in results: ... print(f"Subject: {binding_set.s}") ... Subject: http://stardog.com/tutorial/Album Subject: http://stardog.com/tutorial/artist
Access bindings using dictionary-style access>>> results = SelectQueryResult(conn.select('select * {?s ?p ?o} limit 10')) >>> first_result = results[0] >>> print(f"Subject: {first_result['s']}") Subject: http://stardog.com/tutorial/Album >>> print(f"Predicate: {first_result['p']}") Predicate: http://www.w3.org/1999/02/22-rdf-syntax-ns#type
- get_raw(key, default_value=None)[source]
Returns the raw, unconverted value for the variable binding, or a default if the key is not found.
- property raw: Dict[str, RDFTerm]
Returns a deep copy of the raw bindings from the actual SPARQL query JSON results.
- to_list()[source]
Converts the binding set to a list of converted rdflib equivalents.
- Return type:
List[Union[URIRef,BNode,Literal]]
- property variable_names: List[str]
Returns the variable names in this binding set.
- class stardog.results.RDFTerm(*args, **kwargs)[source]
Bases:
dictAn RDF term as its encoded in JSON in SPARQL JSON Query Results.
-
datatype:
Optional[str] The datatype of the literal. Not strictly required for literals.
-
lang:
Optional[str] The language tag of the literal. Not strictly required for literals.
-
type:
Literal['bnode','uri','literal'] The type of RDF term encoded in this dict
-
value:
str The value of the RDF term. For URIs, this is the URI itself; for literals, this is the value of the literal; for bnodes, this is the blank node identifier.
-
datatype:
- class stardog.results.SPARQLQueryResults(*args, **kwargs)[source]
Bases:
dictThe
resultsmember of the SPARQL JSON Query results
- class stardog.results.SPARQLQueryResultsHead(*args, **kwargs)[source]
Bases:
dictThe
headmember of the SPARQL JSON Query results-
vars:
List[str] List of variable names in the result
-
vars:
- class stardog.results.SPARQLQueryResultsJSON(*args, **kwargs)[source]
Bases:
dictRepresents the SPARQL Query results JSON format
-
head:
SPARQLQueryResultsHead Contains the variables projected in the select query results
-
results:
SPARQLQueryResults Contains the solution(s) to the query.
-
head:
- class stardog.results.SelectQueryResult(results)[source]
Bases:
SequenceA specialized sequence-like container for SPARQL SELECT query results.
This class encapsulates the results returned from a SPARQL SELECT query in JSON format, providing a convenient interface for accessing and manipulating the query results. It implements the Sequence protocol, allowing for indexed access, iteration, and length operations.
Iterate over result bindings>>> results = SelectQueryResult(conn.select('select * {?s ?p ?o} limit 10')) >>> for binding_set in results: ... print(f"Type: {type(binding_set.s)} - {binding_set.s}") ... Type: <class 'rdflib.term.URIRef'> - http://stardog.com/tutorial/%22Heroes%22_(David_Bowie_album) Type: <class 'rdflib.term.URIRef'> - http://stardog.com/tutorial/artist Type: <class 'rdflib.term.URIRef'> - http://stardog.com/tutorial/date Type: <class 'rdflib.term.URIRef'> - http://stardog.com/tutorial/track Type: <class 'rdflib.term.URIRef'> - http://stardog.com/tutorial/(Miss)understood Type: <class 'rdflib.term.URIRef'> - http://stardog.com/tutorial/+_(Ed_Sheeran_album) Type: <class 'rdflib.term.URIRef'> - http://stardog.com/tutorial/...And_Justice_for_All_(album) Type: <class 'rdflib.term.URIRef'> - http://stardog.com/tutorial/...And_Then_There_Were_Three... Type: <class 'rdflib.term.URIRef'> - http://stardog.com/tutorial/...Baby_One_More_Time_(album) Type: <class 'rdflib.term.URIRef'> - http://stardog.com/tutorial/...But_Seriously
String representation ofSelectQueryResultinstance will show you an overview/preview of the result bindings.>>> results = SelectQueryResult(conn.select('select * {?s ?p ?o} limit 10')) >>> print(results) SelectQueryResult with 10 results Variables: s, p, o Preview of the first 3 results: ?s = http://stardog.com/tutorial/%22Heroes%22_(David_Bowie_album), ?p = http://www.w3.org/1999/02/22-rdf-syntax-ns#type, ?o = http://stardog.com/tutorial/Album ?s = http://stardog.com/tutorial/artist, ?p = http://www.w3.org/2000/01/rdf-schema#domain, ?o = http://stardog.com/tutorial/Album ?s = http://stardog.com/tutorial/date, ?p = http://www.w3.org/2000/01/rdf-schema#domain, ?o = http://stardog.com/tutorial/Album ...and 7 more rows.
- property bindings: List[BindingSet]
The binding sets represents a solution to the query.
- property is_empty: bool
Whether there is one or more solution to the query or not.
- property raw: SPARQLQueryResults
Returns a deep copy of the underlying dict containing the raw SPARQL query results.
- property variable_names: List[str]
The variables projected in the query.
stardog.exceptions
- exception stardog.exceptions.StardogException(message, http_code=None, stardog_code=None)[source]
Bases:
ExceptionGeneral Stardog Exceptions
- exception stardog.exceptions.TransactionException(message, http_code=None, stardog_code=None)[source]
Bases:
StardogExceptionTransaction Exceptions