DbPedia上的Sparql查询返回不重复的对象

时间:2015-02-10 16:17:23

标签: python sparql semantic-web dbpedia sparqlwrapper

我正在尝试在DBPedia上执行此Sparql查询,但它似乎忽略了 DISTINCT

SELECT DISTINCT ?source ?title ?content ?topic
            WHERE {
                ?source rdfs:label ?title ;
                <http://dbpedia.org/ontology/abstract> ?content ;
                foaf:isPrimaryTopicOf ?topic .
                ?title bif:contains "php" .
}

实际上,如果您尝试运行查询,结果是这样的:

我正在运行python文件中的查询,此代码返回一个json:

query_rdf = ""
query_rdf += '''
              SELECT DISTINCT ?source ?title ?content ?topic
                WHERE {
                        ?source rdfs:label ?title ;
                        <http://dbpedia.org/ontology/abstract> ?content ;
                        foaf:isPrimaryTopicOf ?topic .
                        ?title bif:contains "php" . 
                }
        '''      
__3store = "http://dbpedia.org/sparql"       
sparql = SPARQLWrapper (__3store,returnFormat="json")
sparql.setQuery(query_rdf)
result = sparql.query().convert()
print json.dumps(result, separators=(',',':'))

1 个答案:

答案 0 :(得分:2)

DISTINCT关键字表示每个整体上与其他行不同。在您显示的结果中,我看到英语(en),西班牙语(es)和阿拉伯语(ar)的标签和摘要。如果您有以下数据:

:a rdfs:label "..."@en, "..."@es ;
   dbpedia-owl:abstract "..."@en, "..."@es ;
   foaf:isPrimaryTopicOf :aa .

并运行查询

select distinct ?source ?label ?abstract ?topic where {
  ?source rdfs:label ?label ;
          dbpedia-owl:abstract ?abstract ;
          foaf:isPrimaryTopicOf ?topic
}

您的结果中会有四行,因为有四种不同的组合:

  

1个源×2个标签×2个摘要×1个主题= 4行

如果要将标签和摘要限制为单一语言(例如英语),则只需过滤结果即可。 E.g:

select distinct ?source ?label ?abstract ?topic where {
  ?source rdfs:label ?label ;
          dbpedia-owl:abstract ?abstract ;
          foaf:isPrimaryTopicOf ?topic .
          ?label bif:contains "php" . 
  filter( langMatches(lang(?label),"en")
          && langMatches(lang(?abstract),"en") )
}

SPARQL results