franz.openrdf.repository package

Submodules

franz.openrdf.repository.repository module

class franz.openrdf.repository.repository.Repository(catalog, database_name, repository)[source]

Bases: object

A repository contains RDF data that can be queried and updated. Access to the repository can be acquired by opening a connection to it. This connection can then be used to query and/or update the contents of the repository.

Please note that a repository needs to be initialized before it can be used and that it should be shut down before it is discarded/garbage collected. Forgetting the latter can result in loss of data (depending on the Repository implementation)!

ACCESS = 'ACCESS'
CREATE = 'CREATE'
OPEN = 'OPEN'
RENEW = 'RENEW'
REPLACE = 'REPLACE'
__init__(catalog, database_name, repository)[source]

Invoke through getRepository().

bulk_mode

Turn BulkMode on with True or off with False.

In bulk mode, all modifications to the triple-store are made without writing to the transaction log. There is overhead to switching in and out of bulk-mode, and it is a global repository state, so all clients are affected.

getConnection()[source]

Opens a connection to this store that can be used for querying and updating the contents of the store. Created connections need to be closed to make sure that any resources they keep hold of are released. The best way to ensure this is to use a with statement:

with repo.getConnection() as conn:
    ...
Returns:A RepositoryConnection object.
Return type:RepositoryConnection
getDatabaseName()[source]

Return the name of the database (remote triple store) that this repository is interfacing with.

getSpec()[source]

Return a session spec string for this repository.

See openSession(). :return: A session spec. :rtype: string

getValueFactory()[source]

Return a ValueFactory for this store.

This is present for RDF4J compatibility, but in the Python API all ValueFactory functionality has been duplicated or subsumed in the RepositoryConnection class. It isn’t necessary to manipulate the ValueFactory class at all.

Returns:A ValueFactory instance.
Return type:ValueFactory
initialize()[source]

Initializes this repository. A repository must be initialized before it can be used.

It is recommended to take advantage of the fact that repositories are context managers and use the with statement to ensure that initialize() and shutDown() are called:

with catalog.getRepository() as repo:
    # No need to call initialize or shutDown inside.
    ...
Returns:self (to allow call chaining).
isWritable()[source]

Checks whether this store is writable, i.e. if the data contained in this store can be changed. The writability of the store is determined by the writability of the Sail that this store operates on.

registerDatatypeMapping(predicate=None, datatype=None, nativeType=None)[source]

Register an inlined datatype.

This allows some literals to be stored in an optimized form on the server.

See also

http://franz.com/agraph/support/documentation/current/lisp-reference.html#ref-type-mapping
More detailed discussion of type mappings in the Lisp API documentation.

You must supply nativeType and either predicate or datatype.

If predicate is supplied, then object arguments to triples with that predicate will use an inlined encoding of type nativeType in their internal representation on the server.

If datatype is supplied, then typed literal objects with a datatype matching datatype will use an inlined encoding of type nativeType.

Duplicated in the RepositoryConnection class for Python user convenience.

Parameters:
  • predicate – The URI of a predicate used in the triple store.
  • datatype – May be one of: XMLSchema.INT, XMLSchema.LONG, XMLSchema.FLOAT, XMLSchema.DATE and XMLSchema.DATETIME.
  • nativeType (string|type) – may be int, datetime, or float.
shutDown()[source]

Shuts the store down, releasing any resources that it keeps hold of. Once shut down, the store can no longer be used.

It is recommended to take advantage of the fact that repositories are context managers and use the with statement to ensure that initialize() and shutDown() are called:

with catalog.getRepository() as repo:
    # No need to call initialize or shutDown inside.
    ...

franz.openrdf.repository.repositoryconnection module

class franz.openrdf.repository.repositoryconnection.GeoType(system, scale=None, unit=None, xMin=None, xMax=None, yMin=None, yMax=None, latMin=None, latMax=None, longMin=None, longMax=None)[source]

Bases: object

Cartesian = 'CARTESIAN'
Spherical = 'SPHERICAL'
__init__(system, scale=None, unit=None, xMin=None, xMax=None, yMin=None, yMax=None, latMin=None, latMax=None, longMin=None, longMax=None)[source]
createBox(xMin=None, xMax=None, yMin=None, yMax=None, unit=None)[source]

Define a rectangular region for the current coordinate system.

createCircle(x, y, radius, unit=None)[source]

Define a circular region with vertex x,y and radius “radius”. The distance unit for the radius is either ‘unit’ or the unit specified for this GeoType. If ‘innerRadius’ is specified, the region is ring-shaped, consisting of the space between the inner and outer circles.

createCoordinate(x=None, y=None, latitude=None, longitude=None, unit=None)[source]

Create an x, y or lat, long coordinate for the system defined by this geotype.

createPolygon(vertices, uri=None)[source]

Define a polygonal region with the specified vertices. ‘vertices’ is a list of x,y pairs. The ‘uri’ is optional.

setConnection(connection)[source]
class franz.openrdf.repository.repositoryconnection.PrefixFormat[source]

Bases: franz.openrdf.repository.repositoryconnection.EncodedIdPrefix

class franz.openrdf.repository.repositoryconnection.RepositoryConnection(repository, close_repo=False)[source]

Bases: object

The RepositoryConnection class is the main interface for updating data in and performing queries on a Repository. By default, a RespositoryConnection is in autoCommit mode, meaning that each operation corresponds to a single transaction on the underlying triple store. autoCommit can be switched off, in which case it is up to the user to handle transaction commit/rollback. Note that care should be taken to always properly close a RepositoryConnection after one is finished with it, to free up resources and avoid unnecessary locks.

Note that concurrent access to the same connection object is explicitly forbidden. The client must perform its own synchronization to ensure non-concurrent access.

Several methods take a vararg argument that optionally specifies a set of contexts on which the method should operate. (A context is the URI of a subgraph.) Note that a vararg parameter is optional, it can be completely left out of the method call, in which case a method either operates on a provided statement’s context (if one of the method parameters is a statement or collection of statements), or operates on the repository as a whole, completely ignoring context. A vararg argument may also be None, meaning that the method operates on those statements which have no associated context only.

