简体   繁体   中英

How to run a sparql query from Python over my GraphDB repository?

I'm trying to run a simple query:

"""
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    SELECT ?label
    WHERE { ?a rdfs:label ?label }
""")

Over my GraphDB repository, but from Python. After some searching I found that SPARQL wrapper can be used for this, but I'm not sure how to make python connect to my GraphDB (endpoint?). I have no experience with API's. What I have so far:

from SPARQLWrapper import SPARQLWrapper, JSON

sparql = SPARQLWrapper("http://192.168.0.12:7200/repositories/MyRepository")
sparql.setQuery("""
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    SELECT ?label
    WHERE { ?a rdfs:label ?label }
""")
sparql.setReturnFormat(JSON)
results = sparql.query().convert()

for result in results["results"]["bindings"]:
    print(result["label"]["value"])

print('---------------------------')

for result in results["results"]["bindings"]:
    print('%s: %s' % (result["label"]["xml:lang"], result["label"]["value"]))

I copied this example query from another stackoverflow, but only changed the subject of the where query so it works with my data, and it works with the repository they pointed to there ( http://dbpedia.org/sparql ), but not with the link that I get from the repository in graphDB.

Any ideas?

The key is to make sure the link you are using to connect to your repository is not the version GraphDB gives you, but the localhost version of that link. GraphDB provides you with an ipadress link. You have to replace the ip adress with "localhost" and it will work. (at least locally).

Considering that the solution mentioned by Robin may not work for everyone, I'll introduce the formal method for this case: STEP1 : Open your GraphDB -> Right sidebars -> Setup -> Repositories STEP2 : Find the repository interested -> click button "Copy repository URL to clickboard" STEP3 : Enter the copied URL between the quotations sparql = SPARQLWrapper("").

Then it should work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM