Getting dbpedia results with optional properties

↘锁芯ラ 提交于 2019-12-24 13:25:42

问题


I'm building an app which shows information about entities of a given text. I'm using a sparqlwrapper library for Python to query DBpedia. I'm using the following code when I get a Person entity:

def get_person_data(einfo):
    data = {}
    try:
        uri = einfo['disambiguated']['dbpedia']

        sparql = SPARQLWrapper("http://dbpedia.org/sparql")
        query = u"""
        SELECT ?birthDate, ?birthName, ?birthPlace
        WHERE { <%s>
                dbpprop:birthDate ?birthDate ;
                dbpprop:birthName ?birthName ;
                dbpprop:birthPlace ?birthPlace
        }
        """ % uri
        sparql.setQuery(query)
        sparql.setReturnFormat(JSON)
        results = sparql.query().convert()

The problem with this code is that when a field is missing in the DBpedia page, the results return nothing. It's difficult to know which properties are present in all the entities of a given type, so I'd like to define some desirable properties and then get the ones present. I tried querying with something like:

SELECT * WHERE {
  ?x rdfs:label "New York"@en.
  ?x dbpedia-owl:abstract ?abstract.
  OPTIONAL { 
  ?x dbpedia-owl:areaTotal ?areaTotal.
  ?x dbpprop:governor ?governor.
  ?x dbpprop:birthPlace ?birthPlace.
  }
  FILTER (LANG(?abstract) = 'en')
}

In this case, New York doesn't have a birthPlace, so I end up getting only the abstract information. I'd like to get areaTotal and governor too.


回答1:


The entire optional block either matches or it doesn't. If you want to optionally match a few different things, you need multiple optional blocks, as in

SELECT * WHERE {
  ?x rdfs:label "New York"@en.
  ?x dbpedia-owl:abstract ?abstract.
  OPTIONAL { ?x dbpedia-owl:areaTotal ?areaTotal. }
  OPTIONAL { ?x dbpprop:governor ?governor. }
  OPTIONAL { ?x dbpprop:birthPlace ?birthPlace. }
  FILTER (LANG(?abstract) = 'en')
}

SPARQL results



来源:https://stackoverflow.com/questions/18190648/getting-dbpedia-results-with-optional-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!