15

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

myahya
  • 2,889
  • 7
  • 34
  • 50

1 Answers1

28

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

RobV
  • 26,016
  • 10
  • 71
  • 114