问题
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