编辑:请阅读这篇文章的评论 - 文章本身已得到解答。
我的查询的相关部分(检索获奖时担任国家元首或政府首脑的诺贝尔奖获得者)是这样的:
?nobel_laureate p:P39 ?p39 . # p39 = "position held"
?p39 ps:P39 ?status .
?p39 pq:P580 ?start_time .
OPTIONAL { ?p39 pq:P582 ?end_time . }
...
FILTER ( ?point_in_time >= ?start_time && ?point_in_time <= ?end_time )
?nobel_laureate
拥有诺贝尔奖获得者。?status holds
诺贝尔奖获得者所属国家的“国家元首担任的职位”和“政府首脑担任的职位”属性的值?point_in_time
是获得诺贝尔奖的时间我现在想要检索“持有职位”语句的“开始时间”和“结束时间”限定符值,其值在
?status
中,例如 Hjalmar Branting 的“瑞典总理”和“瑞典君主”,谁是瑞典公民。
他曾两次担任瑞典首相。 我有一个问题,如果我想检查
?point_in_time
是否在“开始时间”和“结束时间”之间,瑞典总理的不同声明会混淆。
我该怎么做才能让他们分开?
我没有尝试任何事情,因为我一无所知。
编辑:由于我找不到原因,此维基百科列表中还有其他几个人没有出现在输出中。巴拉克·奥巴马 (Barack Obama) 和阿比·艾哈迈德 (Abiy Ahmed) 被
FILTER
淘汰:对于米哈伊尔·戈尔巴乔夫 (Mikhail Gorbachev) 和 F.W. de Klerk,我不知道他们为何失踪。
关于 Abiy Ahmed Ali 问题:如果
?end_time
不受 OPTIONAL
子句约束,则过滤器不会成功,因为 <=
比较会导致错误。
SPARQL 有
bound()
函数用于此目的,它检查参数是否已绑定。在这种情况下,类似(未经测试):
FILTER ( year(?point_in_time) >= year(?start_time) && (year(?point_in_time) <= year(?end_time) || ! bound(?end_time) ) )
但是,QLever 并没有实现这一点,所以你会得到错误:
Invalid SPARQL query: Built-in function "bound" not yet implemented
另一种方法是使用
COALESCE
。该函数接受 n
参数并返回第一个不触发错误的表达式的结果。因此,您可以检查结束日期条件,如果有结束日期,它将根据需要生成 true 或 false,如果没有结束日期,则转到第二个参数,您需要选择该参数,使其始终评估为 true (因为如果满足开始日期条件,仍在任的人就有资格进入该名单)。
代码:
PREFIX p: <http://www.wikidata.org/prop/>
PREFIX pq: <http://www.wikidata.org/prop/qualifier/>
PREFIX ps: <http://www.wikidata.org/prop/statement/>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX wd: <http://www.wikidata.org/entity/>
SELECT DISTINCT ?nobel_laureate_name ?nobel_prize_name ?country_name ?status_name ?year
WHERE
{ { ?country wdt:P31/(wdt:P279)* wd:Q6256 . } UNION { ?country wdt:P31/(wdt:P279)* wd:Q7275 . }
{ ?country wdt:P1906 ?status . } UNION { ?country wdt:P1313 ?status . }
{ ?nobel_laureate wdt:P27 ?country . } UNION { ?nobel_laureate wdt:P27/p:P31 ?p31 .
?p31 ps:P31 wd:Q11514315 .
?p31 pq:P642 ?country .
}
?nobel_laureate p:P39 ?p39 .
?p39 ps:P39 ?status ;
pq:P580 ?start_time
OPTIONAL { ?p39 pq:P582 ?end_time . }
?nobel_laureate
p:P166 ?p166 .
?p166 ps:P166 ?nobel_prize .
?nobel_prize wdt:P361 wd:Q7191 .
?p166 pq:P585 ?point_in_time
FILTER ( year(?point_in_time) >= year(?start_time) && COALESCE ( year(?point_in_time) <= year(?end_time), 1 ) )
BIND(year(?point_in_time) AS ?year)
OPTIONAL { ?nobel_laureate wdt:P18 ?image }
OPTIONAL { ?country wdt:P41 ?flag_image }
?nobel_laureate @en@rdfs:label ?nobel_laureate_name .
?nobel_prize @en@rdfs:label ?nobel_prize_name .
?status @en@rdfs:label ?status_name .
?country @en@rdfs:label ?country_name .
}
ORDER BY ASC(?year)
结果(删除图片以节省空间):