gpt4 book ai didi

sparql - 计数时如何获取 SPARQL 查询的默认返回值

转载 作者:行者123 更新时间:2023-12-02 17:23:49 24 4
gpt4 key购买 nike

我有一个查询,其中我按年份进行分组。有些年份没有可计算的项目,因此没有结果。我想让 SPARQL 在这些年中返回零计数。

我正在使用维基数据查询服务,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

这是结果截图:

enter image description here


这里的关键是optional + bind/coalesce的组合。一般模式是

bind(... as ?default_foo)

optional {
# try to get value ?foo
}

bind(coalesce(?foo, ?default_foo) as ?result_foo)

coalesce返回它可以返回的第一个值(即无错误地绑定(bind)/评估)。因此,如果您尝试在 optional { ... } 中获取的值未绑定(bind),则将采用默认值并绑定(bind)为结果。更详细的写法:

bind(if(bound(?foo), ?foo, ?default_foo) as ?result_foo)

但是 coalesce 更好,因为您可以在其中传递多个值。在更复杂的查询中它可能很有用:参见 this example .

关于sparql - 计数时如何获取 SPARQL 查询的默认返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40454268/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com