|
Inspired by a few related questions (in particular this one), I wanted to ask a more general form of the question: how can I specify preferences for basic graph pattern matching in SPARQL (1.1) such that potentially many lower preferences are only matched if a higher preference cannot be found? It seems there are a few potential solutions and I hope to gather some alternative patterns, some of which may work best in different concrete scenarios. To make the general question concrete, but in a way that can easily be generalised, say I want to get the labels of each resource of type
The basic query in SPARQL would be:
How can this query be adapted to return names from predicates in the above preference order such that values for a given predicate are only returned if no value is returned for a higher-preference predicate? (I.e., if we find a |
|
A sequence of OPTIONALs gets a sort of conditional testing but it does not allow the input from VALUES or the rest of the query.
To allow the input to be defined not by the syntax order (returns one value at the top pref level):
Given that used as a subquery, you can use it to get the ?p and all all ?person ?p is you want all values. +1 That second solution is really rather neat +1 for the first solution. Regarding the second solution, I was thinking along similar lines, but even as a sub-query, doesn't it mean that you only get one name for one person and not one name for each person? For testing:
Against: http://sparql.org/query.html Returns one result for one book. Ok, you want more than a single item -- the data in /books isn't rich enough for testing. We need the old maximum trick ... updated to SPARQL 1.1. And a new answer. |
|
We find the subjects and properties, with preference numbering. We then check to see there isn't a better match. Data:
Query:
Results:
|


I'm particularly (but not solely) interested in a pattern that uses something like
VALUES (?p ?pref) { (foaf:name 1) (skos:prefLabel 2) (skos:altLabel 3) (rdfs:label 4) ... }to specify the ordering. I thought this would be relatively straightforward, but it's difficult to makeVALUESplay nice with sub-queries/group by/limit, etc.What if it finds multiple
foaf:names?I would leave that open ... i.e., I'd take answers for patterns that either (i) only return one value or (ii) return all values for the preferred predicate.
(It shouldn't be so difficult to get the (i) from the (ii) using
GROUP BY/SAMPLEwith a nested sub-query.)