[英]How can get default return values for a SPARQL query when counting
我有一個查詢,其中我可以對年份進行分組。 在某些年份中,沒有要計數的項目,因此沒有結果。 我希望SPARQL在此類年份中返回零計數。
我正在使用Wikidata查詢服務https://query.wikidata.org ,而我目前的解決方案是使一系列值和與實際查詢的並集。 在我看來有點笨拙。 有沒有更好的辦法?
#defaultView:BarChart
select ?year ?number_of_pages ?work_label where {
{
select ?year (sample(?pages) as ?number_of_pages) ?work_label
where {
{
select * where {
values (?year ?pages ?work_label) {
("2000" "0"^^xsd:integer "_")
("2001" "0"^^xsd:integer "_")
("2002" "0"^^xsd:integer "_")
("2003" "0"^^xsd:integer "_")
("2004" "0"^^xsd:integer "_")
("2005" "0"^^xsd:integer "_")
("2006" "0"^^xsd:integer "_")
("2007" "0"^^xsd:integer "_")
("2008" "0"^^xsd:integer "_")
("2009" "0"^^xsd:integer "_")
("2010" "0"^^xsd:integer "_")
("2011" "0"^^xsd:integer "_")
("2012" "0"^^xsd:integer "_")
("2013" "0"^^xsd:integer "_")
("2014" "0"^^xsd:integer "_")
("2015" "0"^^xsd:integer "_")
("2016" "0"^^xsd:integer "_")
}
}
}
union {
?work wdt:P50 wd:Q18921408 .
?work wdt:P1104 ?pages .
?work wdt:P577 ?date .
?work rdfs:label ?long_work_label . filter(lang(?long_work_label) = 'en')
bind(substr(?long_work_label, 1, 20) as ?work_label)
bind(str(year(?date)) as ?year)
}
}
group by ?year ?work ?work_label
order by ?year
}
}
您不需要太多的嵌套查詢。 這是一個簡單的解決方案:
#defaultView:BarChart
select ?year ?pages ?label
where {
# iterating over years
values ?year {
"2000" "2001" "2002" "2003" "2004" "2005"
"2006" "2007" "2008" "2009" "2010" "2011"
"2012" "2013" "2014" "2015" "2016"
}
# binding defaults
bind( 0 as ?default_pages)
bind("_" as ?default_label)
# if there is a work in the given year, ?work_pages and ?work_label will be bound
optional {
?work wdt:P50 wd:Q18921408;
wdt:P1104 ?work_pages;
wdt:P577 ?work_date.
bind(str(year(?work_date)) as ?year).
?work rdfs:label ?long_work_label.
filter(lang(?long_work_label) = 'en').
bind(substr(?long_work_label, 1, 20) as ?work_label)
}
# either take ?work_pages/label value or default and bind it as the result ?pages/label
bind(coalesce(?work_pages, ?default_pages) as ?pages)
bind(coalesce(?work_label, ?default_label) as ?label)
}
order by ?year
這是結果屏幕截圖:
這里的關鍵是optional
+ bind
/ coalesce
的組合。 一般模式是
bind(... as ?default_foo)
optional {
# try to get value ?foo
}
bind(coalesce(?foo, ?default_foo) as ?result_foo)
coalesce
返回它可以的第一個值(綁定/評估沒有錯誤)。 因此,如果您嘗試在optional { ... }
獲取的值未綁定,則將采用默認值並將其綁定為結果。 一種更詳細的寫法:
bind(if(bound(?foo), ?foo, ?default_foo) as ?result_foo)
但是coalesce
更好,因為您可以在其中傳遞多個值。 在更復雜的查詢中,它可能很有用:請參見以下示例 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.