SPARQL Functions Reference

This section lists all supported SPARQL functions in GraphDB. The function specifications include the types of the arguments and the output. Types from XML Schema should be readily recognizable as they start with the xsd: prefix. In addition, the following more generic types are used:

rdfTerm

Any RDF value: a literal, a blank node or an IRI.

iri

An IRI.

bnode

A blank node.

literal

A literal regardless of its datatype or the presence of a language tag.

string

A plain literal or a literal with a language tag. Note that plain literals have the implicit datatype xsd:string.

numeric

A literal with a numeric XSD datatype, e.g. xsd:double and xsd:long.

variable

A SPARQL variable.

expression

A SPARQL expression that may use any constants and variables to compute a value.

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.

  • Functions are denoted like this: ex:function(arg1, arg2, ...) where all arguments must be bound, and are used in bind, in select expressions, in the order clause, etc.

  • Magic predicates are denoted like this: subject ex:magicPredicate (arg1 arg2 ...) where in some cases, the arguments are allowed to be unbound (and are then calculated from the subject). They are used as triple patterns. The object is an RDF list of the arguments (indicated by the parentheses on the right-hand side).

SPARQL 1.1 functions

Function

Description

xsd:boolean BOUND(variable var)

Returns true if the variable var is bound to a value. Returns false otherwise. Variables with the value NaN or INF are considered bound. More

rdfTerm IF(expression e1, expression e2, expression e3)

The IF function form evaluates the first argument, interprets it as a effective boolean value, then returns the value of e2 if the EBV is true, otherwise it returns the value of e3. Only one of e2 and e3 is evaluated. If evaluating the first argument raises an error, then an error is raised for the evaluation of the IF expression. More

rdfTerm COALESCE(expression e1, )

The COALESCE function form returns the RDF term value of the first expression that evaluates without error. In SPARQL, evaluating an unbound variable raises an error.

If none of the arguments evaluates to an RDF term, an error is raised. If no expressions are evaluated without error, an error is raised. More

xsd:boolean NOT EXISTS { pattern }

xsd:boolean EXISTS { pattern }

There is a filter operator EXISTS that takes a graph pattern. EXISTS returns true or false depending on whether the pattern matches the dataset given the bindings in the current group graph pattern, the dataset and the active graph at this point in the query evaluation. No additional binding of variables occurs. The NOT EXISTS form translates into fn:not(EXISTS{...}). More

xsd:boolean xsd:boolean left || xsd:boolean right

Returns a logical OR of left and right. Note that logical-or operates on the effective boolean value of its arguments. More

xsd:boolean xsd:boolean left && xsd:boolean right

Returns a logical AND of left and right. Note that logical-and operates on the effective boolean value of its arguments. More

xsd:boolean rdfTerm term1 = rdfTerm term2

Returns true if term1 and term2 are equal. Returns false otherwise. IRIs and blank nodes are equal if they are the same RDF term as defined in RDF Concepts. Literals are equal if they have an XSD datatype, the same language tag (if any) and their values produced by applying the lexical-to-value mapping of their datatypes are also equal. If the arguments are both literal but their datatype is not an XSD datatype an error will be produced. More

xsd:boolean sameTerm(rdfTerm term1, rdfTerm term2)

Returns true if term1 and term2 are the same RDF term as defined in RDF Concepts; returns false otherwise. More

xsd:boolean rdfTerm term IN (expression e1, )

The IN operator tests whether the RDF term on the left-hand side is found in the values of list of expressions on the right-hand side. The test is done with = operator, which compares the RDF term to each expression for equality. More

xsd:boolean rdfTerm term NOT IN (expression e1, )

The NOT IN operator tests whether the RDF term on the left-hand side is not found in the values of list of expressions on the right-hand side. The test is done with != operator, which compares the RDF term to each expression for inequality. More

xsd:boolean isIRI(rdfTerm term)

xsd:boolean isURI(rdfTerm term)

Returns true if term is an IRI. Returns false otherwise. More

xsd:boolean isBlank(rdfTerm term)

Returns true if term is a blank node. Returns false otherwise. More

xsd:boolean isLiteral(rdfTerm term)

