首页 > 解决方案 > WikiData SPARQL 因子查询 + 标签服务 + 可选而超时

问题描述

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

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

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

在这里试试

标签: subquerysparqlwikidata

解决方案


遵循上面@AKSW 的评论 -OPTIONAL在 SPARQL 中是连接。

重新排序子查询和 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 可选查询


推荐阅读