B. Smith
B. Smith

Reputation: 1193

Is it possible to use if statements to determine which graph pattern to use in where clause in SPARQL?

So I'm fairly new to SPARQL. I know that if statements cannot be used this way in SPARQL, but I was wondering if there is some way of doing what I want to accomplish, which is to match on a different graph pattern based on the value of a binding.

SELECT ...
WHERE {
    // ...set ?x to some count
    IF (?x = 0) {
       // series of graph patterns
    }
    ELSE {
       // different series of graph patterns
    }
}

Most of the examples I've seen have just consisted of setting the value of a specific binding based on an if statement, which is not what I'm trying to do. The graph pattern in the else is expensive computationally and I don't want to run it unless it is necessary.

Upvotes: 1

Views: 87

Answers (1)

Antoine Zimmermann
Antoine Zimmermann

Reputation: 5485

You cannot do it like what you show in your example, but you can use a UNION pattern like the following:

SELECT ...
WHERE {
  {
     // ... set ?x to some value
     // series of graph patterns
     FILTER(?x = 0)
  }
UNION
  {
     // ... set ?x to some value
     // different series of graph patterns
     FILTER(?x != 0)
  }
}

Note that if you want the filter to work inside the subgraph patterns, you need to have ?x bound inside the patterns. If the SPARQL engine is well optimised, the filter should be evaluated before the graph pattern is matched, but you could also play with the placement of the filter, e.g., between the binding of ?x and the graph pattern.

Upvotes: 1

Related Questions