Returns true if term is a literal. Returns false otherwise. More

xsd:boolean isNumeric(rdfTerm term)

Returns true if term is a numeric value. Returns false otherwise. A term is numeric if it has an appropriate datatype and has a valid lexical form, making it a valid argument to functions and operators taking numeric arguments. More

xsd:string STR(literal ltrl)

xsd:string STR(iri rsrc)

Returns the lexical form of ltrl (a literal); returns the codepoint representation of rsrc (an IRI). This is useful for examining parts of an IRI, for instance, the hostname. More

xsd:string LANG(literal ltrl)

Returns the language tag of the literal ltrl, if it has one. It returns “” if ltrl has no language tag. Note that the RDF data model does not include literals with an empty language tag. More

iri DATATYPE(literal ltrl)

Returns the datatype IRI of the literal ltrl. More

iri IRI(string str)

iri IRI(iri rsrc)

iri URI(string str)

iri URI(iri rsrc)

The IRI function constructs an IRI by resolving the string argument str. The IRI is resolved against the base IRI of the query and must result in an absolute IRI. If the function is passed an IRI rsrc, it returns the IRI unchanged. More

bnode BNODE()

bnode BNODE(string str)

The BNODE function constructs a blank node that is distinct from all blank nodes in the dataset being queried and distinct from all blank nodes created by calls to this constructor for other query solutions. If the no argument form is used, every call results in a distinct blank node. If the form with the string str is used, every call results in distinct blank nodes for different strings, and the same blank node for calls with the same string within expressions for one solution mapping. More

iri UUID()

Return a fresh IRI from the UUID URN scheme. Each call of UUID() returns a different UUID. More

xsd:string STRUUID()

Return a string that is the scheme specific part of UUID. That is, as a string literal, the result of generating a UUID, converting to a string literal and removing the initial urn:uuid:. More

xsd:integer STRLEN(string str)

The STRLEN function corresponds to the XPath fn:string-length function and returns an xsd:integer equal to the length in characters of the lexical form of the string str. More

string SUBSTR(string source, xsd:integer startingLoc)

string SUBSTR(string source, xsd:integer startingLoc, xsd:integer length)

The SUBSTR function corresponds to the XPath fn:substring function and returns a literal of the same kind (string literal or literal with language tag) as the source input parameter but with a lexical form formed from the substring of the lexical form of the source. More

string UCASE(string str)

The UCASE function corresponds to the XPath fn:upper-case function. It returns a string literal whose lexical form is the upper case of the lexical form of the argument. More

string LCASE(string str)

The LCASE function corresponds to the XPath fn:lower-case function. It returns a string literal whose lexical form is the lower case of the lexical form of the argument. More

xsd:boolean STRSTARTS(string str1, string str2)

The STRSTARTS function corresponds to the XPath fn:starts-with function and returns true if the lexical form of str1 starts with the lexical form of str2, otherwise it returns false. More

xsd:boolean STRENDS(string str1, string str2)

The STRENDS function corresponds to the XPath fn:ends-with function and returns true if the lexical form of str1 ends with the lexical form of str2, otherwise it returns false. More

xsd:boolean CONTAINS(string str1, string str2)

The CONTAINS function corresponds to the XPath fn:contains function and returns true if the lexical form of str1 contains the lexical form of str2 as a substring. More

string STRBEFORE(string str1, string str2)

The STRBEFORE function corresponds to the XPath fn:substring-before function and returns a literal of the same kind as str1. The lexical form of the result is the substring of the lexical form of str1 that precedes the first occurrence of the lexical form of str2. If the lexical form of str2 is the empty string, this is considered to be a match and the lexical form of the result is the empty string. If there is no such occurrence, an empty string literal is returned. More

string STRAFTER(string str1, string str2)

The STRAFTER function corresponds to the XPath fn:substring-after function and returns a literal of the same kind as str1. The lexical form of the result is the substring of the lexical form of str1 that follows the first occurrence of the lexical form of str2. If the lexical form of str2 is the empty string, this is considered to be a match and the lexical form of the result is the empty string. If there is no such occurrence, an empty simple literal is returned. More

xsd:string ENCODE_FOR_URI(string str)

