You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否将获取维基百科页面ID的两步SPARQL查询合并为单个查询?

合并SPARQL查询:从维基百科标题直接获取页面ID

我希望通过Wikidata Query Service,使用单个SPARQL查询从维基百科标题直接获取对应的维基百科页面ID。目前已实现两步查询:

第一步:通过维基百科标题“Alpes-de-Haute-Provence”获取对应的维基数据ID(wd:Q3131),查询代码如下:

SELECT ?item ?itemLabel ?itemDescription WHERE {
            ?url rdf:type schema:Article;
            schema:about ?item; schema:name ?name ;
            schema:isPartOf <https://fr.wikipedia.org/>;
            schema:name "Alpes-de-Haute-Provence"@fr.
          SERVICE wikibase:label {
            bd:serviceParam
            wikibase:language "fr,[AUTO_LANGUAGE],en"
          }
}

第二步:通过该维基数据ID获取维基百科页面ID,查询代码如下:

SELECT ?pageid WHERE {
    VALUES (?item) {(wd:Q3131)} 
    [ schema:about ?item ; schema:name ?name ;
      schema:isPartOf <https://fr.wikipedia.org/> ]
     SERVICE wikibase:mwapi {
         bd:serviceParam wikibase:endpoint "fr.wikipedia.org" .
         bd:serviceParam wikibase:api "Generator" .
         bd:serviceParam mwapi:generator "allpages" .
         bd:serviceParam mwapi:gapfrom ?name .
         bd:serviceParam mwapi:gapto ?name .
         ?pageid wikibase:apiOutput "@pageid" .
    }
}

请问是否可以将这两步查询合并为单个SPARQL查询?


当然可以合并,直接把两步的查询逻辑整合到同一个WHERE子句中即可。合并后的查询会先匹配法语维基中对应标题的条目,拿到维基数据项和页面标题,再通过MWAPI服务精准匹配标题获取页面ID。

合并后的完整查询代码:

SELECT ?item ?itemLabel ?pageid WHERE {
    # 匹配法语维基中指定标题的条目,获取维基数据项和页面标题
    ?url rdf:type schema:Article;
         schema:about ?item;
         schema:name ?name;
         schema:isPartOf <https://fr.wikipedia.org/>;
         schema:name "Alpes-de-Haute-Provence"@fr.
    
    # 通过MWAPI查询获取页面ID
    SERVICE wikibase:mwapi {
        bd:serviceParam wikibase:endpoint "fr.wikipedia.org";
                        wikibase:api "Generator";
                        mwapi:generator "allpages";
                        mwapi:gapfrom ?name;
                        mwapi:gapto ?name.
        ?pageid wikibase:apiOutput "@pageid".
    }
    
    # 可选:获取维基数据项的标签
    SERVICE wikibase:label {
        bd:serviceParam wikibase:language "fr,[AUTO_LANGUAGE],en".
    }
}

如果不需要返回维基数据项和标签,可以简化为只返回?pageid的版本:

SELECT ?pageid WHERE {
    ?url rdf:type schema:Article;
         schema:about ?item;
         schema:name ?name;
         schema:isPartOf <https://fr.wikipedia.org/>;
         schema:name "Alpes-de-Haute-Provence"@fr.
    
    SERVICE wikibase:mwapi {
        bd:serviceParam wikibase:endpoint "fr.wikipedia.org";
                        wikibase:api "Generator";
                        mwapi:generator "allpages";
                        mwapi:gapfrom ?name;
                        mwapi:gapto ?name.
        ?pageid wikibase:apiOutput "@pageid".
    }
}

内容的提问来源于stack exchange,提问作者LeMoussel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 23:47:30