# SPARQL extensions reference¶

This page describes functions that are not part of the W3C SPARQL specification but that are available for use to use in GraphDB.

## Mathematical function extensions¶

Beside the standard SPARQL functions operating on numbers, GraphDB offers several additional functions, allowing users to do more mathematical operations. These are implemented using Java’s Math class.

The prefix ofn: stands for the namespace <http://www.ontotext.com/sparql/functions/>.

Function

Description

xsd:double ofn:acos(numeric a)

The arccosine function. The input is in the range $$[-1, +1]$$. The output is in the range $$[0, \pi]$$ radians. See Math.acos(double).

Example: ofn:acos(0.5) = 1.0471975511965979

xsd:double ofn:asin(numeric a)

The arcsine function. The input is in the range $$[-1, +1]$$. The output is in the range $$[-\pi/2, \pi/2]$$ radians. See Math.asin(double).

Example: ofn:asin(0.5) = 0.5235987755982989

xsd:double ofn:atan(numeric a)

The arctangent function. The output is in the range $$(-\pi/2, \pi/2)$$ radians. See Math.atan(double).

Example: ofn:atan(1) = 0.7853981633974483

xsd:double ofn:atan2(numeric y, numeric x)

The double-argument arctangent function (the angle component of the conversion from rectangular coordinates to polar coordinates). The output is in the range $$[-\pi/2, \pi/2]$$ radians. See Math.atan2(double,double).

Example: ofn:atan2(1, 0) = 1.5707963267948966

xsd:double ofn:cbrt(numeric a)

The cubic root function. See Math.cbrt(double).

Example: ofn:cbrt(2) = 1.2599210498948732

xsd:double ofn:copySign(numeric magnitude, numeric sign)

Returns the first floating-point argument with the sign of the second floating-point argument. See Math.copySign(double,double).

Example: ofn:copySign(2, -7.5) = -2.0

xsd:double ofn:cos(numeric a)

The cosine function. The argument is in radians. See Math.cos(double).

Example: ofn:cos(1) = 0.5403023058681398

xsd:double ofn:cosh(numeric x).

The hyperbolic cosine function. See Math.cosh(double).

Example: ofn:cosh(1) = 1.543080634815244

xsd:double ofn:e()

Returns the double value that is closer than any other to $$e$$, the base of the natural logarithms. See Math.E.

Example: ofn:e() = 2.718281828459045

xsd:double ofn:exp(double a)

The exponent function, $$e^x$$. See Math.exp(double).

Example: ofn:exp(2) = 7.38905609893065

xsd:double ofn:expm1(numeric x)

Returns $$e^x - 1$$. See Math.expm1(double).

Example: ofn:expm1(3) = 19.085536923187668

xsd:double ofn:floorDiv(numeric x, numeric y)

Returns the largest (closest to positive infinity) int value (as a double number) that is less than or equal to the algebraic quotient. The arguments are implicitly cast to long. See Math.floorDiv(long,long).

Example: ofn:floorDiv(5, 2) = 2.0

xsd:double ofn:floorMod(numeric x, numeric y)

Returns the floor modulus (as a double number) of the arguments. The arguments are implicitly cast to long. See Math.floorMod(long,long).

Example: ofn:floorMod(10, 3) = 1.0

xsd:double ofn:getExponent(numeric d)

Returns the unbiased exponent used in the representation of a double. This means that we take n from the binary representation of x: $$x = 1 \times 2^n + \{1|0\} \times 2^{(n-1)} + ... + \{1|0\} \times 2^0$$, i.e., the power of the highest non-zero bit of the binary form of x. See Math.getExponent(double).

Example: ofn:getExponent(10) = 3.0

xsd:double ofn:hypot(numeric x, numeric y)

Returns $$sqrt(x^2 +y^2)$$ without intermediate overflow or underflow. See Math.hypot(double,double).

Example: ofn:hypot(3, 4) = 5.0

xsd:double ofn:IEEEremainder(numeric f1, numeric f2)

Computes the remainder operation on two arguments as prescribed by the IEEE 754 standard. See Math.IEEEremainder(double,double).

Example: ofn:IEEEremainder(3, 4) = -1.0

xsd:double ofn:log(numeric a)

The natural logarithm function. See Math.log(double).

Example: ofn:log(4) = 1.3862943611198906

xsd:double ofn:log10(numeric a).

The common (decimal) logarithm function. See Math.log10(double).

Example: ofn:log10(4) = 0.6020599913279624

xsd:double ofn:log1p(numeric x)

Returns the natural logarithm of the sum of the argument and 1. See Math.log1p(double).

Example: ofn:log1p(4) = 1.6094379124341003

xsd:double ofn:max(numeric a, numeric b)

The greater of two numbers. See Math.max(double,double).

Example: ofn:max(3, 5) = 5.0

xsd:double ofn:min(numeric a, numeric b)

The smaller of two numbers. See Math.min(double,double).

Example: ofn:min(3, 5) = 3.0

xsd:double ofn:nextAfter(numeric start, numeric direction)

