rdflib.plugins.stores package — rdflib 7.1.4 documentation (original) (raw)
Submodules¶
rdflib.plugins.stores.auditable module¶
This wrapper intercepts calls through the store interface and implements thread-safe logging of destructive operations (adds / removes) in reverse. This is persisted on the store instance and the reverse operations are executed In order to return the store to the state it was when the transaction began Since the reverse operations are persisted on the store, the store itself acts as a transaction.
Calls to commit or rollback, flush the list of reverse operations This provides thread-safe atomicity and isolation (assuming concurrent operations occur with different store instances), but no durability (transactions are persisted in memory and won’t be available to reverse operations after the system fails): A and I out of ACID.
class rdflib.plugins.stores.auditable.AuditableStore(store)[source]¶
Bases: Store
Parameters:
store (Store) –
identifier: URIRef of the Store. Defaults to CWD configuration: string containing information open can use to connect to datastore.
Parameters:
store (Store) –
__len__(context=None)[source]¶
Number of statements in the store. This should only account for non- quoted (asserted) statements if the context is not specified, otherwise it should return the number of statements in the formula or context given.
Parameters:
context (Optional[Graph]) – a graph instance to query or None
__module__ = 'rdflib.plugins.stores.auditable'¶
add(triple, context, quoted=False)[source]¶
Adds the given statement to a specific context or to the model. The quoted argument is interpreted by formula-aware stores to indicate this statement is quoted/hypothetical It should be an error to not specify a context and have the quoted argument be True. It should also be an error for the quoted argument to be True when the store is not formula-aware.
Parameters:
Return type:
bind(prefix, namespace, override=True)[source]¶
Parameters:
- override (bool) – rebind, even if the given namespace is already bound to another prefix.
- prefix (str) –
- namespace (URIRef) –
Return type:
close(commit_pending_transaction=False)[source]¶
This closes the database connection. The commit_pending_transaction parameter specifies whether to commit all pending transactions before closing (if the store is transactional).
Parameters:
commit_pending_transaction (bool) –
Return type:
Return type:
contexts(triple=None)[source]¶
Generator over all contexts in the graph. If triple is specified, a generator over all contexts the triple is in.
if store is graph_aware, may also return empty contexts
Return type:
Returns:
a generator over Nodes
Parameters:
triple (Optional[Tuple[Node, Node, Node]]) –
destroy(configuration)[source]¶
This destroys the instance of the store identified by the configuration string.
Parameters:
configuration (str) –
Return type:
Parameters:
prefix (str) –
Return type:
Return type:
open(configuration, create=True)[source]¶
Opens the store specified by the configuration string. If create is True a store will be created if it does not already exist. If create is False and a store does not already exist an exception is raised. An exception is also raised if a store exists, but there is insufficient permissions to open the store. This should return one of: VALID_STORE, CORRUPTED_STORE, or NO_STORE
Parameters:
Return type:
Parameters:
namespace (URIRef) –
Return type:
If stores provide their own SPARQL implementation, override this.
queryGraph is None, a URIRef or ‘__UNION__’ If None the graph is specified in the query-string/object If URIRef it specifies the graph to query, If ‘__UNION__’ the union of all named graphs should be queried (This is used by ConjunctiveGraphs Values other than None obviously only makes sense for context-aware stores.)
Parameters:
Return type:
remove(spo, context=None)[source]¶
Remove the set of triples matching the pattern from the store
Parameters:
Return type:
Return type:
triples(triple, context=None)[source]¶
A generator over all the triples matching the pattern. Pattern can include any objects for used for comparing against nodes in the store, for example, REGEXTerm, URIRef, Literal, BNode, Variable, Graph, QuotedGraph, Date? DateRange?
Parameters:
- context (Optional[Graph]) – A conjunctive query can be indicated by either providing a value of None, or a specific context can be queries by passing a Graph instance (if store is context aware).
- triple (Tuple[Optional[Node], Optional[Node], Optional[Node]]) –
Return type:
Iterator[Tuple[Tuple[Node, Node, Node], Iterator[Optional[Graph]]]]
rdflib.plugins.stores.berkeleydb module¶
class rdflib.plugins.stores.berkeleydb.BerkeleyDB(configuration=None, identifier=None)[source]¶
Bases: Store
A store that allows for on-disk persistent using BerkeleyDB, a fast key/value DB.
This store implementation used to be known, previous to rdflib 6.0.0 as ‘Sleepycat’ due to that being the then name of the Python wrapper for BerkeleyDB.
This store allows for quads as well as triples. See examples of use in both the examples.berkeleydb_example and test/test_store/test_store_berkeleydb.py
files.
NOTE on installation:
To use this store, you must have BerkeleyDB installed on your system separately to Python (brew install berkeley-db
on a Mac) and also have the BerkeleyDB Python wrapper installed (pip install berkeleydb
). You may need to install BerkeleyDB Python wrapper like this:YES_I_HAVE_THE_RIGHT_TO_USE_THIS_BERKELEY_DB_VERSION=1 pip install berkeleydb
Parameters:
- configuration (Optional[str]) –
- identifier (Optional[Identifier]) –
__annotations__ = {'db_env': 'db.DBEnv'}¶
__init__(configuration=None, identifier=None)[source]¶
identifier: URIRef of the Store. Defaults to CWD configuration: string containing information open can use to connect to datastore.
Parameters:
- configuration (Optional[str]) –
- identifier (Optional[Identifier]) –
__len__(context=None)[source]¶
Number of statements in the store. This should only account for non- quoted (asserted) statements if the context is not specified, otherwise it should return the number of statements in the formula or context given.
Parameters:
context (Optional[Graph]) – a graph instance to query or None
Return type:
__module__ = 'rdflib.plugins.stores.berkeleydb'¶
add(triple, context, quoted=False, txn=None)[source]¶
Add a triple to the store of triples.
Parameters:
Return type:
Add a graph to the store, no effect if the graph already exists. :type graph: Graph:param graph: a Graph instance
Return type:
bind(prefix, namespace, override=True)[source]¶
Parameters:
- override (bool) – rebind, even if the given namespace is already bound to another prefix.
- prefix (str) –
- namespace (URIRef) –
Return type:
close(commit_pending_transaction=False)[source]¶
This closes the database connection. The commit_pending_transaction parameter specifies whether to commit all pending transactions before closing (if the store is transactional).
Parameters:
commit_pending_transaction (bool) –
Return type:
context_aware_: bool_ = True¶
contexts(triple=None)[source]¶
Generator over all contexts in the graph. If triple is specified, a generator over all contexts the triple is in.
if store is graph_aware, may also return empty contexts
Return type:
Returns:
a generator over Nodes
Parameters:
triple (Optional[Tuple[Node, Node, Node]]) –
db_env_: db.DBEnv_ = None¶
formula_aware_: bool_ = True¶
graph_aware_: bool_ = True¶
property identifier_: Identifier | None_¶
Return type:
Parameters:
prefix (str) –
Return type:
Return type:
Generator[Tuple[str, URIRef], None, None]
open(path, create=True)[source]¶
Opens the store specified by the configuration string. If create is True a store will be created if it does not already exist. If create is False and a store does not already exist an exception is raised. An exception is also raised if a store exists, but there is insufficient permissions to open the store. This should return one of: VALID_STORE, CORRUPTED_STORE, or NO_STORE
Parameters:
Return type:
Parameters:
namespace (URIRef) –
Return type:
remove(spo, context, txn=None)[source]¶
Remove the set of triples matching the pattern from the store
Parameters:
- spo (Tuple[Optional[Node], Optional[Node], Optional[Node]]) –
- context (Optional[Graph]) –
- txn (Optional[Any]) –
Return type:
Remove a graph from the store, this should also remove all triples in the graph
Parameters:
- graphid – a Graph instance
- graph (Graph) –
Return type:
transaction_aware_: bool_ = False¶
triples(spo, context=None, txn=None)[source]¶
A generator over all the triples matching
Parameters:
- spo (Tuple[Optional[Node], Optional[Node], Optional[Node]]) –
- context (Optional[Graph]) –
- txn (Optional[Any]) –
Return type:
Generator[Tuple[Tuple[Node, Node, Node], Generator[Optional[Graph], None, None]], None, None]
rdflib.plugins.stores.concurrent module¶
class rdflib.plugins.stores.concurrent.ConcurrentStore(store)[source]¶
Bases: object
__dict__ = mappingproxy({'__module__': 'rdflib.plugins.stores.concurrent', '__init__': <function ConcurrentStore.__init__>, 'add': , 'remove': , 'triples': , '__len__': <function ConcurrentStore.__len__>, '_ConcurrentStore__begin_read': <function ConcurrentStore.__begin_read>, '_ConcurrentStore__end_read': <function ConcurrentStore.__end_read>, '__dict__': <attribute '__dict__' of 'ConcurrentStore' objects>, '__weakref__': <attribute '__weakref__' of 'ConcurrentStore' objects>, '__doc__': None, '__annotations__': {}})¶
__module__ = 'rdflib.plugins.stores.concurrent'¶
__weakref__¶
list of weak references to the object (if defined)
class rdflib.plugins.stores.concurrent.ResponsibleGenerator(gen, cleanup)[source]¶
Bases: object
A generator that will help clean up when it is done being used.
__init__(gen, cleanup)[source]¶
__module__ = 'rdflib.plugins.stores.concurrent'¶
__slots__ = ['cleanup', 'gen']¶
cleanup¶
gen¶
rdflib.plugins.stores.memory module¶
class rdflib.plugins.stores.memory.Memory(configuration=None, identifier=None)[source]¶
Bases: Store
An in memory implementation of a triple store.
Same as SimpleMemory above, but is Context-aware, Graph-aware, and Formula-aware Authors: Ashley Sommer
Parameters:
- configuration (Optional[str]) –
- identifier (Optional[Identifier]) –
__init__(configuration=None, identifier=None)[source]¶
identifier: URIRef of the Store. Defaults to CWD configuration: string containing information open can use to connect to datastore.
Parameters:
- configuration (Optional[str]) –
- identifier (Optional[Identifier]) –
__len__(context=None)[source]¶
Number of statements in the store. This should only account for non- quoted (asserted) statements if the context is not specified, otherwise it should return the number of statements in the formula or context given.
Parameters:
context (Optional[Graph]) – a graph instance to query or None
Return type:
__module__ = 'rdflib.plugins.stores.memory'¶
add(triple, context, quoted=False)[source]¶
Add a triple to the store of triples.
Parameters:
Return type:
Add a graph to the store, no effect if the graph already exists. :type graph: Graph:param graph: a Graph instance
Return type:
bind(prefix, namespace, override=True)[source]¶
Parameters:
- override (bool) – rebind, even if the given namespace is already bound to another prefix.
- prefix (str) –
- namespace (URIRef) –
Return type:
context_aware_: bool_ = True¶
contexts(triple=None)[source]¶
Generator over all contexts in the graph. If triple is specified, a generator over all contexts the triple is in.
if store is graph_aware, may also return empty contexts
Return type:
Returns:
a generator over Nodes
Parameters:
triple (Optional[Tuple[Node, Node, Node]]) –
formula_aware_: bool_ = True¶
graph_aware_: bool_ = True¶
Parameters:
prefix (str) –
Return type:
Return type:
Parameters:
namespace (URIRef) –
Return type:
query(query, initNs, initBindings, queryGraph, **kwargs)[source]¶
If stores provide their own SPARQL implementation, override this.
queryGraph is None, a URIRef or ‘__UNION__’ If None the graph is specified in the query-string/object If URIRef it specifies the graph to query, If ‘__UNION__’ the union of all named graphs should be queried (This is used by ConjunctiveGraphs Values other than None obviously only makes sense for context-aware stores.)
Parameters:
- query (Union[Query, str]) –
- initNs (Mapping[str, Any]) –
- initBindings (Mapping[str, Identifier]) –
- queryGraph (str) –
Return type:
remove(triple_pattern, context=None)[source]¶
Remove the set of triples matching the pattern from the store
Parameters:
- triple_pattern (Tuple[Optional[Node], Optional[Node], Optional[Node]]) –
- context (Optional[Graph]) –
Return type:
Remove a graph from the store, this should also remove all triples in the graph
Parameters:
- graphid – a Graph instance
- graph (Graph) –
Return type:
triples(triple_pattern, context=None)[source]¶
A generator over all the triples matching
Parameters:
- triple_pattern (Tuple[Optional[Node], Optional[Node], Optional[Node]]) –
- context (Optional[Graph]) –
Return type:
Generator[Tuple[Tuple[Node, Node, Node], Generator[Optional[Graph], None, None]], None, None]
update(update, initNs, initBindings, queryGraph, **kwargs)[source]¶
If stores provide their own (SPARQL) Update implementation, override this.
queryGraph is None, a URIRef or ‘__UNION__’ If None the graph is specified in the query-string/object If URIRef it specifies the graph to query, If ‘__UNION__’ the union of all named graphs should be queried (This is used by ConjunctiveGraphs Values other than None obviously only makes sense for context-aware stores.)
Parameters:
- update (Union[Update, Any]) –
- initNs (Mapping[str, Any]) –
- initBindings (Mapping[str, Identifier]) –
- queryGraph (str) –
Return type:
class rdflib.plugins.stores.memory.SimpleMemory(configuration=None, identifier=None)[source]¶
Bases: Store
A fast naive in memory implementation of a triple store.
This triple store uses nested dictionaries to store triples. Each triple is stored in two such indices as follows spo[s][p][o] = 1 and pos[p][o][s] = 1.
Authors: Michel Pelletier, Daniel Krech, Stefan Niederhauser
Parameters:
- configuration (Optional[str]) –
- identifier (Optional[Identifier]) –
__init__(configuration=None, identifier=None)[source]¶
identifier: URIRef of the Store. Defaults to CWD configuration: string containing information open can use to connect to datastore.
Parameters:
- configuration (Optional[str]) –
- identifier (Optional[Identifier]) –
__len__(context=None)[source]¶
Number of statements in the store. This should only account for non- quoted (asserted) statements if the context is not specified, otherwise it should return the number of statements in the formula or context given.
Parameters:
context (Optional[Graph]) – a graph instance to query or None
Return type:
__module__ = 'rdflib.plugins.stores.memory'¶
add(triple, context, quoted=False)[source]¶
Add a triple to the store of triples.
Parameters:
Return type:
bind(prefix, namespace, override=True)[source]¶
Parameters:
- override (bool) – rebind, even if the given namespace is already bound to another prefix.
- prefix (str) –
- namespace (URIRef) –
Return type:
Parameters:
prefix (str) –
Return type:
Return type:
Parameters:
namespace (URIRef) –
Return type:
query(query, initNs, initBindings, queryGraph, **kwargs)[source]¶
If stores provide their own SPARQL implementation, override this.
queryGraph is None, a URIRef or ‘__UNION__’ If None the graph is specified in the query-string/object If URIRef it specifies the graph to query, If ‘__UNION__’ the union of all named graphs should be queried (This is used by ConjunctiveGraphs Values other than None obviously only makes sense for context-aware stores.)
Parameters:
- query (Union[Query, str]) –
- initNs (Mapping[str, Any]) –
- initBindings (Mapping[str, Identifier]) –
- queryGraph (str) –
- kwargs (Any) –
Return type:
remove(triple_pattern, context=None)[source]¶
Remove the set of triples matching the pattern from the store
Parameters:
- triple_pattern (Tuple[Optional[Node], Optional[Node], Optional[Node]]) –
- context (Optional[Graph]) –
Return type:
triples(triple_pattern, context=None)[source]¶
A generator over all the triples matching
Parameters:
- triple_pattern (Tuple[Optional[Node], Optional[Node], Optional[Node]]) –
- context (Optional[Graph]) –
Return type:
Iterator[Tuple[Tuple[Node, Node, Node], Iterator[Optional[Graph]]]]
update(update, initNs, initBindings, queryGraph, **kwargs)[source]¶
If stores provide their own (SPARQL) Update implementation, override this.
queryGraph is None, a URIRef or ‘__UNION__’ If None the graph is specified in the query-string/object If URIRef it specifies the graph to query, If ‘__UNION__’ the union of all named graphs should be queried (This is used by ConjunctiveGraphs Values other than None obviously only makes sense for context-aware stores.)
Parameters:
- update (Union[Update, str]) –
- initNs (Mapping[str, Any]) –
- initBindings (Mapping[str, Identifier]) –
- queryGraph (str) –
- kwargs (Any) –
Return type:
rdflib.plugins.stores.regexmatching module¶
This wrapper intercepts calls through the store interface which make use of the REGEXTerm class to represent matches by REGEX instead of literal comparison.
Implemented for stores that don’t support this and essentially provides the support by replacing the REGEXTerms by wildcards (None) and matching against the results from the store it’s wrapping.
class rdflib.plugins.stores.regexmatching.REGEXMatching(storage)[source]¶
Bases: Store
identifier: URIRef of the Store. Defaults to CWD configuration: string containing information open can use to connect to datastore.
__len__(context=None)[source]¶
Number of statements in the store. This should only account for non- quoted (asserted) statements if the context is not specified, otherwise it should return the number of statements in the formula or context given.
Parameters:
context – a graph instance to query or None
__module__ = 'rdflib.plugins.stores.regexmatching'¶
add(triple, context, quoted=False)[source]¶
Adds the given statement to a specific context or to the model. The quoted argument is interpreted by formula-aware stores to indicate this statement is quoted/hypothetical It should be an error to not specify a context and have the quoted argument be True. It should also be an error for the quoted argument to be True when the store is not formula-aware.
bind(prefix, namespace, override=True)[source]¶
Parameters:
override – rebind, even if the given namespace is already bound to another prefix.
close(commit_pending_transaction=False)[source]¶
This closes the database connection. The commit_pending_transaction parameter specifies whether to commit all pending transactions before closing (if the store is transactional).
contexts(triple=None)[source]¶
Generator over all contexts in the graph. If triple is specified, a generator over all contexts the triple is in.
if store is graph_aware, may also return empty contexts
Returns:
a generator over Nodes
destroy(configuration)[source]¶
This destroys the instance of the store identified by the configuration string.
open(configuration, create=True)[source]¶
Opens the store specified by the configuration string. If create is True a store will be created if it does not already exist. If create is False and a store does not already exist an exception is raised. An exception is also raised if a store exists, but there is insufficient permissions to open the store. This should return one of: VALID_STORE, CORRUPTED_STORE, or NO_STORE
remove(triple, context=None)[source]¶
Remove the set of triples matching the pattern from the store
remove_context(identifier)[source]¶
triples(triple, context=None)[source]¶
A generator over all the triples matching the pattern. Pattern can include any objects for used for comparing against nodes in the store, for example, REGEXTerm, URIRef, Literal, BNode, Variable, Graph, QuotedGraph, Date? DateRange?
Parameters:
context – A conjunctive query can be indicated by either providing a value of None, or a specific context can be queries by passing a Graph instance (if store is context aware).
class rdflib.plugins.stores.regexmatching.REGEXTerm(expr)[source]¶
Bases: str
REGEXTerm can be used in any term slot and is interpreted as a request to perform a REGEX match (not a string comparison) using the value (pre-compiled) for checking rdf:type matches
__dict__ = mappingproxy({'__module__': 'rdflib.plugins.stores.regexmatching', '__doc__': '\n REGEXTerm can be used in any term slot and is interpreted as a request to\n perform a REGEX match (not a string comparison) using the value\n (pre-compiled) for checking rdf:type matches\n ', '__init__': <function REGEXTerm.__init__>, '__reduce__': <function REGEXTerm.__reduce__>, '__dict__': <attribute '__dict__' of 'REGEXTerm' objects>, '__weakref__': <attribute '__weakref__' of 'REGEXTerm' objects>, '__annotations__': {}})¶
__module__ = 'rdflib.plugins.stores.regexmatching'¶
Helper for pickle.
__weakref__¶
list of weak references to the object (if defined)
rdflib.plugins.stores.regexmatching.regexCompareQuad(quad, regexQuad)[source]¶
rdflib.plugins.stores.sparqlconnector module¶
class rdflib.plugins.stores.sparqlconnector.SPARQLConnector(query_endpoint=None, update_endpoint=None, returnFormat='xml', method='GET', auth=None, **kwargs)[source]¶
Bases: object
this class deals with nitty gritty details of talking to a SPARQL server
Parameters:
- query_endpoint (Optional[str]) –
- update_endpoint (Optional[str]) –
- returnFormat (str) –
- method (Literal[
'GET'
,'POST'
,'POST_FORM'
]) – - auth (Optional[Tuple[str, str]]) –
__dict__ = mappingproxy({'__module__': 'rdflib.plugins.stores.sparqlconnector', '__doc__': '\n this class deals with nitty gritty details of talking to a SPARQL server\n ', '__init__': <function SPARQLConnector.__init__>, 'method': , 'query': , 'update': , '__dict__': <attribute '__dict__' of 'SPARQLConnector' objects>, '__weakref__': <attribute '__weakref__' of 'SPARQLConnector' objects>, '__annotations__': {'_method': 'str'}})¶
__init__(query_endpoint=None, update_endpoint=None, returnFormat='xml', method='GET', auth=None, **kwargs)[source]¶
auth, if present, must be a tuple of (username, password) used for Basic Authentication
Any additional keyword arguments will be passed to to the request, and can be used to setup timeouts etc.
Parameters:
- query_endpoint (Optional[str]) –
- update_endpoint (Optional[str]) –
- returnFormat (str) –
- method (Literal[
'GET'
,'POST'
,'POST_FORM'
]) – - auth (Optional[Tuple[str, str]]) –
__module__ = 'rdflib.plugins.stores.sparqlconnector'¶
__weakref__¶
list of weak references to the object (if defined)
query(query, default_graph=None, named_graph=None)[source]¶
Parameters:
Return type:
update(query, default_graph=None, named_graph=None)[source]¶
Parameters:
Return type:
exception rdflib.plugins.stores.sparqlconnector.SPARQLConnectorException[source]¶
Bases: Exception
__module__ = 'rdflib.plugins.stores.sparqlconnector'¶
__weakref__¶
list of weak references to the object (if defined)
rdflib.plugins.stores.sparqlstore module¶
This is an RDFLib store around Ivan Herman et al.’s SPARQL service wrapper. This was first done in layer-cake, and then ported to RDFLib
class rdflib.plugins.stores.sparqlstore.SPARQLStore(query_endpoint=None, sparql11=True, context_aware=True, node_to_sparql=<function _node_to_sparql>, returnFormat='xml', auth=None, **sparqlconnector_kwargs)[source]¶
Bases: SPARQLConnector, Store
An RDFLib store around a SPARQL endpoint
This is context-aware and should work as expected when a context is specified.
For ConjunctiveGraphs, reading is done from the “default graph”. Exactly what this means depends on your endpoint, because SPARQL does not offer a simple way to query the union of all graphs as it would be expected for a ConjuntiveGraph. This is why we recommend using Dataset instead, which is motivated by the SPARQL 1.1.
Fuseki/TDB has a flag for specifying that the default graph is the union of all graphs (tdb:unionDefaultGraph
in the Fuseki config).
Warning
By default the SPARQL Store does not support blank-nodes!
As blank-nodes act as variables in SPARQL queries, there is no way to query for a particular blank node without using non-standard SPARQL extensions.
See http://www.w3.org/TR/sparql11-query/#BGPsparqlBNodes
You can make use of such extensions through the node_to_sparql
argument. For example if you want to transform BNode(‘0001’) into “bnode:b0001”, you can use a function like this:
def my_bnode_ext(node): ... if isinstance(node, BNode): ... return 'bnode:b%s' % node ... return _node_to_sparql(node) store = SPARQLStore('http://dbpedia.org/sparql', ... node_to_sparql=my_bnode_ext)
You can request a particular result serialization with thereturnFormat
parameter. This is a string that must have a matching plugin registered. Built in is support for xml
,json
, csv
, tsv
and application/rdf+xml
.
The underlying SPARQLConnector uses the urllib library. Any extra kwargs passed to the SPARQLStore connector are passed to urllib when doing HTTP calls. I.e. you have full control of cookies/auth/headers.
Form example:
store = SPARQLStore('...my endpoint ...', auth=('user','pass'))
will use HTTP basic auth.
Parameters:
- query_endpoint (Optional[str]) –
- sparql11 (bool) –
- context_aware (bool) –
- node_to_sparql (Callable[[Node], str]) –
- returnFormat (str) –
- auth (Optional[Tuple[str, str]]) –
__init__(query_endpoint=None, sparql11=True, context_aware=True, node_to_sparql=<function _node_to_sparql>, returnFormat='xml', auth=None, **sparqlconnector_kwargs)[source]¶
auth, if present, must be a tuple of (username, password) used for Basic Authentication
Any additional keyword arguments will be passed to to the request, and can be used to setup timeouts etc.
Parameters:
- query_endpoint (Optional[str]) –
- sparql11 (bool) –
- context_aware (bool) –
- node_to_sparql (Callable[[Node], str]) –
- returnFormat (str) –
- auth (Optional[Tuple[str, str]]) –
__len__(context=None)[source]¶
Number of statements in the store. This should only account for non- quoted (asserted) statements if the context is not specified, otherwise it should return the number of statements in the formula or context given.
Parameters:
context (Optional[Graph]) – a graph instance to query or None
Return type:
__module__ = 'rdflib.plugins.stores.sparqlstore'¶
add(_, context=None, quoted=False)[source]¶
Adds the given statement to a specific context or to the model. The quoted argument is interpreted by formula-aware stores to indicate this statement is quoted/hypothetical It should be an error to not specify a context and have the quoted argument be True. It should also be an error for the quoted argument to be True when the store is not formula-aware.
Parameters:
Return type:
Adds each item in the list of statements to a specific context. The quoted argument is interpreted by formula-aware stores to indicate this statement is quoted/hypothetical. Note that the default implementation is a redirect to add
Parameters:
quads (Iterable[Tuple[Node, Node, Node, Graph]]) –
Return type:
Add a graph to the store, no effect if the graph already exists. :type graph: Graph:param graph: a Graph instance
Return type:
bind(prefix, namespace, override=True)[source]¶
Parameters:
- override (bool) – rebind, even if the given namespace is already bound to another prefix.
- prefix (str) –
- namespace (URIRef) –
Return type:
Return type:
contexts(triple=None)[source]¶
Iterates over results to “SELECT ?NAME { GRAPH ?NAME { ?s ?p ?o } }” or “SELECT ?NAME { GRAPH ?NAME {} }” if triple is None.
Returns instances of this store with the SPARQL wrapper object updated via addNamedGraph(?NAME).
This causes a named-graph-uri key / value pair to be sent over the protocol.
Please note that some SPARQL endpoints are not able to find empty named graphs.
Parameters:
triple (Optional[Tuple[Node, Node, Node]]) –
Return type:
Generator[IdentifiedNode, None, None]
create(configuration)[source]¶
Parameters:
configuration (str) –
Return type:
destroy(configuration)[source]¶
This destroys the instance of the store identified by the configuration string.
Parameters:
configuration (str) –
Return type:
formula_aware_: bool_ = False¶
graph_aware_: bool_ = True¶
Parameters:
prefix (str) –
Return type:
Return type:
objects(subject=None, predicate=None)[source]¶
A generator of objects with the given subject and predicate
Parameters:
Return type:
open(configuration, create=False)[source]¶
This method is included so that calls to this Store via Graph, e.g. Graph(“SPARQLStore”), can set the required parameters
Parameters:
Return type:
predicate_objects(subject=None)[source]¶
A generator of (predicate, object) tuples for the given subject
Parameters:
Return type:
Generator[Tuple[Node, Node], None, None]
predicates(subject=None, object=None)[source]¶
A generator of predicates with the given subject and object
Parameters:
Return type:
Parameters:
namespace (URIRef) –
Return type:
query(query, initNs=None, initBindings=None, queryGraph=None, DEBUG=False)[source]¶
If stores provide their own SPARQL implementation, override this.
queryGraph is None, a URIRef or ‘__UNION__’ If None the graph is specified in the query-string/object If URIRef it specifies the graph to query, If ‘__UNION__’ the union of all named graphs should be queried (This is used by ConjunctiveGraphs Values other than None obviously only makes sense for context-aware stores.)
Parameters:
- query (Union[Query, str]) –
- initNs (Optional[Mapping[str, Any]]) –
- initBindings (Optional[Mapping[str, Identifier]]) –
- queryGraph (Optional[str]) –
- DEBUG (bool) –
Return type:
regex_matching = 0¶
Remove the set of triples matching the pattern from the store
Parameters:
Return type:
Remove a graph from the store, this should also remove all triples in the graph
Parameters:
- graphid – a Graph instance
- graph (Graph) –
Return type:
Return type:
subject_objects(predicate=None)[source]¶
A generator of (subject, object) tuples for the given predicate
Parameters:
Return type:
Generator[Tuple[Node, Node], None, None]
subject_predicates(object=None)[source]¶
A generator of (subject, predicate) tuples for the given object
Parameters:
Return type:
Generator[Tuple[Node, Node], None, None]
subjects(predicate=None, object=None)[source]¶
A generator of subjects with the given predicate and object
Parameters:
Return type:
transaction_aware_: bool_ = False¶
triples(spo, context=None)[source]¶
- tuple **(s, o, p)**the triple used as filter for the SPARQL select. (None, None, None) means anything.
- context contextthe graph effectively calling this method.
Returns a tuple of triples executing essentially a SPARQL like SELECT ?subj ?pred ?obj WHERE { ?subj ?pred ?obj }
context may include three parameter to refine the underlying query:
- LIMIT: an integer to limit the number of results
- OFFSET: an integer to enable paging of results
- ORDERBY: an instance of Variable(‘s’), Variable(‘o’) or Variable(‘p’) or, by default, the first ‘None’ from the given triple
Warning
- Using LIMIT or OFFSET automatically include ORDERBY otherwise this is because the results are retrieved in a not deterministic way (depends on the walking path on the graph)
- Using OFFSET without defining LIMIT will discard the first OFFSET - 1 results
a_graph.LIMIT = limit a_graph.OFFSET = offset triple_generator = a_graph.triples(mytriple):
do something
Removes LIMIT and OFFSET if not required for the next triple() calls
del a_graph.LIMIT del a_graph.OFFSET
Parameters:
Return type:
Iterator[Tuple[Tuple[Node, Node, Node], None]]
triples_choices(_, context=None)[source]¶
A variant of triples that can take a list of terms instead of a single term in any slot. Stores can implement this to optimize the response time from the import default ‘fallback’ implementation, which will iterate over each term in the list and dispatch to triples.
Parameters:
- _ (Tuple[Union[Node, List[Node]], Union[Node, List[Node]], Union[Node, List[Node]]]) –
- context (Optional[Graph]) –
Return type:
Generator[Tuple[Tuple[Node, Node, Node], Iterator[Optional[Graph]]], None, None]
update(query, initNs={}, initBindings={}, queryGraph=None, DEBUG=False)[source]¶
If stores provide their own (SPARQL) Update implementation, override this.
queryGraph is None, a URIRef or ‘__UNION__’ If None the graph is specified in the query-string/object If URIRef it specifies the graph to query, If ‘__UNION__’ the union of all named graphs should be queried (This is used by ConjunctiveGraphs Values other than None obviously only makes sense for context-aware stores.)
Parameters:
- query (Union[Update, str]) –
- initNs (Dict[str, Any]) –
- initBindings (Dict[str, Identifier]) –
- queryGraph (Optional[Identifier]) –
- DEBUG (bool) –
Return type:
class rdflib.plugins.stores.sparqlstore.SPARQLUpdateStore(query_endpoint=None, update_endpoint=None, sparql11=True, context_aware=True, postAsEncoded=True, autocommit=True, dirty_reads=False, **kwds)[source]¶
Bases: SPARQLStore
A store using SPARQL queries for reading and SPARQL Update for changes.
This can be context-aware, if so, any changes will be to the given named graph only.
In favor of the SPARQL 1.1 motivated Dataset, we advise against using this with ConjunctiveGraphs, as it reads and writes from and to the “default graph”. Exactly what this means depends on the endpoint and can result in confusion.
For Graph objects, everything works as expected.
See the SPARQLStore base class for more information.
Parameters:
- query_endpoint (Optional[str]) –
- update_endpoint (Optional[str]) –
- sparql11 (bool) –
- context_aware (bool) –
- postAsEncoded (bool) –
- autocommit (bool) –
- dirty_reads (bool) –
BLOCK_END = '}'¶
BLOCK_FINDING_PATTERN = re.compile('(?P<block_start>{)|(?P<block_end>})|(?P<block_content>((\'([^\'\\\\]|\\\\.)*\')|("([^"\\\\]|\\\\.)*")|(\'\'\'((\'|\'\')?([^\'\\\\]|\\\\.))*\'\'\')|("""(("|"")?([^"\\\\]|\\\\.))*"""))|(<([^<>"{}|^`\\])¶
BLOCK_START = '{'¶
BlockContent = '((\'([^\'\\\\]|\\\\.)*\')|("([^"\\\\]|\\\\.)*")|(\'\'\'((\'|\'\')?([^\'\\\\]|\\\\.))*\'\'\')|("""(("|"")?([^"\\\\]|\\\\.))*"""))|(<([^<>"{}|^`\\]\\\\[\\x00-\\x20])*>)|(#[^\\x0D\\x0A]*([\\x0D\\x0A]|\\Z))|(\\\\.)'¶
BlockFinding = '(?P<block_start>{)|(?P<block_end>})|(?P<block_content>((\'([^\'\\\\]|\\\\.)*\')|("([^"\\\\]|\\\\.)*")|(\'\'\'((\'|\'\')?([^\'\\\\]|\\\\.))*\'\'\')|("""(("|"")?([^"\\\\]|\\\\.))*"""))|(<([^<>"{}|^`\\]\\\\[\\x00-\\x20])*>)|(#[^\\x0D\\x0A]*([\\x0D\\x0A]|\\Z))|(\\\\.))'¶
ESCAPED = '\\\\.'¶
IRIREF = '<([^<>"{}|^`\\]\\\\[\\x00-\\x20])*>'¶
STRING_LITERAL1 = "'([^'\\\\]|\\\\.)*'"¶
STRING_LITERAL2 = '"([^"\\\\]|\\\\.)*"'¶
STRING_LITERAL_LONG1 = "'''(('|'')?([^'\\\\]|\\\\.))*'''"¶
STRING_LITERAL_LONG2 = '"""(("|"")?([^"\\\\]|\\\\.))*"""'¶
String = '(\'([^\'\\\\]|\\\\.)*\')|("([^"\\\\]|\\\\.)*")|(\'\'\'((\'|\'\')?([^\'\\\\]|\\\\.))*\'\'\')|("""(("|"")?([^"\\\\]|\\\\.))*""")'¶
__init__(query_endpoint=None, update_endpoint=None, sparql11=True, context_aware=True, postAsEncoded=True, autocommit=True, dirty_reads=False, **kwds)[source]¶
:param autocommit if set, the store will commit after every writing operations. If False, we only make queries on the server once commit is called.
:param dirty_reads if set, we do not commit before reading. So you cannot read what you wrote before manually calling commit.
Parameters:
- query_endpoint (Optional[str]) –
- update_endpoint (Optional[str]) –
- sparql11 (bool) –
- context_aware (bool) –
- postAsEncoded (bool) –
- autocommit (bool) –
- dirty_reads (bool) –
__len__(*args, **kwargs)[source]¶
Number of statements in the store. This should only account for non- quoted (asserted) statements if the context is not specified, otherwise it should return the number of statements in the formula or context given.
Parameters:
Return type:
__module__ = 'rdflib.plugins.stores.sparqlstore'¶
add(spo, context=None, quoted=False)[source]¶
Add a triple to the store of triples.
Parameters:
Return type:
Add a list of quads to the store.
Parameters:
quads (Iterable[Tuple[Node, Node, Node, Graph]]) –
Return type:
Add a graph to the store, no effect if the graph already exists. :type graph: Graph:param graph: a Graph instance
Return type:
add(), addN(), and remove() are transactional to reduce overhead of many small edits. Read and update() calls will automatically commit any outstanding edits. This should behave as expected most of the time, except that alternating writes and reads can degenerate to the original call-per-triple situation that originally existed.
Return type:
contexts(*args, **kwargs)[source]¶
Iterates over results to “SELECT ?NAME { GRAPH ?NAME { ?s ?p ?o } }” or “SELECT ?NAME { GRAPH ?NAME {} }” if triple is None.
Returns instances of this store with the SPARQL wrapper object updated via addNamedGraph(?NAME).
This causes a named-graph-uri key / value pair to be sent over the protocol.
Please note that some SPARQL endpoints are not able to find empty named graphs.
Parameters:
Return type:
Generator[IdentifiedNode, None, None]
nsBindings_: Dict[str, Any]_¶
objects(subject=None, predicate=None)[source]¶
A generator of objects with the given subject and predicate
Parameters:
Return type:
open(configuration, create=False)[source]¶
sets the endpoint URLs for this SPARQLStore
Parameters:
- configuration (Union[str, Tuple[str, str]]) – either a tuple of (query_endpoint, update_endpoint), or a string with the endpoint which is configured as query and update endpoint
- create (bool) – if True an exception is thrown.
Return type:
predicate_objects(subject=None)[source]¶
A generator of (predicate, object) tuples for the given subject
Parameters:
Return type:
Generator[Tuple[Node, Node], None, None]
predicates(subject=None, object=None)[source]¶
A generator of predicates with the given subject and object
Parameters:
Return type:
query(*args, **kwargs)[source]¶
If stores provide their own SPARQL implementation, override this.
queryGraph is None, a URIRef or ‘__UNION__’ If None the graph is specified in the query-string/object If URIRef it specifies the graph to query, If ‘__UNION__’ the union of all named graphs should be queried (This is used by ConjunctiveGraphs Values other than None obviously only makes sense for context-aware stores.)
Parameters:
Return type:
Remove a triple from the store
Parameters:
Return type:
Remove a graph from the store, this should also remove all triples in the graph
Parameters:
- graphid – a Graph instance
- graph (Graph) –
Return type:
Return type:
Return type:
subject_objects(predicate=None)[source]¶
A generator of (subject, object) tuples for the given predicate
Parameters:
Return type:
Generator[Tuple[Node, Node], None, None]
subject_predicates(object=None)[source]¶
A generator of (subject, predicate) tuples for the given object
Parameters:
Return type:
Generator[Tuple[Node, Node], None, None]
subjects(predicate=None, object=None)[source]¶
A generator of subjects with the given predicate and object
Parameters:
Return type:
triples(*args, **kwargs)[source]¶
- tuple **(s, o, p)**the triple used as filter for the SPARQL select. (None, None, None) means anything.
- context contextthe graph effectively calling this method.
Returns a tuple of triples executing essentially a SPARQL like SELECT ?subj ?pred ?obj WHERE { ?subj ?pred ?obj }
context may include three parameter to refine the underlying query:
- LIMIT: an integer to limit the number of results
- OFFSET: an integer to enable paging of results
- ORDERBY: an instance of Variable(‘s’), Variable(‘o’) or Variable(‘p’) or, by default, the first ‘None’ from the given triple
Warning
- Using LIMIT or OFFSET automatically include ORDERBY otherwise this is because the results are retrieved in a not deterministic way (depends on the walking path on the graph)
- Using OFFSET without defining LIMIT will discard the first OFFSET - 1 results
a_graph.LIMIT = limit a_graph.OFFSET = offset triple_generator = a_graph.triples(mytriple):
do something
Removes LIMIT and OFFSET if not required for the next triple() calls
del a_graph.LIMIT del a_graph.OFFSET
Parameters:
Return type:
Iterator[Tuple[Tuple[Node, Node, Node], None]]
update(query, initNs={}, initBindings={}, queryGraph=None, DEBUG=False)[source]¶
Perform a SPARQL Update Query against the endpoint, INSERT, LOAD, DELETE etc. Setting initNs adds PREFIX declarations to the beginning of the update. Setting initBindings adds inline VALUEs to the beginning of every WHERE clause. By the SPARQL grammar, all operations that support variables (namely INSERT and DELETE) require a WHERE clause. Important: initBindings fails if the update contains the substring ‘WHERE {’ which does not denote a WHERE clause, e.g. if it is part of a literal.
Context-aware query rewriting
- When: If context-awareness is enabled and the graph is not the default graph of the store.
- Why: To ensure consistency with the Memory store. The graph must accept “local” SPARQL requests (requests with no GRAPH keyword) as if it was the default graph.
- What is done: These “local” queries are rewritten by this store. The content of each block of a SPARQL Update operation is wrapped in a GRAPH block except if the block is empty. This basically causes INSERT, INSERT DATA, DELETE, DELETE DATA and WHERE to operate only on the context.
- Example:
"INSERT DATA { <urn:michel> <urn:likes> <urn:pizza> }"
is converted into"INSERT DATA { GRAPH <urn:graph> { <urn:michel> <urn:likes> <urn:pizza> } }"
. - Warning: Queries are presumed to be “local” but this assumption is not checked. For instance, if the query already contains GRAPH blocks, the latter will be wrapped in new GRAPH blocks.
- Warning: A simplified grammar is used that should tolerate extensions of the SPARQL grammar. Still, the process may fail in uncommon situations and produce invalid output.
Parameters:
- query (Union[Update, str]) –
- initNs (Dict[str, Any]) –
- initBindings (Dict[str, Identifier]) –
- queryGraph (Optional[str]) –
- DEBUG (bool) –
where_pattern = re.compile('(?PWHERE\\s*\\{)', re.IGNORECASE)¶
Module contents¶
This package contains modules for additional RDFLib stores