Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tingletech/2b77088e7a5ce06b42cb to your computer and use it in GitHub Desktop.
Save tingletech/2b77088e7a5ce06b42cb to your computer and use it in GitHub Desktop.
Groovy SPARQL Example
@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