I am trying to retrieve some municipalities from Wikidata using SPARQL but several items returned have much of their fields empty despite these items having these data. I do not understand what is wrong with the query below (link to WQS). For example, the municipality Almelo has its coordinates (P625), and parent place (P131) erroneously missing in the results:
SELECT ?mun ?munLabel ?coords ?parentPlace ?area WHERE {
?mun p:P31 ?instanceOf # Get statement because we need this later
.
?instanceOf ps:P31/wdt:279* wd:Q2039348.
OPTIONAL {
?mun wdt:P625 ?coords;
wdt:P131 ?parentPlace;
wdt:P2046 ?area
.
}
MINUS { ?instanceOf pq:P582 ?endTime. } # Don't show municipalities that have an end time
service wikibase:label { bd:serviceParam wikibase:language "en". }
} ORDER BY ?munLabel
This is because you are using one OPTIONAL statement instead of 3 separately.
In this case, Almelo doesn't have an 'area', wdt:P2046, so the whole OPTIONAL statement evaluates as false, and so it binds no variables.
The following query works: Notice that we have 3 distinct optional statements, so that they may fail to bind variables independently of each other.
SELECT ?mun ?munLabel ?coords ?parentPlace ?area WHERE {
?mun p:P31 ?instanceOf # Get statement because we need this later
.
?instanceOf ps:P31/wdt:279* wd:Q2039348.
OPTIONAL {?mun wdt:P625 ?coords }
OPTIONAL {?mun wdt:P131 ?parentPlace }
OPTIONAL {?mun wdt:P2046 ?area }
MINUS { ?instanceOf pq:P582 ?endTime. } # Don't show municipalities that have an end time
service wikibase:label { bd:serviceParam wikibase:language "en". }
} ORDER BY ?munLabel
You have to declare OPTIONAL each statement independently:
OPTIONAL { ?mun wdt:P625 ?coords . }
OPTIONAL { ?mun wdt:P131 ?parentPlace . }
OPTIONAL { ?mun wdt:P2046 ?area . }
Otherwise, if one of them is missing, then the whole OPTIONAL block is ignored.
See also Multiple Optional Graph Patterns.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With