WikiData SPARQL超时子查询+标签服务+可选

时间:2018-05-24 20:27:41

标签: subquery sparql wikidata

在尝试回答这个问题时:How to filter results of wikidata to specific language,我遇到了以下问题:

有些国家/地区more than one capital。此查询随机选择每个国家/地区只有一个资本:

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 

Try it here

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

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

Try it here

1 个答案:

答案 0 :(得分:1)

评论后@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

Try it here

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

另请参阅:SPARQL Optional query