Returns the floating-point number adjacent to the first argument in the direction of the second argument. See Math.nextAfter(double,double).

Example: ofn:nextAfter(2, -7) = 1.9999999999999998

xsd:double ofn:nextDown(numeric d)

Returns the floating-point value adjacent to d in the direction of negative infinity. See Math.nextDown(double).

Example: ofn:nextDown(2) = 1.9999999999999998

xsd:double ofn:nextUp(numeric d)

Returns the floating-point value adjacent to d in the direction of positive infinity. See Math.nextUp(double).

Example: ofn:nextUp(2) = 2.0000000000000004

xsd:double ofn:pi()

Returns the double value that is closer than any other to $$\pi$$, the ratio of the circumference of a circle to its diameter. See Math.PI.

Example: ofn:pi() = 3.141592653589793

xsd:double ofn:pow(numeric a, numeric b)

The power function. See Math.pow(double,double).

Example: ofn:pow(2, 3) = 8.0

xsd:double ofn:rint(numeric a)

Returns the double value that is closest in value to the argument and is equal to a mathematical integer. See Math.rint(double).

Example: ofn:rint(2.51) = 3.0

xsd:double ofn:scalb(numeric d, numeric scaleFactor)

Returns $$d \times 2^{scaleFactor}$$ rounded as if performed by a single correctly rounded floating-point multiply to a member of the double value set. See Math.scalb(double,int). scaleFactor can be negative, for example: ofn:scalb(3, -3) = 3 * 2^-3 = 0.375.

Example: ofn:scalb(3, 3) = 24.0

xsd:double ofn:signum(numeric d)

Returns the signum function of the argument; zero if the argument is zero, 1.0 if the argument is greater than zero, -1.0 if the argument is less than zero. See Math.signum(double).

Example: ofn:signum(-5) = -1.0

xsd:double ofn:sin(numeric a)

The sine function. The argument is in radians. See Math.sin(double).

Example: ofn:sin(2) = 0.9092974268256817

xsd:double ofn:sinh(numeric x)

The hyperbolic sine function. See Math.sinh(double).

Example: ofn:sinh(2) = 3.626860407847019

xsd:double ofn:sqrt(numeric a)

The square root function. See Math.sqrt(double).

Example: ofn:sqrt(2) = 1.4142135623730951d

xsd:double ofn:tan(numeric a)

The tangent function. The argument is in radians. See Math.tan(double).

Example: ofn:tan(1) = 1.5574077246549023

xsd:double ofn:tanh(numeric x)

The hyperbolic tangent function. See Math.tanh(double).

Example: ofn:tanh(1) = 0.7615941559557649

xsd:double ofn:toDegrees(numeric angrad)

Converts an angle measured in radians to an approximately equivalent angle measured in degrees. See Math.toDegrees(double).

Example: ofn:toDegrees(1) = 57.29577951308232

xsd:double ofn:toRadians(numeric angdeg)

Converts an angle measured in degrees to an approximately equivalent angle measured in radians. See Math.toRadians(double).

Example: ofn:toRadians(1) = 0.017453292519943295

xsd:double ofn:ulp(numeric d)

Returns the size of an ulp of the argument. An ulp, unit in the last place, of a double value is the positive distance between this floating-point value and the double value next larger in magnitude. Note that for non-NaN x, ulp(-x) == ulp(x). See Math.ulp(double).

Example: ofn:ulp(1) = 2.220446049250313E-16

GraphDB also supports several Jena ARQ simple mathematical function analogs. The prefix afn: stands for the namespace <http://jena.apache.org/ARQ/function#>. (See Jena SPARQL extensions for additional Jena functions supported by GraphDB.)

Function

Description

afn:min(num1, num2)

Return the minimum of two numbers.

afn:max(num1, num2)

Return the maximum of two numbers.

afn:pi()

The value of pi as an XSD double.

afn:e()

The value of e as an XSD double.

afn:sqrt(num)

The square root of num.

## Date and time function extensions¶

Beside the standard SPARQL functions related to date and time, GraphDB offers several additional functions, allowing users to do more with their temporal data.

The prefix ofn: stands for the namespace <http://www.ontotext.com/sparql/functions/>. For more information, refer to Time functions extensions.

Function

Description

xsd:long ofn:years-from-duration(xsd:duration dur)

Return the “years” part of the duration literal

xsd:long ofn:months-from-duration(xsd:duration dur)

Returns the “months” part of the duration literal

xsd:long ofn:days-from-duration(xsd:duration dur)

Returns the “days” part of the duration literal

xsd:long ofn:hours-from-duration(xsd:duration dur)

Returns the “hours” part of the duration literal

xsd:long ofn:minutes-from-duration(xsd:duration dur)

Returns the “minutes” part of the duration literal

xsd:long ofn:seconds-from-duration(xsd:duration dur)

Returns the “seconds” part of the duration literal

xsd:long ofn:millis-from-duration(xsd:duration dur)

Returns the “milliseconds” part of the duration literal

xsd:long ofn:asWeeks(xsd:duration dur)