__init__(repository, close_repo=False)[source]

Call through getConnection().

Parameters:
  • repository (Repository) – Repository to connect to.
  • close_repo (bool) – If True shutdown the repository when this connection is closed. The default is False.
add(arg0, arg1=None, arg2=None, contexts=None, base=None, format=None, serverSide=False, attributes=None)[source]

Calls addTriple(), addStatement(), or addFile().

Best practice is to avoid add() and use addTriple(), addStatement() or addFile() instead.

Parameters:
  • arg0 (Statement|string|Value) – May be a Statement or a filepath. If so, arg1 and arg2 default to None. May also be the subject of a triple (in that case arg1 and arg2 must be the predicate and the object respectively).
  • arg1 (string|Value) – Predicate of the new triple.
  • arg2 (string|Value) – Object of the new triple.
  • contexts (Iterable[URI|string]) – Optional list of contexts (subgraph URIs), defaulting to None. A context is the URI of a subgraph. If None, the triple(s) will be added to the null context (the default or background graph).
  • base (string) – The baseURI to associate with loading a file. Defaults to None. If None the baseURI will be chosen by the server.
  • format (RDFFormat) – Either RDFFormat.NTRIPLES or RDFFormat.RDFXML. Defaults to None.
  • serverSide (bool) – Indicates whether the filepath refers to a file on the client computer or on the server. Defaults to False (i.e. client-side).
  • attributes (dict[str, str]) – Attributes for the new triple (a mapping from attribute names to values).
addData(data, rdf_format=RDFFormat.TURTLE: Turtle, base_uri=None, context=None, attributes=None)[source]

Adds data from a string to the repository.

Parameters:
  • data (string) – Data to be added.
  • rdf_format (RDFFormat|str) – Data format - either a RDFFormat or a MIME type (string).
  • base_uri (string) – Base for resolving relative URIs. If None (default), the URI will be chosen by the server.
  • context (URI|string) – Graph to add the data to. If None (default) the default graph will be used.
  • attributes (dict[str, str]) – Attributes for the added triples (a mapping from attribute names to values).
addFile(filePath, base=None, format=None, context=None, serverSide=False, content_encoding=None, attributes=None)[source]

Loads a file into the triple store. Note that a file can be loaded into only one context.

Parameters:
  • filepath – Identifies the file to load.
  • context (URI|string|list[URI|string]) – An optional context URI (subgraph URI), defaulting to None. If None, the triple(s) will be added to the null context (the default or background graph).
  • base (string) – The baseURI to associate with loading a file. Defaults to None. If None the baseURI will be chosen by the server.
  • format (RDFFormat) – Either RDFFormat.NTRIPLES or RDFFormat.RDFXML. Defaults to None.
  • serverSide (bool) – Indicates whether the filepath refers to a file on the client computer or on the server. Defaults to False (i.e. client-side).
  • attributes (dict[str, str]) – Attributes for all added triples (a mapping from attribute names to values).
addIndex(_type)[source]

Add a specific type of index to the current set of triple indices.

Parameters:_type (string) – Index name (see listIndices()).
addRules(rules, language=QueryLanguage.PROLOG)[source]

Add Prolog functors to the current session.

