Created
June 27, 2011 05:30
-
-
Save AlBaker/1048357 to your computer and use it in GitHub Desktop.
Groovy SPARQL Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Grab('com.hp.hpl.jena:jena:2.6.4') | |
@Grab('com.hp.hpl.jena:arq:2.8.8') | |
import groovy.sparql.Sparql | |
// Can also take a Jena model as an argument | |
def sparql = new Sparql("http://dbpedia.org/sparql") | |
def query = """ | |
SELECT ?abstract | |
WHERE { | |
SERVICE <http://dbpedia.org/sparql> { | |
<http://dbpedia.org/resource/Groovy_%28programming_language%29> | |
<http://dbpedia.org/ontology/abstract> | |
?abstract | |
} | |
} LIMIT 5 | |
""" | |
sparql.eachRow query { row -> | |
println row.abstract | |
} | |
/** | |
* Also accept a map of binding parameters | |
* Entries of URI type can be used in Subject/Predicate slots in the triple | |
* Types of String are turned into Literals, so if you want literal URIs, use Strings | |
*/ | |
def predicate = new URI("http://dbpedia.org/ontology/abstract") | |
sparql.eachRow( query, [ uri:new URI("http://dbpedia.org/resource/Groovy_%28programming_language%29"), predicate:predicate], { row -> | |
println row.abstract | |
}) | |
/** | |
* Also the map can accept an object, and find subject/predicate/object fields | |
*/ | |
class GroovyWiki { | |
def subject = new URI("http://dbpedia.org/resource/Groovy_%28programming_language%29") | |
def predicate = new URI("http://dbpedia.org/ontology/abstract") | |
} | |
def obj = new GroovyWiki() | |
def map = [groovy:obj] | |
// note the form of the variables in the query is: | |
// mapEntry name plus Subject, Predicate, or Object(not shown) | |
query = """ | |
SELECT ?abstract | |
WHERE { | |
SERVICE <http://dbpedia.org/sparql> { | |
?groovySubject ?groovyPredicate ?abstract | |
} | |
} LIMIT 5 | |
""" | |
sparql = new Sparql("http://dbpedia.org/sparql") | |
sparql.eachRow( query, map, { row -> | |
println row.abstract | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment