Search code examples
sparqlrdf

SPARQL: How to restrict a variable to a namespace?


Consider the following SPARQL query:

PREFIX basics: <http://example.org/basic-knowledge/>
PREFIX special: <http://example.org/special-predicates/>

SELECT ?S ?P ?O
WHERE
{

 ?S ?P ?O.

}

This yields all triples.

How can I restrict the result to those triples where the predicate ?P is from the namespace with the prefix special:?


Solution

  • This can be done with a string test. str() turns URIs into strings.

    FILTER(strStarts(str(?P), str(special:)))
    

    note the special: is replaced by the parser with the full URI: http://example.org/special-predicates so the executiuon is

    FILTER(strStarts(str(?P), str(<ttp://example.org/special-predicates>)))
    

    Runnable example:

    PREFIX ns1: <http://example/>
    PREFIX ns2: <http://ex/>
    
    SELECT * {
     VALUES ?x { ns1:abc ns2:xyz }
     FILTER(strstarts(str(?x), str(ns1:)))
    }