The ENCODE_FOR_URI function corresponds to the XPath fn:encode-for-uri function. It returns a simple literal with the lexical form obtained from the lexical form of its input after translating reserved characters according to the fn:encode-for-uri function. More

string CONCAT(string str1, )

The CONCAT function corresponds to the XPath fn:concat function. The function accepts string literals as arguments.

The lexical form of the returned literal is obtained by concatenating the lexical forms of its inputs. If all input literals are literals with identical language tag, then the returned literal is a literal with the same language tag, in all other cases, the returned literal is a simple literal. More

xsd:boolean langMatches(xsd:string languageTag, xsd:string languageRange)

Returns true if languageTag (first argument) matches languageRange (second argument). According to language tag semantics, the matching is case-insensitive. languageRange is a basic language range. For example, “en” will match any of the languageTags “en”, “EN”, “En”, “en-GB”, “en-US”, etc. A language range of “*” matches any non-empty language tag string. More

xsd:boolean REGEX(string text, xsd:string pattern)

xsd:boolean REGEX(string text, xsd:string pattern, xsd:string flags)

Invokes the XPath fn:matches function to match text against a regular expression pattern. Regular expression matching may involve the modifier flags: “i” requests case-insensitive matching. More

string REPLACE(string arg, xsd:string pattern, xsd:string replacement)

string REPLACE(string arg, xsd:string pattern, xsd:string replacement, xsd:string flags)

The REPLACE function corresponds to the XPath fn:replace function. It replaces each non-overlapping occurrence of the regular expression pattern with the replacement string. Regular expression matching may involve the modifier flags: “i” requests case-insensitive matching. More

numeric ABS(numeric num)

Returns the absolute value of num. An error is raised if the argument is not a numeric value.

This function is the same as fn:numeric-abs for terms with a datatype from XDM. More

numeric ROUND(numeric num)

Returns the number with no fractional part that is closest to num. If there are two such numbers, then the one that is closest to positive infinity is returned. An error is raised if the argument is not a numeric value.

This function is the same as fn:numeric-round for terms with a datatype from XDM. More

numeric CEIL(numeric num)

Returns the smallest (closest to negative infinity) number with no fractional part that is not less than the value of num. An error is raised if the argument is not a numeric value.

This function is the same as fn:numeric-ceil for terms with a datatype from XDM. More

numeric FLOOR(numeric num)

Returns the largest (closest to positive infinity) number with no fractional part that is not greater than the value of num. An error is raised if the argument is not a numeric value.

This function is the same as fn:numeric-floor for terms with a datatype from XDM. More

xsd:double RAND()

Returns a pseudo-random number between 0 (inclusive) and 1.0 (exclusive). Different numbers can be produced every time this function is invoked. Numbers should be produced with approximately equal probability. More

xsd:dateTime NOW()

Returns an XSD dateTime value for the current query execution. All calls to this function in any one query execution will return the same value. The exact moment returned is not specified. More

xsd:integer YEAR(xsd:dateTime arg)

Returns the year part of arg as an integer.

This function corresponds to fn:year-from-dateTime. More

xsd:integer MONTH(xsd:dateTime arg)

Returns the month part of arg as an integer.

This function corresponds to fn:month-from-dateTime. More

xsd:integer DAY(xsd:dateTime arg)

Returns the day part of arg as an integer.

This function corresponds to fn:day-from-dateTime. More

xsd:integer HOURS(xsd:dateTime arg)

Returns the hours part of arg as an integer. The value is as given in the lexical form of the XSD dateTime.

This function corresponds to fn:hours-from-dateTime. More

xsd:integer MINUTES(xsd:dateTime arg)

Returns the minutes part of the lexical form of arg. The value is as given in the lexical form of the XSD dateTime.

This function corresponds to fn:minutes-from-dateTime. More

xsd:decimal SECONDS(xsd:dateTime arg)

Returns the seconds part of the lexical form of arg.

This function corresponds to fn:seconds-from-dateTime. More

xsd:dayTimeDuration TIMEZONE(xsd:dateTime arg)

Returns the timezone part of arg as an xsd:dayTimeDuration. Raises an error if there is no timezone.

