Friday, August 28, 2009

SPARQL Switch/Case

The Intellidimension SPARQL processor supports a Switch/Case syntax that allows for the implementation of If…Else If…Else If…Else… logic in your queries. The syntax of a switch statement consists of a variable list followed by a body that contains one or more graph patterns preceded by the case keyword.

switch ([variable list]) {
  case {[graph pattern 1]}
  ..
 
case {[graph pattern N]}
}

The variable list defines one or more variables to be grouped by when evaluating the body of the statement. The graph patterns for the cases are evaluated once for each unique binding of the variables in the list. The case graph patterns are evaluated in order and once a pattern is matched for a set of variable bindings then no more patterns are evaluated (for that set of variable bindings).

The example below uses some inference rules to create some sample data and then runs a SPARQL SELECT query that utilizes a switch statement to get a label for a resource. The logic is to first use the property <name>, then <label> and if neither exists then to turn the subject URI into a literal.

# infer some data
rulebase (
construct {<a> <label> "a"}
construct {<b> <label> "b"}
construct {<b> <name> "bee"}
construct {<c> <size> "large"}
)

select ?s ?txt where {
?s ?p ?o.
switch(?s) {
case {?s <name> ?txt} #name first
case {?s <label> ?txt} #then label
case {filter(?txt=str(?s))} #default
}
}

When this query is executed it produces the following results.

<a>    "a"
<b> "bee"
<c> "c"

The switch statement is perfect for generating a single value for a property based on some predetermined ranking of predicates.