In the following SPARQL query, I'm not sure how to use if
to bind one of two strings to the variable ?result
. I heard that there are concepts of “in scope” and “out of scope,” but I don't really see the difference. I've also tried putting the if
clause in the select
line, but it didn't work either. How can I fix this query to bind ?result
to one of the two strings based on the condition?
SELECT ?result
WHERE{
?chain rdf:type rdfs:Property .
?chain rdfs:domain <http://www.vs.cs.hs-rm.de/ontostor/SVC#MDiskGroup> .
?chain rdfs:range <http://www.vs.cs.hs-rm.de/ontostor/SVC#IOgroup> .
?this ?chain ?arg .
?arg io:id ?var .
IF(?var = "0"^^xsd:integer,
BIND(" *"^^xsd:string AS ?result),
BIND(""^^xsd:string AS ?result)) .
}
The
if
operator in SPARQL isn't a statement as it sometimes is in a programming language, but a functional form. expression. The value ofif(test,a,b)
isa
iftest
is true, andb
iftest
is false. As the documentation says:So,
if
isn't a statement like it might be in a programming language, but it's simply a function that takes three arguments and returns a value. SPARQL is a query language, and doesn't have statements that get executed; it's a query language for matching patterns in a graph and binding variables to values. Soif
is a function, and it just so happens that if the first argument is true, then it returns the second argument, otherwise it returns the third. In general, you'd bind the value of a function to a variable withand this case is no different. You'd call the
if
function and bind its result to a variable withIn your case, this means that you would use the following query. I've added some newlines to help the readability, but they're not necessary. Integers in a SPARQL query are shorthand for a literal with type
xsd:integer
, so I've also used (thanks to RobV's comment)0
instead of"0"^^xsd:integer
. (See 2.3.2 Matching Literals with Numeric Types.)If we actually want to shorten this even more, then we can use
xsd:string
as a constructor, and do (see 17.5 XPath Constructor Functions):This might seem a little bit odd at first if you're used to doing things like
but many language actually provide a ternary operator that lets you do the much shorter
instead. This is the functionality you're getting with SPARQL.