This function corresponds to fn:timezone-from-dateTime except for the treatment of literals with no timezone. More

xsd:string TZ(xsd:dateTime arg)

Returns the timezone part of arg as a simple literal. Returns the empty string if there is no timezone. More

xsd:string MD5(xsd:string arg)

Returns the MD5 checksum, as a hex digit string, calculated on the UTF-8 representation of the lexical form of the argument. More

xsd:string SHA1(xsd:string arg)

Returns the SHA1 checksum, as a hex digit string, calculated on the UTF-8 representation of the lexical form of the argument. More

xsd:string SHA256(xsd:string arg)

Returns the SHA256 checksum, as a hex digit string, calculated on the UTF-8 representation of the lexical form of the argument. More

xsd:string SHA512(xsd:string arg)

Returns the SHA512 checksum, as a hex digit string, calculated on the UTF-8 representation of the lexical form of the argument. More

SPARQL 1.1 constructor functions

Casting in SPARQL 1.1 is performed by calling a constructor function for the target type on an operand of the source type. The standard includes the following constructor functions:

Note

Note that SPARQL 1.1 does not have an xsd:date constructor. Instead, use STRDT(value,xsd:date) to attach the xsd:date datatype to the value.

Constructor function

Description

literal STRDT(xsd:string lexicalForm, iri datatypeIRI)

The STRDT function constructs a literal with lexical form and type as specified by the arguments. More

xsd:langString STRLANG(xsd:string lexicalForm, xsd:string langTag)

The STRLANG function constructs a literal with lexical form and language tag as specified by the arguments. More

xsd:integer(rdfTerm value)

Casts value to xsd:integer. More

xsd:decimal(rdfTerm value)

Casts value to xsd:decimal. More

xsd:float(rdfTerm value)

Casts value to xsd:float. More

xsd:double(rdfTerm value)

Casts value to xsd:double. More

xsd:string(rdfTerm value)

Casts value to xsd:string. More

xsd:boolean(rdfTerm value)

Casts value to xsd:boolean. More

xsd:dateTime(rdfTerm value)

Casts value to xsd:dateTime. More

xsd:nonPositiveInteger(rdfTerm value)

Casts value to xsd:nonPositiveInteger. More

xsd:negativeInteger(rdfTerm value)

Casts value to xsd:negativeInteger. More

xsd:long(rdfTerm value)

Casts value to xsd:long. More

xsd:int(rdfTerm value)

Casts value to xsd:int. More

xsd:short(rdfTerm value)

Casts value to xsd:short. More

xsd:byte(rdfTerm value)

Casts value to xsd:byte. More

xsd:nonNegativeInteger(rdfTerm value)

Casts value to xsd:nonNegativeInteger. More

xsd:unsignedLong(rdfTerm value)

Casts value to xsd:unsignedLong. More

xsd:unsignedInt(rdfTerm value)

Casts value to xsd:unsignedInt. More

xsd:unsignedShort(rdfTerm value)

Casts value to xsd:unsignedShort. More

xsd:unsignedByte(rdfTerm value)

Casts value to xsd:unsignedByte. More

xsd:positiveInteger(rdfTerm value)

Casts value to xsd:positiveInteger. More

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 function analogs. The prefix afn: stands for the namespace <http://jena.apache.org/ARQ/function#>.

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

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().

?result spif:for (?start ?end)

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

?result spif:foreach (?arg1 ?arg2 )

Generates bindings for the given arguments arg1, arg2 and so on.

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/SPARQL-star syntax here.

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.

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)

GeoSPARQL extension functions

On top of the standard GeoSPARQL functions, GraphDB adds a few useful extensions based on the USeekM library. The prefix ext: 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 here.

Function

Description

xsd:double ext:area(geomLiteral g)

Calculates the area of the surface of the geometry.

geomLiteral ext: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 ext: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 ext: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 ext: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 ext: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 ext:shortestLine(geomLiteral g1, geomLiteral g2)

Computes the shortest line between two geometries. Returns it as a LineString object.

geomLiteral ext: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 ext: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 ext: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 extensions here.

Other function extensions

Below are additional Jena function analogs supported by GraphDB.

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.)