Reputation: 1
I have a python script that queries DBpedia using 2 SPARQL queries, and, for each of the queries, puts the result in a list. Then I make a set of this list to remove duplicates, and I have the results I need. This seems like an inefficient way of doing it, if there is a possibility of combining the queries to speed up this process.
Can someone who is experienced at SQL SPARQL help me combine these queries to speed up my python script?
For context: I want the label names of both the property and value of all properties for the DBpedia page of the queryword I give to this function (Query 1) AND the ones that have a numerical/textual value and not a label as value (Query 2).
def querydbpedia(queryword):
mylist = list()
sparql = SPARQLWrapper("http://dbpedia.org/sparql")
sparql.setQuery("""
prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT DISTINCT ?pLabel ?oLabel ?o WHERE {
<http://dbpedia.org/resource/""" + queryword + """> ?p ?o.
?p rdfs:label ?pLabel .
?o rdfs:label ?oLabel .
FILTER(LANG(?pLabel) = "" || LANGMATCHES(LANG(?pLabel), "en"))
FILTER(LANG(?oLabel) = "" || LANGMATCHES(LANG(?oLabel), "en"))
}
""")
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
for result in results["results"]["bindings"]:
mystr = (result["pLabel"]["value"] + " - " + result["oLabel"]["value"]).lower()
mylist.append(mystr)
sparql.setQuery("""
prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT DISTINCT ?pLabel ?oLabel ?o WHERE {
<http://dbpedia.org/resource/""" + queryword + """> ?p ?o.
?p rdfs:label ?pLabel .
OPTIONAL {?o rdfs:label ?oLabel} .
FILTER(LANG(?pLabel) = "" || LANGMATCHES(LANG(?pLabel), "en"))
FILTER(LANG(?o) = "" || LANGMATCHES(LANG(?o), "en"))
}
""")
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
for result in results["results"]["bindings"]:
mystr = (result["pLabel"]["value"] + " - " + result["o"]["value"]).lower()
if not ("abstract" in mystr):
mylist.append(mystr)
mylist = list(set(mylist))
return mylist
Upvotes: 0
Views: 299
Reputation: 8465
You could use SPARQL UNION
.
Or you could use SPARQL 1.1 VALUES
, to apply the same query to multiple resources. For example --
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT DISTINCT ?s ?pLabel ?oLabel ?o WHERE {
?s ?p ?o.
VALUES ?s {<http://dbpedia.org/resource/Leipzig> <http://dbpedia.org/resource/Dresden>}
?p rdfs:label ?pLabel .
?o rdfs:label ?oLabel .
FILTER(LANG(?pLabel) = "" || LANGMATCHES(LANG(?pLabel), "en"))
FILTER(LANG(?oLabel) = "" || LANGMATCHES(LANG(?oLabel), "en"))
}
Upvotes: 1