Is there a standard way of restricting the results of a SPARQL query to belong to a specific namespace.
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).
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.
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.
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.
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#"))
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With