Returns the duration of the period as weeks

xsd:long ofn:asDays(xsd:duration dur)

Returns the duration of the period as days

xsd:long ofn:asHours(xsd:duration dur)

Returns the duration of the period as hours

xsd:long ofn:asMinutes(xsd:duration dur)

Returns the duration of the period as minutes

xsd:long ofn:asSeconds(xsd:duration dur)

Returns the duration of the period as seconds

xsd:long ofn:asMillis(xsd:duration dur)

Returns the duration of the period as milliseconds

xsd:long ofn:weeksBetween(xsd:dateTime d1, xsd:dateTime d2)

Returns the duration between the two dates as weeks

xsd:long ofn:daysBetween(xsd:dateTime d1, xsd:dateTime d2)

Returns the duration between the two dates as days

xsd:long ofn:hoursBetween(xsd:dateTime d1, xsd:dateTime d2)

Returns the duration between the two dates as hours

xsd:long ofn:minutesBetween(xsd:dateTime d1, xsd:dateTime d2)

Returns the duration between the two dates as minutes

xsd:long ofn:secondsBetween(xsd:dateTime d1, xsd:dateTime d2)

Returns the duration between the two dates as seconds

xsd:long ofn:millisBetween(xsd:dateTime d1, xsd:dateTime d2)

Returns the duration between the two dates as milliseconds

## RDF-star extension functions¶

To avoid any parsing of an embedded triple, GraphDB introduces the following SPARQL functions:

Function

Description

xsd:boolean rdf:isTriple(variable var)

Checks if the variable var is bound to an embedded triple

iri rdf:subject(variable var)
iri rdf:predicate(variable var)
rdfTerm rdf:object(variable var)

Extracts the subject, predicate, or object from a variable bound to an embedded triple

rdf:Statement(iri subj, iri pred, rdfTerm obj)

Creates a new embedded statement with the provided values

See more about RDF-star and SPARQL-star syntax in the Syntax and examples section of this documentation’s RDF-star and SPARQL-star page.

## SPARQL functions vs magic predicates¶

Functions and magic predicates are denoted and used differently. Magic predicates are similar to how GraphDB plugins can interpret certain triple patterns, and unlike functions, they can return multiple values per call.

• Function calls take the form ex:function(arg1, arg2, ...), where all arguments must be bound. These are most commonly used in BIND, SELECT, FILTER, and ORDER BY clauses but may be used in other places as well.

• Magic predicates take the form subject ex:magicPredicate (arg1 arg2 ...). In some cases, the arguments are allowed to be unbound, and are then calculated from the subject. They are used as query triple patterns that have the magic predicate name in the middle, a parenthesized RDF list of arguments as the object, and the variable where the result should be bound (or a parenthesized list of such variables, in the case of certain OpenAI GPT extensions) as the subject.

## SPARQL SPIN functions¶

The following SPIN SPARQL functions and magic predicates are available in GraphDB. The prefix spif: stands for the namespace <http://spinrdf.org/spif#>.

SPIN functions that work on text use 0-based indexes, unlike SPARQL’s functions, which use 1-based indexes.

Function

Description

Dates

spif:parseDate(xsd:string date, xsd:string format)

Parses date using format with Java’s SimpleDateFormat

spif:dateFormat(xsd:dateTime date, xsd:string format)

Formats date using format with Java SimpleDateFormat

xsd:long spif:currentTimeMillis()

The current time in milliseconds since the epoch

xsd:long spif:timeMillis(xsd:dateTime date)

The time in milliseconds since the epoch for the provided argument

Numbers

numeric spif:mod(xsd:numeric dividend, xsd:numeric divisor)

Remainder from integer division

xsd:string spif:decimalFormat(numeric number, xsd:string format)

Formats number using format with Java’s DecimalFormat

xsd:double spif:random()

Calls Java’s Math.random()

Strings

xsd:string spif:trim(string str)

Calls String.trim()

spif:generateUUID()

UUID generation as a literal. Same as SPARQL’s STRUUID().

spif:cast(literal value, iri type)

Same as SPARQL’s STRDT(STR(value), type). Does not do validation either.

xsd:int spif:indexOf(string str, string substr)

Position of first occurrence of a substring.

Note that SPIN functions that work on text use 0-based indexes, unlike SPARQL’s functions, which use 1-based indexes.

xsd:int spif:lastIndexOf(string str, string substr)

Position of last occurrence of a substring.

Note that SPIN functions that work on text use 0-based indexes, unlike SPARQL’s functions, which use 1-based indexes.

xsd:string spif:buildString(string template, arguments…)

Builds a literal from a template, e.g. “foo {?2} bar {?1}” where {?2} will be replaced with second argument and {?1} will be replaced with the first argument after the template.

xsd:string spif:replaceAll(string str, xsd:string regexp, xsd:string flags)

Calls Java String.replaceAll, same as SPARQL’s REPLACE().

xsd:string spif:unCamelCase(string str)

Converts camel-cased string to non-camel case string with spaces

