维基数据SPARQL超时,子查询+标签服务+可选



在尝试回答这个问题时:如何将维基数据的结果过滤为特定语言,我遇到了以下问题:

一些国家拥有不止一个首都。 此查询仅随机选择每个国家/地区一个首都:

SELECT ?country (sample(?capital) as ?aCapital) WHERE {
?country wdt:P31 wd:Q3624078.  
FILTER NOT EXISTS {?country wdt:P31 wd:Q3024240} # not a former country
?country wdt:P36 ?capital.
} 
GROUP BY ?country 

在这里尝试一下

但是,在尝试添加标注和坐标时,查询超时:

SELECT ?country ?countryLabel ?aCapital ?aCapitalLabel ?coords WHERE {
OPTIONAL {?aCapital wdt:P625 ?coords.}
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
{
SELECT ?country (sample(?capital) as ?aCapital) WHERE {
?country wdt:P31 wd:Q3624078.  
FILTER NOT EXISTS {?country wdt:P31 wd:Q3024240} # not a former country
?country wdt:P36 ?capital.
} 
GROUP BY ?country 
}
}
ORDER BY ?countryLabel
LIMIT 1000

在这里尝试一下

在上面的评论之后 @AKSW - SPARQL 中的OPTIONAL连接。

重新排序子查询和 OPTIONAL 可以解决问题:

SELECT ?country ?countryLabel ?aCapital ?aCapitalLabel ?coords WHERE {
{
{
SELECT ?country (sample(?capital) as ?aCapital) WHERE {
?country wdt:P31 wd:Q3624078.  
FILTER NOT EXISTS {?country wdt:P31 wd:Q3024240} # not a former country
?country wdt:P36 ?capital.
} 
GROUP BY ?country 
}
OPTIONAL {?aCapital wdt:P625 ?coords.}
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
}
ORDER BY ?countryLabel
LIMIT 1000

在这里试试。

请注意,这需要添加额外的{+}以保持语法正确。

另请参阅:SPARQL 可选查询

最新更新