Note that this only works with a dedicated session (See session().

See also

http://franz.com/agraph/support/documentation/current/prolog-tutorial.html
Tutorial describing the syntax of Prolog rules (functors).
Parameters:
  • rules (string) – A string containing Prolog rule definitions. The definitions are S-expressions using the <- and <-- operators (to append and overwrite rules respectively).
  • language – Ignored.
addStatement(statement, contexts=<object object>, attributes=None)[source]

Add the supplied statement to the specified contexts in the repository.

Parameters:
  • statement (Statement) – The statement to be added. Note that the context field is ignored (use the contexts parameters instead).
  • contexts (Iterable[string|URI]) – List of contexts (graph URIs) to add the statement to. If present this overrides the context from the statement object. The default context is None, which adds the statement to the null context (the default or background graph).
  • attributes (dict[str, str]) – Attributes for the added triple (a mapping from attribute names to values). If present this overrides the attributes passed in the statement object.
addTriple(subject, predicate, object, contexts=None, attributes=None)[source]

Add a single triple to the repository.

Parameters:
  • subject (Value) – Subject of the new triple.
  • predicate (Value) – Predicate of the new triple.
  • object (Value) – Object of the new triple.
  • contexts (Iterable[string|URI]) – List of contexts (graph URIs) to add the triple to. Defaults to None, which adds the statement to the null context (the default or background graph).
  • attributes (dict[str, str]) – Attributes for the added triple (a mapping from attribute names to values).
addTriples(triples_or_quads, context=None, ntriples=False, attributes=None)[source]

Add the supplied triples or quads to this repository.

Each triple or quad can have between 3 and 5 elements, the last one being the dictionary of attributes (or None if the default attributes should be used).

Parameters:
  • triples_or_quads (Iterable[list[string|Value]|tuple[string|Value]|Statement]) – List of triples or quads. Each element can be either a statement or a list or tuple of Value objects or strings.
  • context (string|URI|list[string|URI]) – Context (graph) or list of contexts to add the triples to. Defaults to None (the default graph). Note that this will be ignored for all input quads that already specify a context.
  • ntriples (bool) – If True, parts of the triples are assumed to be strings in N-Triples format and are sent to the server without any conversion.
  • attributes (dict[str, str]) – Default attributes for the added triples (a mapping from attribute names to values). These will be used only for statements that do not contain their own attribute dictionaries.
add_commit_size

The threshold for commit size during triple add operations. Set to 0 (zero) or None to clear size-based autocommit behavior. When set to an integer triple_count > 0, a commit will occur every triple_count triples added and at the end of the triples being added.

allocateEncodedIds(prefix, amount=1)[source]

allocateEncodedIds allows you to use the server to allocate unique ids for a given registered prefix which has a fixed-width format specifier.

See notes on next-encoded-upi-for-prefix in:

https://franz.com/agraph/support/documentation/current/encoded-ids.html

callStoredProc(function, module, *args)[source]
clear(contexts='ALL_CONTEXTS')[source]

Removes all statements from designated contexts in the repository. If contexts is ALL_CONTEXTS, clears the repository of all statements.

Parameters:contexts (Iterable[string|URI]|string|URI) – A context or list of contexts.
clearAttributeFilter()[source]

Remove the static attribute filter (if set).

clearNamespaces(reset=True)[source]

Delete all namespaces in this repository for the current user.

Parameters:reset – If True (default) the user’s namespaces are reset to the default set of namespaces, otherwise all namespaces are cleared.
close()[source]

Close the connection. This also closes the session if it is active.

It is safe to call this on a connection that has already been closed.

Note that using with is the preferred way to manage connections.

closeSession()[source]

Close a session.

It is not an error to call this when no session is active.

commit(settings=None, **kwargs)[source]

Commit changes on an open session.

Parameters can be used to control distributed transaction settings for the current transaction, as if using temporaryTransactionSettings().

createBNode(nodeID=None)[source]

Create a new blank node.

Parameters:nodeID (string) – Optional node identifier, if not given a fresh one will be generated.
Returns:A BNode value.
Return type:BNode
createBox(xMin=None, xMax=None, yMin=None, yMax=None)[source]

Create a rectangular search region (a box) for geospatial search. This method works for both Cartesian and spherical coordinate systems.

Parameters:
  • xMin (float|int) – Minimum latitude.
  • xMax (float|int) – Maximum latitude.
  • yMin (float|int) – Minimum longitude.
  • yMax (float|int) – Maximum longitude.
Returns:

A geospatial literal corresponding to the specified search region.

Return type:

Literal

createCircle(x, y, radius, unit=None)[source]

Create a circular search region for geospatial search.

This method works for both Cartesian and spherical coordinate systems.

Parameters:
  • x (float|int) – Latitude of the center.
  • y (float|int) – Longitude of the center.
  • radius (float|int) – The radius of the circle expressed in the designated unit.
  • unit (string) – Unit in which the radius is expressed. Defaults to the unit assigned to the coordinate system. Legal values are "degree", "radian", "km" and "mile".
createCoordinate(x=None, y=None, latitude=None, longitude=None)[source]

Create an x, y or latitude, longitude coordinate in the current coordinate system.

Either x, y or latitude, longitude must be given.

Parameters:
  • x – X coordinate of the created point.
  • y – Y coordinate of the created point.
  • latitude – Latitude of the created point.
  • longitude – Longitude of the created point.
Returns:

A literal representing the created point.

Return type:

Literal

createFreeTextIndex(name, predicates=None, indexLiterals=None, indexResources=None, indexFields=None, minimumWordSize=None, stopWords=None, wordFilters=None, innerChars=None, borderChars=None, tokenizer=None)[source]

Create a free-text index with the given parameters.

See also

http://franz.com/agraph/support/documentation/current/http-protocol.html#put-freetext-index
Documentation of the HTTP endpoint used by this method.
http://franz.com/agraph/support/documentation/current/text-index.html
General information about text indexing in AllegroGraph.
Parameters:
  • name (string) – Name for the new index.
  • predicates (list[string|URI]) – A list of predicates to be indexed. If not given all triples will be indexed regardless of predicate.
  • indexLiterals (bool|list[URI]) – Determines which literals to index. It can be``True`` (the default), False, or a list of resources, indicating the literal types that should be indexed.
  • indexResources (bool|string) – Determines which resources are indexed. It can be True, False (the default), or "short", to index only the part of resources after the last slash or hash character.
  • indexFields (list[string]) – List of triples fields to index. Can be any combination of "subject", "predicate", "object", and "graph". The default is ["object"].
  • minimumWordSize (int) – Determines the minimum size a word must have to be indexed. The default is 3.
  • stopWords (list[string]) – List of words that should not be indexed. When not given, a list of common English words is used.
  • wordFilters (list[string]) – List of normalizing filters used to process words before indexing. The list if supported filters can be found here: http://franz.com/agraph/support/documentation/current/text-index.html
  • innerChars (list[string]) –

    The character set to be used as the constituent characters of a word. Should be a list of character classes. Valid classes are:

    • ”alpha”`: All (unicode) alphabetic characters.
    • "digit": All base-10 digits.
    • "alphanumeric": All digits and alphabetic characters.
    • a single character
    • a range of characters: A single character, followed by a dash (-) character, followed by another single character.
  • borderChars (list[string]) – The character set to be used as the border characters of indexed words. Uses the same syntax as innerChars.
  • tokenizer (string) – Controls the way in which the text is plit into tokens. Can be either "default" or "japaense". Note that the japaense tokenizer ignores innerChars and borderChars.
createLatLongSystem(unit='degree', scale=None, latMin=None, latMax=None, longMin=None, longMax=None)[source]

Create a spherical coordinate system and use it as the current coordinate system.

Parameters:
  • scale (float|int) – Estimate of the size of a typical search region in the latitudinal direction.
  • unit (string) – One of: 'degree', 'mile', 'radian', 'km'. The default is 'degree'.
  • longMin (float|int) – Left side of the coordinate system.
  • longMax (float|int) – Right side of the coordinate system.
  • latMin (float|int) – Bottom border of the coordinate system.
  • latMax (float|int) – Top border of the coordinate system.
Returns:

The new coordinate system.

createLiteral(value, datatype=None, language=None)[source]

Create a new literal with value value. datatype, if supplied, should be a URI (it can be a string or an URI instance, in which case value must be a string.

Parameters:
  • value (int|long|float|string|datetime.datetime|datetime.date|datetime.time) – Literal value - can be a string, a number or a datetime object.
  • datatype (string|URI) – Optional literal type. Note that if value is not a string the type will be guessed automatically.
  • language (string) – Optional language tag.
createPolygon(vertices, uri=None, geoType=None)[source]

Define a polygonal region with the specified vertices.

Parameters:
  • vertices (list[(float, float)]) – List of x, y pairs.
  • uri (URI) – URI under which the polygon will be stored in the repository. If not given a blank node will be used.
  • geoType – unused
Returns:

An object representing the newly created polygon.

Return type:

GeoPolygon

createRange(lowerBound, upperBound)[source]

Create a compound literal representing a range from lowerBound to upperBound.

Parameters:
  • lowerBound (int) – Lower bound of the range.
  • upperBound (int) – Upper bound of the range.
Returns:

A new literal object.

Return type:

RangeLiteral

createRectangularSystem(scale=1, unit=None, xMin=0, xMax=None, yMin=0, yMax=None)[source]

Create a Cartesian coordinate system and use it as the current coordinate system.

Parameters:
  • scale (float|int) – Estimate of the Y size of a typical search region.
  • unit – Must be None (the default).
  • xMin (float|int) – Left edge of the rectangle.
  • xMax (float|int) – Right edge of the rectangle.
  • yMin (float|int) – Bottom edge of the rectangle.
  • yMax (float|int) – Top edge of the rectangle.
Returns:

The new coordinate system.

createStatement(subject, predicate, object, context=None)[source]

Create a new Statement object.

Note that this does not cause the statement to be added to the repository.

Parameters:
  • subject (Resource) – Subject of the new statement.
  • predicate (URI) – Predicate of the new statement.
  • object (Value) – Object of the new statement.
  • context (URI) – Graph of the new statement (optional).
Returns:

A new statement.

Return type:

Statement

createURI(uri=None, namespace=None, localname=None)[source]

Creates a new URI from the supplied string-representation(s). If two non-keyword arguments are passed, assumes they represent a namespace/localname pair.

Parameters:
  • uri (string) – URI text, unless namespace is passed and localname is not, in which case this becomes the namespace.
  • namespace (string|URI) – Namespace part of the URI if localname is passed, otherwise this becomes the local name.
  • localname – Local part of the URI. Should only be used as a keyword argument and together with namespace.
Returns:

An URI object.

Return type:

URI

deleteAttributeDefinition(name)[source]

Delete an attribute definition.

Parameters:name – Attribute name.
deleteDuplicates(mode)[source]

Delete duplicate triples from the store.

Parameters:mode – can be “spo” (triples are duplicates if they have the same subject, predicate, and object, regardless of the graph) or “spog” (triples are duplicates if they have the same subject, predicate, object, and graph).

See also

Method getDuplicateStatements().

deleteFreeTextIndex(name)[source]

Delete a free-text index from the server.

Parameters:name (string) – Index name.
deleteMaterialized()[source]

Deletes all previously materialized triples. Returns the number of triples deleted.

deleteSpinFunction(uri)[source]
Deletes the Spin function at the given uri.
uri - Spin function identifier
deleteSpinMagicProperty(uri)[source]
Deletes the Spin magic property at the given uri.
uri - Spin magic property identifier
disableDuplicateSuppression()[source]

Disable duplicate suppression for this store. See https://franz.com/agraph/support/documentation/current/deleting-duplicate-triples.html

disableSubjectTriplesCache()[source]

Disable the subject triples cache (see enableSubjectTriplesCache()).

dropIndex(_type)[source]

Removes a specific type of index to the current set of triple indices.

Parameters:_type (string) – Index name (see listIndices()).
enableSubjectTriplesCache(size=None)[source]

Maintain a cache of size size that caches, for each accessed resource, quads where the resource appears in subject position.

This can accelerate the performance of certain types of queries.

Parameters:size (int) – The maximum number of subjects whose triples will be cached. Default is 100,000.
evalFreeTextSearch(pattern, infer=False, callback=None, limit=None, offset=None, index=None)[source]

Return a list of statements for the given free-text pattern search.

If no index is provided, all indices will be used.

Parameters:
evalInServer(code)[source]

Evaluate the Lisp code in the server.

You must have “eval” permissions to the store to use this feature.

evalJavaScript(code)[source]

Evaluate the JavaScript code in the server.

You must have “eval” permissions to the store to use this feature.

executeBooleanQuery(query, language=QueryLanguage.SPARQL)[source]

Prepare and immediately evaluate a query that returns a boolean.

Parameters:
  • query (str) – Query text.
  • language (QueryLanguage) – Query language, the default is SPARQL.
Returns:

Query result.

Return type:

bool

executeGraphQuery(query, language=QueryLanguage.SPARQL, output=None, output_format=RDFFormat.NQX: Extended N-Quads (with attributes))[source]

Prepare and immediately evaluate a query that returns RDF.

Parameters:
  • query (str) – Query text.
  • language (QueryLanguage) – Query language, the default is SPARQL.
  • output (str|file) – File path or a file-like object to write the result to.
  • output_format (RDFFormat) – Serialization format for output.
Returns:

Query result, or None if output is used.

Return type:

RepositoryResult|None

executeTupleQuery(query, language=QueryLanguage.SPARQL, output=None, output_format=RDFFormat.TABLE: Table)[source]

Prepare and immediately evaluate a query that returns tuples.

Parameters:
  • query (str) – Query text.
  • language (QueryLanguage) – Query language, the default is SPARQL.
  • output (str|file) – File path or a file-like object to write the result to.
  • output_format (RDFFormat) – Serialization format for output.
Returns:

Query result, or None if output is used.

Return type:

TupleQueryResult

executeUpdate(query)[source]

Prepare and immediately evaluate a SPARQL update query.

Parameters:query (str) – Query text.
Returns:Query result (true iff the store has been modified).
Return type:bool
export(handler, contexts='ALL_CONTEXTS')[source]

Export all explicit statements in the specified contexts to a file.

Deprecated since version 4.14.1: Use saveResponse() instead.

Parameters:
  • handler (RDFWriter) – An RDFWriter instance describing the target file and data format.
  • contexts (Iterable[string|URI]|string|URI) – A context or list of contexts (default: all contexts).
exportStatements(subj, pred, obj, includeInferred, handler, contexts='ALL_CONTEXTS')[source]

Export statements to a file.

Deprecated since version 4.14.1: Use saveResponse() instead.

Parameters:
  • subj (Value) – Subject or None (i.e. no filtering on subject).
  • pred (URI) – Predicate or None (i.e. no filtering on predicate).
  • obj (Value) – Object or None (i.e. no filtering on object).
  • includeInferred (bool) – If True inferred triples will be included in the output. The default is False.
  • handler (RDFWriter) – An RDFWriter instance describing the target file and data format.
  • contexts (Iterable[string|URI]|string|URI) – A context or list of contexts (default: all contexts).
getAddCommitSize()[source]

Get the current value of add_commit_size. :return: Value of add_commit_size.

getAttributeDefinition(name)[source]

Get the definition of a given attribute.

Return None if there is no such attribute.

Parameters:name – Attribute name.
Returns:A definition object.
Return type:AttributeDefinition
getAttributeDefinitions()[source]

Get a list of all attribute definitions from the server.

Returns:A list of attribute definition objects.
Return type:list[AttributeDefinition]
getAttributeFilter()[source]

Get the current static attribute filter.

The result will be a string, not an AttributeFilter object.

Returns:The filter or none (if there is no static filter).
Return type:str
getContextIDs()[source]

Return a list of context resources, one for each context referenced by a quad in the triple store. Note that the default context will not be included in the result.

Returns:A list of contexts (as URI objects).
Return type:list[URI]
getDuplicateStatements(mode)[source]

Return all duplicates in the store.

Parameters:mode – can be “spo” (triples are duplicates if they have the same subject, predicate, and object, regardless of the graph) or “spog” (triples are duplicates if they have the same subject, predicate, object, and graph).
Returns:An iterator over duplicate statements.
Return type:RepositoryResult
getDuplicateSuppressionPolicy()[source]

Return the duplicate suppression policy used by the store. See https://franz.com/agraph/support/documentation/current/deleting-duplicate-triples.html

Returns:Duplicate suppression policy: “spo”, “spog” or None.
Return type:str
getFreeTextIndexConfiguration(name)[source]

Get the current settings of a free-text index.

The result will be a dictionary where keys are parameter names as used in createFreeTextIndex().

Parameters:name (string) – Index name.
Returns:A dictionary with configuration data, keys are argument names from createFreeTextIndex().
Return type:dict
getGeoType()[source]

Get the current geospatial coordinate system.

Returns:A coordinate system.
Return type:GeoType
getNamespace(prefix)[source]

Get the namespace that is associated with the specified prefix, if any.

Parameters:prefix – Namespace prefix.
Returns:Namespace URI.
Raises:RequestError – if there is no namespace with given prefix.
getNamespaces()[source]

Get all declared prefix/namespace pairs.

The result is a dictionary mapping prefixes to namespace URIs.

Returns:A dictionary of namespaces.
Return type:dict[string,string]
getSpec()[source]

Get the session specification string for this repository.

Returns:Spec string suitable for use with openSession().
getSpinFunction(uri)[source]
Gets the string of the function for the given uri.
uri - Spin function identifier
getSpinMagicProperty(uri)[source]
Get the spin magic property for the uri
uri - spin magic property identifier
getStatements(subject=None, predicate=None, object=None, contexts='ALL_CONTEXTS', includeInferred=False, limit=None, offset=None, tripleIDs=False, output=None, output_format=RDFFormat.NQX: Extended N-Quads (with attributes))[source]

Get all statements with a specific subject, predicate and/or object from the repository. The result is optionally restricted to the specified set of named contexts (graphs).

Return a RepositoryResult object that can be used to iterate over the resulting statements and filter out duplicates if desired. Alternatively one can write the results to a file or stream using the output parameter.

Parameters:
  • subject (Value) – Subject value or None (no subject filtering).
  • predicate (URI) – Predicate value or None (no predicatefiltering).
  • object (Value) – Object value or None (no object filtering).
  • contexts (URI|string|Iterable[URI|string]) – An optional list of graphs to retrieve the statements from. By default statements are taken from all graphs.
  • includeInferred (bool) – If True, include triples inferred through RDFS++ reasoning. The default is False.
  • limit (int) – Max number of statements to retrieve (optional).
  • offset (int) – Used in conjunction with limit to return results starting from the nth statement.
  • tripleIDs – If True the id field will be filled in the returned statements.
  • output (str|file) – File path or a file-like object to write the result to.
  • output_format (RDFFormat) – Serialization format for output.
  • include_attributes (bool) – If true the returned statements will include triple attributes. The default is false.
Returns:

An iterator over the resulting statements or None (if output is used).

Return type:

RepositoryResult

getStatementsById(ids, output=None, output_format=RDFFormat.NQX: Extended N-Quads (with attributes))[source]

Return all statements whose triple ID matches an ID in the list ‘ids’.

Parameters:
  • ids (Iterable[int]) – List of statement ids.
  • output (str|file) – File path or a file-like object to write the result to.
  • output_format (RDFFormat) – Serialization format for output.
Returns:

An iterator over requested statements or None (if output is used).

Return type:

RepositoryResult

getSubjectTriplesCacheSize()[source]

Return the current size of the subject triples cache.

See also

enablerSubjectTriplesCache()

getTransactionSettings()[source]

Return distributed transaction settings currently in force.

Returns:A settings object.
Return type:TransactionSettings
getUserAttributes()[source]

Get the current set of user attributes.

Returns:A dictionary mapping attribute names to values (or lists of values).
Return type:dict[str, str|list[str]]
getValueFactory()[source]

Get the ValueFactory associated with this repository.

Note that it is recommended to use methods defined in RepositoryConnection instead of a value factory. The latter is only provided for RDF4J compatibility.

Returns:A value factory.
Return type:ValueFactory
isEmpty()[source]

Return True if this repository does not contain any (explicit) statements.

listEncodedIdPrefixes()[source]

Lists all encoded id prefixes.

See: https://franz.com/agraph/support/documentation/current/encoded-ids.html

listFreeTextIndices()[source]

Get the names of currently defined free-text indices.

Returns:List of index names.
Return type:list[string]
listIndices()[source]

Return the list of the current set of triple indices.

Index names are strings such as "gospi", "spogi" etc. Use listValidIndices() to get the list of index names supported by the server.

Returns:List of index names (see listValidIndices()).
Return type:list[string]
listSpinFunctions()[source]

Returns a list of defined SPIN function.

listSpinMagicProperties()[source]

Returns a list of defined SPIN magic properties function.

listValidIndices()[source]

Return the list of valid index names.

Returns:List of index names.
Return type:list[string]
loadRules(filename, language=QueryLanguage.PROLOG)[source]

Add Prolog rules from file to the current session.

Note that this only works with a dedicated session.

Parameters:
  • filename (string) – Path to the file containing Prolog rules.
  • language – Ignored.
materializeEntailed(_with=None, without=None, useTypeSubproperty=False, commit=100000)[source]

Call to materialize entailed triples to enable reasoning queries without the dynamic query-time reasoner. Returns the number of triples added.

_with and without can be either a single string or a list of strings denoting rules beyond rdfs++ you wish to use. See the documentation for the current set, but “same-as”, “restriction”, “values-from”, “class”, and “property” are examples.

useTypeSubproperty tells the materializer to prefer using types that are rdfs:subPropertyOf rdf:type rather than rdf:type directly.

commit indicates the number of triples per commit for the materializer.

modifyFreeTextIndex(name, predicates=None, indexLiterals=None, indexResources=None, indexFields=None, minimumWordSize=None, stopWords=None, wordFilters=None, reIndex=None, innerChars=None, borderChars=None, tokenizer=None)[source]

Modify parameters of a free-text index.

Parameters:
  • name (string) – Name of the index to be modified.
  • predicates (list[string|URI]) – A list of predicates to be indexed. If not given all triples will be indexed regardless of predicate.
  • indexLiterals (bool|list[URI]) – Determines which literals to index. It can be``True`` (the default), False, or a list of resources, indicating the literal types that should be indexed.
  • indexResources (bool|string) – Determines which resources are indexed. It can be True, False (the default), or "short", to index only the part of resources after the last slash or hash character.
  • indexFields (list[string]) – List of triples fields to index. Can be any combination of "subject", "predicate", "object", and "graph". The default is ["object"].
  • minimumWordSize (int) – Determines the minimum size a word must have to be indexed. The default is 3.
  • stopWords (list[string]) – List of words that should not be indexed. When not given, a list of common English words is used.
  • wordFilters (list[string]) – List of normalizing filters used to process words before indexing. The list if supported filters can be found here: http://franz.com/agraph/support/documentation/current/text-index.html
  • innerChars (list[string]) –

    The character set to be used as the constituent characters of a word. Should be a list of character classes. Valid classes are:

    • ”alpha”`: All (unicode) alphabetic characters.
    • "digit": All base-10 digits.
    • "alphanumeric": All digits and alphabetic characters.
    • a single character
    • a range of characters: A single character, followed by a dash (-) character, followed by another single character.
  • borderChars (list[string]) – The character set to be used as the border characters of indexed words. Uses the same syntax as innerChars.
  • tokenizer (string) – Controls the way in which the text is plit into tokens. Can be either "default" or "japaense". Note that the japaense tokenizer ignores innerChars and borderChars.
namespace(prefix)[source]

Creates an object that allows for simple creation of URIs in given namespace. Attribute lookups on the returned object will produce URIs with the attribute name as localname. Indexing into the object or calling it like a function will have the same effect.

>>> from franz.openrdf.connect import ag_connect
>>> conn = ag_connect('repo')
>>> ex = conn.namespace('http://franz.com/example/')
>>> ex.foo
<http://franz.com/example/foo>
>>> ex['bar']
<http://franz.com/example/bar>
>>> ex('baz')
<http://franz.com/example/baz>
Parameters:prefix (str) – Prefix prepended to URIs created by the returned object.
Returns:An object that can be used to create URIs.
openSession(autocommit=False, lifetime=None, loadinitfile=False)[source]

Open a session.

It is not an error to call this when a session is already active on this connection, but no new session will be created (i.e. nested sessions are not supported).

See also

http://franz.com/agraph/support/documentation/current/http-protocol.html#sessions
More detailed explanation of session-related concepts in the HTTP API reference.
Parameters:
  • autocommit (bool) – if True, commits are done on each request, otherwise you will need to call commit() or rollback() as appropriate for your application. The default value is False.
  • lifetime (int) – Time (in seconds) before the session expires when idle. Note that the client maintains a thread that pings the session before this happens. The maximum acceptable value is 21600 (6 hours). When the value is None (the default) the lifetime is set to 300 seconds (5 minutes).
  • loadinitfile (bool) – if True then the current initfile will be loaded for you when the session starts. The default is False.
optimizeIndices(level=None, wait=None)[source]

Optimize indices.

Please see documentation for argument values and meanings:

https://franz.com/agraph/support/documentation/current/triple-index.html#optimize

prepareBooleanQuery(queryLanguage=QueryLanguage.SPARQL, query=None, baseURI=None, queryString=None)[source]

Parse query into a boolean query object which can be executed against the triple store.

Parameters:
  • queryLanguage (QueryLanguage) – Either QueryLanguage.SPARQL or QueryLanguage.PROLOG.
  • query (string) – The query string (must contain an ASK query).
  • baseURI (string|URI) – An optional base used to resolve relative URIs in the query.
  • queryString (string) – Legacy name of the query parameter.
Returns:

A query object.

Return type:

BooleanQuery

prepareGraphQuery(queryLanguage=QueryLanguage.SPARQL, query=None, baseURI=None, queryString=None)[source]

Parse query into a graph query object which can be executed against the triple store.

Parameters:
  • queryLanguage (QueryLanguage) – Either QueryLanguage.SPARQL or QueryLanguage.PROLOG.
  • query (string) – The query string (must be a``CONSTRUCT`` or DESCRIBE query).
  • baseURI (string|URI) – An optional base used to resolve relative URIs in the query.
  • queryString (string) – Legacy name of the query parameter.
Returns:

A query object.

Return type:

GraphQuery

prepareQuery(queryLanguage, queryString, baseURI=None)[source]

Embed ‘queryString’ into a query object which can be executed against the RDF storage.

prepareTupleQuery(queryLanguage=QueryLanguage.SPARQL, query=None, baseURI=None, queryString=None)[source]

Parse query into a tuple query object which can be executed against the triple stroe.

Parameters:
  • queryLanguage (QueryLanguage) – Either QueryLanguage.SPARQL or QueryLanguage.PROLOG.
  • query (string) – The query string (must contain a SELECT query).
  • baseURI (string|URI) – An optional base used to resolve relative URIs in the query.
  • queryString (string) – Legacy name of the query parameter.
Returns:

A query object.

Return type:

TupleQuery

prepareUpdate(queryLanguage=QueryLanguage.SPARQL, query=None, baseURI=None, queryString=None)[source]

Parse query into an update query object which can be executed against the triple store.

Parameters:
  • queryLanguage (QueryLanguage) – Either QueryLanguage.SPARQL or QueryLanguage.PROLOG.
  • query (string) – The query string (must contain an UPDATE query).
  • baseURI (string|URI) – An optional base used to resolve relative URIs in the query.
  • queryString (string) – Legacy name of the query parameter.
Returns:

A query object.

Return type:

UpdateQuery

putSpinFunction(uri, sparqlQuery, arguments)[source]
Adds a Spin function.
uri - Spin function identifier sparqlQuery - Spin function query text arguments - names of arguments in the sparqlQuery
putSpinMagicProperty(uri, sparqlQuery, arguments)[source]
Add a Spin magic property.
uri - Spin magic property identifier sparqlQuery arguments - names of arguments to the sparqlQuery - must contain the leading question mark
registerDatatypeMapping(predicate=None, datatype=None, nativeType=None)[source]

Register an inlined datatype.

See Repository.registerDatatypeMapping().

registerEncodedIdPrefix(prefix, format)[source]

Registers a single encoded prefix.

See: https://franz.com/agraph/support/documentation/current/encoded-ids.html

registerEncodedIdPrefixes(registrations)[source]

Registers multiple encoded prefixes. Any kind of iteratable collection of items with a prefix attribute and format attribute, or the prefix at index 0 and the format at index 1 will do (e.g. a list of tuples). Using PrefixFormat instances also works well.

See: https://franz.com/agraph/support/documentation/current/encoded-ids.html

registerNeighborMatrix(name, generator, group_uris, max_depth=2)[source]

Construct a neighbor matrix named name.

The generator named generator is applied to each URI in group_uris, computing edges to max depth max_depth.

Requires a dedicated session.

Parameters:
  • name (string) – Name that will be used to identify the matrix.
  • generator (string) – Name of the SNA generator used to compute the edges. See registerSNAGenerator().
  • group_uris (list[URI|string]) – Initial list of vertices from which the graph will be created.
  • max_depth (int) – Max distance from the initial vertices.
registerSNAGenerator(name, subjectOf=None, objectOf=None, undirected=None, generator_query=None)[source]

Create a new SNA generator named name. If one already exists with the same name - redefine it.

The edges traversed by the new generator can be defined in one of two ways:

  • Using three lists of predicates to define edges between subjects and objects of triples (subjectOf, objectOf, undirected).
  • Using a Prolog query (generator_query).

Requires a dedicated session.

Parameters:
  • name (string) – Name of the new/modified generator.
  • subjectOf (list[URI|string]) – Create object to subject edges for these predicates.
  • objectOf (list[URI|string]) – Create subject to object edges for these predicates.
  • undirected (list[URI|string]) – Create edges in both directions for these predicates.
  • generator_query – A Prolog query that generates neighbors given a start node ?node.
remove(arg0, arg1=None, arg2=None, contexts=None)[source]

Call removeTriples() or removeStatement().

Best practice is to avoid remove() and use removeTriples() or removeStatement() directly.

Note that context fields of statements passed to this method are ignored.

arg0 may be a Statement. If so, then arg1 and arg2 default to None.

arg0, arg1, and arg2 may be the subject, predicate and object of a triple.

Parameters:
  • arg0 (Statement|Value|Iterable[Statement]) – Either a Statement, a list of statements or the subject of a triple.
  • arg1 (URI) – Predicate of a triple.
  • arg2 (Value) – Object of a triple.
  • contexts (Iterable[URI|string]) – An optional list of graphs to remove triples from.
removeNamespace(prefix)[source]

Remove a namespace declaration by removing the association between a prefix and a namespace name.

Parameters:prefix (string) – Namespace prefix.
removeQuads(quads, ntriples=False)[source]

Remove enumerated quads from this repository. Each quad can be a list or a tuple of Value objects.

Parameters:
  • quads (Iterable[list[string|Value]|tuple[string|Value]]) – List of quads. Each element can be either a statement or a list or tuple of Value objects or strings.
  • ntriples (bool) – If True, parts of the quads are assumed to be strings in N-Triples format and are sent to the server without any conversion.
removeQuadsByID(tids)[source]

Remove all quads with matching IDs.

Parameters:tids (list[int]) – List of IDs to be removed.
removeStatement(statement, contexts=None)[source]

Remove the supplied statement from the specified contexts in the repository.

Parameters:
  • statement (Statement) – Statement to be removed. Note that the context field of this object will be ignored.
  • contexts (Iterable[URI|string]) – An optional list of graphs to remove the statement from.
removeTriples(subject, predicate, object, contexts='ALL_CONTEXTS')[source]

Remove the statement(s) with the specified subject, predicate and object from the repository, optionally restricted to the specified contexts.

Parameters:
  • subject (Value|None) – Subject of the triples to be removed.
  • predicate (URI|None) – Predicate of the triples to be removed.
  • object (Value|None) – Object of the triples to be removed.
  • contexts (Iterable[URI|string]|None) – An optional list of graphs to remove triples from.
rollback()[source]

Roll back changes on open session.

runAsUser(username=None)[source]

Only for use as a superuser during a session.

Runs requests on this connection as username.

None - the default - clears the setting.

saveResponse(fileobj, accept, raiseAll=False)[source]

Save the server response(s) for the call(s) within the with statement to fileobj, using accept for the response type requested.

Deprecated since version 100.0.1: Use getStatements(output=…) or evaluate(output=…) to export data.

Responses will be uncompressed and saved to fileobj, but not decoded. Therefore, the API called will likely error out shortly after the response is saved (which is okay because we really only want the side-effect of saving the response).

RequestError is always thrown on errors from the server. Other exceptions can be optionally raised with raiseAll=True.

You will only want to make only one conn call in the with statement unless you wrap each call in its own try/except.

Example:

with open(‘out’, ‘w’) as response:
with conn.saveResponse(response, ‘application/rdf+xml’):
conn.getStatements(None, None, None) # The response is written to response
session(autocommit=False, lifetime=None, loadinitfile=False)[source]

A session context manager for use with the with statement:

with conn.session():
    # Automatically calls openSession at block start
    # Do work
    # Automatically calls closeSession at block end
    # or in case of an exception.
Parameters:
  • autocommit (bool) – if True, commits are done on each request, otherwise you will need to call commit() or rollback() as appropriate for your application. The default value is False.
  • lifetime (int) – Time (in seconds) before the session expires when idle. Note that the client maintains a thread that ping the session before this happens.
  • loadinitfile (bool) – if True then the current initfile will be loaded for you when the session starts. The default is False.
setAddCommitSize(triple_count)[source]

Set the value of add_commit_size. :param triple_count: Value of add_commit_size.

setAttributeDefinition(attr_def)[source]

Define or modify an attribute definition.

Parameters:attr_def – Attribute definition.
setAttributeFilter(attribute_filter)[source]

Set the static attribute filter.

Parameters:attribute_filter (AttributeFilter|str) – The filter - either an AttributeFilter or a string.
setDuplicateSuppressionPolicy(mode)[source]

Set the duplicate suppression policy used by the store. See https://franz.com/agraph/support/documentation/current/deleting-duplicate-triples.html

Parameters:mode (str) – Duplicate suppression policy: “spo”, “spog” or None (disable suppression).
setGeoType(geoType)[source]

Set the current geospatial coordinate system.

Parameters:geoType (GeoType) – The new coordinate system.
setNamespace(prefix, name)[source]

Define or redefine a namespace mapping in the repository.

Parameters:
  • prefix (string) – Namespace prefix.
  • name (string) – Namespace URI.
setTransactionSettings(settings=None, **kwargs)[source]

Change distributed transaction settings used by this connection.

The new settings can be described either by a TransactionSettings object or by passing individual parameters as keyword arguments. Argument names must match the fields of the TransactionSettings class.

If a settings object is passed all settings will be replaced. Keyword arguments will only affect specific parameters, any setting for which there is no corresponding keyword argument in the call will keep its current value.

If both types of arguments are passed they will be merged, with keyword arguments taking precedence over values from the settings object.

Parameters:
  • settings (TransactionSettings) – A settings object.
  • kwargs – Individual transaction parameters. See TransactionSettings for a list of valid names.
setUserAttributes(attributes)[source]

Set user attributes (used to filter the store during queries).

Parameters:attributes (dict[str, str|list[str]]) – A dictionary mapping attribute names to values. A value is either a string or a list of strings.
size(contexts='ALL_CONTEXTS')[source]

Returns the number of (explicit) statements that are in the specified contexts in this repository.

Parameters:contexts (Iterable[string|URI]) – List of contexts (graph URIs) to count the statements in. By default statements in all graphs will be counted.
temporaryTransactionSettings(settings=None, **kwargs)[source]

Create a context in which transaction settings of this connection are modified or replaced.

If a settings object is given as an argument it will replace all transaction settings. Keyword arguments may be used to modify individual transaction parameters without affecting other settings.

Here is how this method can be used to temporarily lower durability requirements while executing some operations:

with conn.temporaryTransactionSettings(durability='min'):
    # Durability is now 'min', other settings remain unchanged.
    # Perform some operations
    ...
    conn.commit()
# At this points durability will be restored to its original value.
Parameters:
  • settings (TransactionSettings) – A settings object.
  • kwargs – Individual transaction parameters. See TransactionSettings for a list of valid names.
Returns:

A context manager that takes care of changing and restroing distributed transaction settings.

temporaryUserAttributes(attributes)[source]

Set user attributes for the duration of a code block.

This method returns a context manager. It can be used like this:

with conn.temporaryUserAttributes({'access-level': 'low'}):
    conn.do_something()
Parameters:attributes (dict[str, str|list[str]]) – A dictionary mapping attribute names to values. A value is either a string or a list of strings.
Return type:ContextManager[None]
unregisterEncodedIdPrefix(prefix)[source]

Unregisters the specified encoded id prefix.

See: https://franz.com/agraph/support/documentation/current/encoded-ids.html

franz.openrdf.repository.repositoryconnection.attribute_definition_from_dict(item)[source]

franz.openrdf.repository.repositoryresult module

Module contents