xsd:string spif:upperCase(string str)

Converts to upper case, similar to SPARQL’s UCASE() but disregarding the language tag from the input string

xsd:string spif:lowerCase(string str)

Converts to lower case, similar to SPARQL’s LCASE() but disregarding the language tag from the input string

xsd:string spif:titleCase(string str)

Converts to title case (each word starts with a capital). You can use this function to convert a multi-word string to string to CamelCase as suitable for a class name as follows: replace(titleCase(?x)," ",""). CamelCase is a convention that uses leading uppercase instead of space to delineate words. See spif:unCamelCase() for the opposite operation.

xsd:string spif:lowerTitleCase(string str)

Converts to lower title case (each but the first word starts with a capital. You can use this function to convert a multi-word string to camelCase as suitable for a property as follows: replace(lowerTitleCase(?x)," ",""). CamelCase is a convention that uses leading uppercase instead of space to delineate words. See spif:unCamelCase() for the opposite operation.

IRIs

xsd:string spif:encodeURL(string str)

Calls java.net.URLEncoder.encode, similar to SPARQL’s ENCODE_FOR_URI() but not the same

xsd:string spif:decodeURL(string str)

Calls java.net.URLEncoder.decode

iri spif:buildURI(string template, arguments…)

Builds a URI from a template, e.g. “<urn:{?1}/{?2}>” where {?2} will be replaced with second argument and {?1} will be replaced with the first argument after the template. The template must begin with < and end with >

xsd:boolean spif:isValidURI(string str)

According to some standards, note that it allows spaces too

Functions

rdfTerm spif:invoke(iri function, arguments…)

Invokes a function indirectly (supplied as an IRI) with the provided arguments

xsd:boolean spif:canInvoke(iri function, arguments…)

Checks if the given function can be invoked with the given arguments

There are three magic predicates: spif:split, spif:for, and spif:foreach.

Predicate

Description

?result spif:split (?string ?regex)

Takes two arguments: a string to split and a regex to split on. The current implementation uses Java’s String.split() method.

The following query splits the ?input string at the commas and returns three rows, with the ?name value being “Marion”, then “Suess”, then “Green” in those rows:

PREFIX spif: <http://spinrdf.org/spif#>

SELECT ?name WHERE {
BIND(str("Marion,Suess,Green") as ?input)
?name spif:split (?input ",") .
}


?result spif:for (?start ?end)

Generates bindings from a given start integer value to another given end integer value.

The following query returns three rows, with the variable ?result having the value 6 in the first row, 7 in the second, and 8 in the third:

PREFIX spif: <http://spinrdf.org/spif#>

SELECT ?result WHERE {
?result spif:for (6 8)
}


?result spif:foreach (?arg1 ?arg2 …)

Generates bindings for the given arguments arg1, arg2 and so on. They can be of any type.

The following query returns three rows, with each row showing ?result bound to one of the arguments being passed:

PREFIX spif: <http://spinrdf.org/spif#>
PREFIX ex:   <http://www.example.com/ns/>

SELECT ?result WHERE {
?result spif:foreach (ex:some-uri "some string" 23.7)
}


## RDF list function extensions¶

GraphDB supports the below Jena list function analogs.

The prefix list: stands for the namespace <http://jena.apache.org/ARQ/list#>.

Function

Description

list list:member member

Membership of an RDF List (RDF Collection). Currently in GraphDB, if list is not bound or a constant, an error will be thrown; else evaluate for the list in the variable list. If member is a variable, generate solutions with member bound to each element of list. If member is bound or a constant expression, test to see if it is a member of list.

list list:index (index member)

Index of an RDF List (RDF Collection). Currently in GraphDB, if list is not bound or a constant, an error will be thrown; else evaluate for one particular list. The object is a list pair, either element can be bound, unbound or a fixed node. Unbound variables in the object list are bound by the property function.

list list:length length

Length of an RDF List (RDF Collection). Currently in GraphDB, if list is not bound or a constant, an error will be thrown; else evaluate for one particular list. The object is tested against or bound to the length of the list.

Note

The Jena behavior is that if list is not bound or a constant, the function finds and iterates all lists in the graph (can be slow). As mentioned above, currently, GraphDB does not provide support for unbound list. Support for it will be added with the coming releases.

## Aggregation function extensions¶

GraphDB supports the below Jena ARQ aggregate function analogs, which are modeled after the corresponding SQL aggregate functions.

The prefix agg: stands for the namespace <http://jena.apache.org/ARQ/function/aggregate#>.

• agg:stdev

• agg:stdev_samp

• agg:stdev_pop

• agg:variance

• agg:var_samp

• agg:var_pop

The stdev_pop() and stdev_samp() functions compute the population standard deviation and sample standard deviation, respectively, of the input values. (stdev() is an alias for stdev_samp()) Both functions evaluate all input rows matched by the query. The difference is that stdev_samp() is scaled by 1/(N-1) while stdev_pop() is scaled by 1/N.

The var_samp() and var_pop() functions compute the sample variance and population variance, respectively, of the input values. (variance() is an alias for variance_samp()) Both functions evaluate all input rows matched by the query. The difference is that variance_samp() is scaled by 1/(N-1) while variance_pop() is scaled by 1/N.

## GeoSPARQL functions¶

The following functions are defined by the GeoSPARQL standard. For more information, refer to OGC GeoSPARQL - A Geographic Query Language for RDF Data. The prefix geof: stands for the namespace <http://www.opengis.net/def/function/geosparql/>.

The type geomLiteral serves as a placeholder for any GeoSPARQL literal that describes a geometry. GraphDB supports WKT (datatype geo:wktLiteral) and GML (datatype geo:gmlLiteral).

Function

Description

xsd:double geof:distance(geomLiteral geom1, geomLiteral geom2, iri units)

Returns the shortest distance in units between any two Points in the two geometric objects as calculated in the spatial reference system of geom1. See the list following this table for potential unit values to pass as the iri parameter.

geomLiteral geof:buffer(geomLiteral geom, xsd:double radius, iri units)

This function returns a geometric object that represents all Points whose distance from geom1 is less than or equal to the radius measured in units. Calculations are in the spatial reference system of geom1.

geomLiteral geof:convexHull(geomLiteral geom1)

This function returns a geometric object that represents all Points in the convex hull of geom1. Calculations are in the spatial reference system of geom1.

geomLiteral geof:intersection(geomLiteral geom1, geomLiteral geom2)

This function returns a geometric object that represents all Points in the intersection of geom1 with geom2. Calculations are in the spatial reference system of geom1.

geomLiteral geof:union(geomLiteral geom1, geomLiteral geom2)

This function returns a geometric object that represents all Points in the union of geom1 with geom2. Calculations are in the spatial reference system of geom1.

geomLiteral geof:difference(geomLiteral geom1, geomLiteral geom2)

This function returns a geometric object that represents all Points in the set difference of geom1 with geom2. Calculations are in the spatial reference system of geom1.

geomLiteral geof:symDifference(geomLiteral geom1, geomLiteral geom2)

This function returns a geometric object that represents all Points in the set symmetric difference of geom1 with geom2. Calculations are in the spatial reference system of geom1.

geomLiteral geof:envelope(geomLiteral geom1)

This function returns the minimum bounding box of geom1. Calculations are in the spatial reference system of geom1.

geomLiteral geof:boundary(geomLiteral geom1)

This function returns the closure of the boundary of geom1. Calculations are in the spatial reference system of geom1.

iri geof:getSRID(geomLiteral geom)

Returns the spatial reference system URI for geom.

xsd:boolean geof:relate(geomLiteral geom1, geomLiteral geom2, xsd:string matrix)

Returns true if the spatial relationship between geom1 and geom2 corresponds to one with acceptable values for the specified pattern-matrix. Otherwise, this function returns false. Pattern-matrix represents a DE-9IM intersection pattern consisting of T (true) and F (false) values. The spatial reference system for geom1 is used for spatial calculations.

xsd:boolean geof:sfEquals(geomLiteral geom1, geomLiteral geom2)

DE-9IM intersection pattern: (TFFFTFFFT)

xsd:boolean geof:sfDisjoint(geomLiteral geom1, geomLiteral geom2)

DE-9IM intersection pattern: (FF*FF****)

xsd:boolean geof:sfIntersects(geomLiteral geom1, geomLiteral geom2)

DE-9IM intersection pattern: (T******** *T******* ***T***** ****T****)

xsd:boolean geof:sfTouches(geomLiteral geom1, geomLiteral geom2)

DE-9IM intersection pattern: (FT******* F**T***** F***T****)

xsd:boolean geof:sfCrosses(geomLiteral geom1, geomLiteral geom2)

DE-9IM intersection pattern: (T*T***T**) for P/L, P/A, L/A; (0*T***T**) for L/L

xsd:boolean geof:sfWithin(geomLiteral geom1, geomLiteral geom2)

DE-9IM intersection pattern: (T*F**F***)

xsd:boolean geof:sfContains(geomLiteral geom1, geomLiteral geom2)

DE-9IM intersection pattern: (T*****FF*)

xsd:boolean geof:sfOverlaps(geomLiteral geom1, geomLiteral geom2)

DE-9IM intersection pattern: (T*T***T**) for A/A, P/P; (1*T***T**) for L/L

xsd:boolean geof:ehEquals(geomLiteral geom1, geomLiteral geom2)

DE-9IM intersection pattern: (TFFFTFFFT)

xsd:boolean geof:ehDisjoint(geomLiteral geom1, geomLiteral geom2)

DE-9IM intersection pattern: (FF*FF****)

xsd:boolean geof:ehMeet(geomLiteral geom1, geomLiteral geom2)

DE-9IM intersection pattern: (FT******* F**T***** F***T****)

xsd:boolean geof:ehOverlap(geomLiteral geom1, geomLiteral geom2)

DE-9IM intersection pattern: (T*T***T**)

xsd:boolean geof:ehCovers(geomLiteral geom1, geomLiteral geom2)

DE-9IM intersection pattern: (T*TFT*FF*)

xsd:boolean geof:ehCoveredBy(geomLiteral geom1, geomLiteral geom2)

DE-9IM intersection pattern: (TFF*TFT**)

xsd:boolean geof:ehInside(geomLiteral geom1, geomLiteral geom2)

DE-9IM intersection pattern: (TFF*FFT**)

xsd:boolean geof:ehContains(geomLiteral geom1, geomLiteral geom2)

DE-9IM intersection pattern: (T*TFF*FF*)

xsd:boolean geof:rcc8eq(geomLiteral geom1, geomLiteral geom2)

DE-9IM intersection pattern: (TFFFTFFFT)

xsd:boolean geof:rcc8dc(geomLiteral geom1, geomLiteral geom2)

DE-9IM intersection pattern: (FFTFFTTTT)

xsd:boolean geof:rcc8ec(geomLiteral geom1, geomLiteral geom2)

DE-9IM intersection pattern: (FFTFTTTTT)

xsd:boolean geof:rcc8po(geomLiteral geom1, geomLiteral geom2)

DE-9IM intersection pattern: (TTTTTTTTT)

xsd:boolean geof:rcc8tppi(geomLiteral geom1, geomLiteral geom2)

DE-9IM intersection pattern: (TTTFTTFFT)

xsd:Boolean geof:rcc8tpp(geomLiteral geom1, geomLiteral geom2)

DE-9IM intersection pattern: (TFFTTFTTT)

xsd:boolean geof:rcc8ntpp(geomLiteral geom1, geomLiteral geom2)

DE-9IM intersection pattern: (TFFTFFTTT)

xsd:boolean geof:rcc8ntppi(geomLiteral geom1, geomLiteral geom2)

DE-9IM intersection pattern: (TTTFFTFFT)

The following are potential geof:distance unit values:

• http://www.opengis.net/def/uom/OGC/1.0/degree

• http://www.opengis.net/def/uom/OGC/1.0/GridSpacing

• http://www.opengis.net/def/uom/OGC/1.0/metre

• http://www.opengis.net/def/uom/OGC/1.0/unity

### GeoSPARQL extension functions¶

On top of the standard GeoSPARQL functions, GraphDB adds a few useful extensions based on the USeekM library. The prefix geoext: stands for the namespace <http://rdf.useekm.com/ext#>.

The types geo:Geometry, geo:Point, etc. refer to GeoSPARQL types in the http://www.opengis.net/ont/geosparql# namespace.

See more about GraphDB’s GeoSPARQL extensions in the GeoSPARQL support section of this documentation.

 Function Description xsd:double geoext:area(geomLiteral g) Calculates the area of the surface of the geometry. geomLiteral geoext:closestPoint(geomLiteral g1, geomLiteral g2) For two given geometries, computes the point on the first geometry that is closest to the second geometry. xsd:boolean geoext:containsProperly(geomLiteral g1, geomLiteral g2) Tests if the first geometry properly contains the second geometry. Geom1 contains properly geom2 if all geom1 contains geom2 and the boundaries of the two geometries do not intersect. xsd:boolean geoext:coveredBy(geomLiteral g1, geomLiteral g2) Tests if the first geometry is covered by the second geometry. Geom1 is covered by geom2 if every point of geom1 is a point of geom2. xsd:boolean geoext:covers(geomLiteral g1, geomLiteral g2) Tests if the first geometry covers the second geometry. Geom1 covers geom2 if every point of geom2 is a point of geom1. xsd:double geoext:hausdorffDistance(geomLiteral g1, geomLiteral g2) Measures the degree of similarity between two geometries. The measure is normalized to lie in the range [0, 1]. Higher measures indicate a greater degree of similarity. geo:Line geoext:shortestLine(geomLiteral g1, geomLiteral g2) Computes the shortest line between two geometries. Returns it as a LineString object. geomLiteral geoext:simplify(geomLiteral g, double d) Given a maximum deviation from the curve, computes a simplified version of the given geometry using the Douglas-Peuker algorithm. geomLiteral geoext:simplifyPreserveTopology(geomLiteral g, double d) Given a maximum deviation from the curve, computes a simplified version of the given geometry using the Douglas-Peuker algorithm. Will avoid creating derived geometries (polygons in particular) that are invalid. xsd:boolean geoext:isValid(geomLiteral g) Checks whether the input geometry is a valid geometry.

## Geospatial extension functions¶

At present, there is just one SPARQL extension function. The prefix omgeo: stands for the namespace <http://www.ontotext.com/owlim/geo#>.

Function

Description

xsd:double omgeo:distance(numeric lat1, numeric long1, numeric lat2, numeric long2)

Computes the distance between two points in kilometers and can be used in FILTER and ORDER BY clauses.

Latitude is limited to the range -90 (South) to +90 (North). Longitude is limited to the range -180 (West) to +180 (East).

See more about GraphDB’s geospatial extension functions.

## Jena SPARQL extensions¶

Below are several Jena function analogs supported by GraphDB. (See Mathematical function extensions for additional Jena math functions that GraphDB supports.)

The prefix afn: stands for the namespace <http://jena.apache.org/ARQ/function#>.

Function

Description

iri apf:splitIRI (namespace  localname)
iri apf:splitURI (namespace  localname)

Split the IRI or URI into namespace (an IRI) and local name (a string). Compare if given values or bound variables, otherwise set the variable. The object is a list with 2 elements. splitURI is a synonym.

var apf:concat (arg arg …)

Concatenate the arguments in the object list as strings, and assign to var.

var apf:strSplit (arg arg)

Split a string and return a binding for each result. The subject variable should be unbound. The first argument to the object list is the string to be split. The second argument to the object list is a regular expression by which to split the string. The subject var is bound for each result of the split, and each result has the whitespace trimmed from it.

afn:bnode(?x)

Return the blank node label if ?x is a blank node.

afn:localname(?x)

The local name of ?x.

afn:namespace(?x)

The namespace of ?x.

afn:sprintf(format, v1, v2, …)

Make a string from the format string and the RDF terms.

afn:substr(string, startIndex [,endIndex])

Substring, Java style using startIndex and endIndex.

afn:substring

Synonym for afn:substr.

afn:strjoin(sep, string …)

Concatenate given strings, using sep as a separator.

afn:sha1sum(resource)

Calculate the SHA1 checksum of a literal or URI.

afn:now()

Current time. (Actually, a fixed moment of the current query execution — see the standard function NOW() for details.)

## Time functions extensions¶

Beside the standard SPARQL functions related to time, GraphDB offers several additional functions, allowing users to do more with their time data. Those are implemented within the same namespace as standard math functions, <http://www.ontotext.com/sparql/functions/>. The default prefix for the functions is ofn.

### Period extraction functions¶

The first group of functions is related to accessing particular parts of standard duration literals. For example, the expression 2019-03-24T22:12:29.183+02:00" - "2019-04-19T02:42:28.182+02:00" will produce the following duration literal: -P0Y0M25DT4H29M58.999S. It is possible to parse the result and obtain the proper parts of it - for example, “25 days”, “4” hours, or more discrete time units. However, instead of having to do this manually, GraphDB offers functions that perform the computations at the engine level. The functions take a period as input and output xsd:long.

Note

The functions described here perform simple extractions, rather than computing the periods. For example, if you have 40 days in the duration literal, but no months, i.e., P0Y0M40DT4H29M58.999S, a months-from-duration extraction will not return 1 months.

The following table describes the functions that are implemented and gives example results, assuming the literal -P0Y0M25DT4H29M58.999S is passed to them:

Function | Description

Expected return value

ofn:years-from-duration | Return the “years” part of the duration literal

0

ofn:months-from-duration

Returns the “months” part of the duration literal

0

ofn:days-from-duration

Returns the “days” part of the duration literal

25

ofn:hours-from-duration

Returns the “hours” part of the duration literal

4

ofn:minutes-from-duration

Returns the “minutes” part of the duration literal

29

ofn:seconds-from-duration

Returns the “seconds” part of the duration literal

58

ofn:millis-from-duration

Returns the “milliseconds” part of the duration literal

999

An example query using a function from this group would be:

PREFIX xsd:<http://www.w3.org/2001/XMLSchema#>
PREFIX ofn:<http://www.ontotext.com/sparql/functions/>
SELECT ?result {
bind (ofn:millis-from-duration("-P0Y0M25DT4H29M58.999S"^^xsd:dayTimeDuration) as ?result)
}


### Period transformation functions¶

The second group of functions is related to transforming a standard duration literal. This reduces the need for performing mathematical transformations on the input date. The functions take a period as input and output xsd:long.

Note

The transformation is performed with no fractional components. For example, if transformed, the duration literal we used previously, -P0Y0M25DT4H29M58.999S will yield 25 days, rather than 25.19 days.

The following table describes the functions that are implemented and gives example results, assuming the literal -P0Y0M25DT4H29M58.999S is passed to them. Note that the return values are negative since the period is negative:

Function

Description

Expected return value

ofn:asWeeks

Returns the duration of the period as weeks

-3

ofn:asDays

Returns the duration of the period as days

-25

ofn:asHours

Returns the duration of the period as hours

-604

ofn:asMinutes

Returns the duration of the period as minutes

-36269

ofn:asSeconds

Returns the duration of the period as seconds

-2176198

ofn:asMillis

Returns the duration of the period as milliseconds

-2176198999

An example query using a function from this group would be:

PREFIX xsd:<http://www.w3.org/2001/XMLSchema#>
PREFIX ofn:<http://www.ontotext.com/sparql/functions/>
SELECT ?result {
bind (ofn:asMillis("-P0Y0M25DT4H29M58.999S"^^xsd:dayTimeDuration) as ?result)
}


### Durations expressed in certain units¶

The third group of functions eliminates the need for computing a difference between two dates when a transformation will be necessary, essentially combining the mathematical operation of subtracting two dates with a transformation. It is more efficient than performing an explicit mathematical operation between two date literals, for example: "2019-03-24T22:12:29.183+02:00" - "2019-04-19T02:42:28.182+02:00" and then using a transformation function. The functions take two dates as input and output integer literals.

Note

Regular SPARQL subtraction can return negative values, as evidenced by the negative duration literal used in the example. However, comparisons are only positive. So, comparison isn’t an exact match for a subtraction followed by transformation. If one of the timestamps has timezone but the other does not, the result is ill-defined.

The following table describes the functions that are implemented and gives example results, assuming the date literals 2019-03-24T22:12:29.183+02:00" and "2019-04-19T02:42:28.182+02:00" are passed to them. Note that the return values are positive:

Function

Description

Expected return value

ofn:weeksBetween

Returns the duration between the two dates as weeks

3

ofn:daysBetween

Returns the duration between the two dates as days

25

ofn:hoursBetween

Returns the duration between the two dates as hours

604

ofn:minutesBetween

Returns the duration between the two dates as minutes

36269

ofn:secondsBetween

Returns the duration between the two dates as seconds

2176198

ofn:millisBetween

Returns the duration between the two dates as milliseconds

2176198999

An example query using a function from this group would be:

PREFIX xsd:<http://www.w3.org/2001/XMLSchema#>
PREFIX ofn:<http://www.ontotext.com/sparql/functions/>
SELECT ?result {
bind (ofn:millisBetween("2019-03-24T22:12:29.183+02:00"^^xsd:dateTime, "2019-04-19T02:42:28.182+02:00"^^xsd:dateTime) as ?result)
}


### Arithmetic operations¶

The fourth group of functions includes operations such as: adding duration to a date; adding dayTimeDuration to a dateTime; adding time duration to a time; comparing durations. This is done via the SPARQL operator extensibility.

## OpenAI GPT extensions¶

These magic predicates send queries to an OpenAI GPT model and return the answer as part of your SPARQL query results. Before using any of them, you must configure your access to the model as described in Configuring your use of GPT models.

Function

Description

?answer gpt:ask ?message

?answer gpt:ask (?message1 ?message2 …)

This magic predicate passes one or more messages with instructions to the OpenAI GPT. The results (unlike with gpt:list) are stored in a single binding. The last message passed can be a real number between 0 and 2 to set the temperature of the response.

If passing more than one argument in the triple pattern’s object position, enclose them in parentheses.

?answer gpt:list ?message

?answer gpt:list (?message1 ?message2 …)

This magic predicate passes one or more messages with instructions to the OpenAI GPT. These instructions should include a number that indicates how many results that you would like. The results (unlike with gpt:ask) can then be returned as multiple bindings of the specified variable, which will be displayed as separate result set rows. The last message passed can be a real number between 0 and 2 to set the temperature of the response.

If passing more than one argument in the triple pattern’s object position, enclose them in parentheses.

?column1 gpt:table ?message

?column1 gpt:table (?message1 ?message2 …)

(?column1 ?column2) gpt:table ?message

(?column1 ?column2 ?column3) gpt:table (?message1 ?message2 …)

This sends one or more requests to create multiple bindings with multiple values — in other words, a table. The last message passed can be a real number between 0 and 2 to set the temperature of the response.

Because gpt:table is a magic predicate, you call it as a triple pattern with the variable(s) in which to store the response as the subject and the messages to pass as the object. The subject can list more than one variable to store the values of the table columns. If you have more than one subject variable, enclose the list in parentheses. Similarly, if you pass more than one message, enclose the list in parentheses.

## List manipulation extension functions¶

Function

Description

helper:tuple()

Combines all of its arguments into an internal list that you can reference using a blank node connected to the list members. You can use this as both a function and as a magic predicate. The helper:iterate() function lets you access individual members of the list.

See helper:tuple() — Combine values into a list for more on this function.

helper:tupleAggr()

Similar to the helper:tuple function but only takes one argument. If the argument is bound to multiple values, it will aggregate those values into a list that can be accessed by a blank node connected to the list members. You can access individual members of the list using the helper:iterate() function.

See helper:tupleAggr() — Aggregate values into a list for more on this function.

helper:rdf()

Takes a subject, predicate, and object and combines them into an internal triple connected by a blank node. You can provide the triple components directly or combine using the helper:tuple function. If you do use the helper:tuple function, you may also add a reference to a named graph to store the triple.

See helper:rdf() — Combine values into an RDF triple for more on this function.

helper:serializeRDF()

Serializes RDF stored internally with a function such as helper:rdf so that you can see the contents of the triples. The default format is Turtle-star, but you can request a different one by naming the MIME type as an optional second argument.

See helper:serializeRDF() — Convert internal RDF to readable triples for more on this function.

?listMember helper:iterate ?tuple

Iterates over the elements of an internal list created by the helper:tuple, helper:tupleAggr, or helper:rdf functions. See helper:iterate() — Iterate through an internal list for more on this magic predicate.