Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SPARQL - Restricting Result Resource to Certain Namespace(s)

Tags:

sparql

Is there a standard way of restricting the results of a SPARQL query to belong to a specific namespace.

like image 888
myahya Avatar asked Mar 07 '12 08:03

myahya


People also ask

How does SPARQL work?

SPARQL sees your data as a directed, labeled graph, that is internally expressed as triples consisting of subject, predicate and object. Correspondingly, a SPARQL query consists of a set of triple patterns in which each element (the subject, predicate and object) can be a variable (wildcard).

What is construct query in SPARQL?

The CONSTRUCT query form returns an RDF graph. The graph is built based on a template which is used to generate RDF triples based on the results of matching the graph pattern of the query.


1 Answers

Short answer - no there is no standard direct way to do this

Long answer - However yes you can do a limited form of this with the string functions and a FILTER clause. What function you use depends on what version of SPARQL your engine supports.

SPARQL 1.1 Solution

Almost all implementations will these days support SPARQL 1.1 and you can use the STRSTARTS() function like so:

FILTER(STRSTARTS(STR(?var), "http://example.org/ns#"))

This is my preferred approach and should be relatively efficient because it is simple string matching.

SPARQL 1.0 Solution

If you are stuck using an implementation that only supports SPARQL 1.0 you can still do this like so but it uses regular expressions via the REGEX() function so will likely be slower:

FILTER(REGEX(STR(?var), "^http://example\\.org/ns#"))

Regular Expressions and Meta-Characters

Note that for the regular expression we have to escape the meta-character . as otherwise it could match any character e.g. http://exampleXorg/ns#foo would be considered a valid match.

As \ is the escape character for both regular expressions and SPARQL strings it has to be double escaped here in order to get the regular expression to have just \. in it and treat . as a literal character.

Recommendation

If you can use SPARQL 1.1 then do so because using the simpler string functions will be more performant and avoids the need to worry about escaping any meta-characters that you have when using REGEX

like image 64
RobV Avatar answered Sep 22 '22 21:09

RobV