Processing SPARQL Queries using Java
ARQ - A SPARQL Processor for Jena

Raji GHAWI
26/01/2009
Outline



Query Execution



Query Analysis

26/01/2009

2
1. Query Execution
Query Execution
Read a file into a model

String fileName = "../univ.owl";
// Model model = ModelFactory.createDefaultModel();
OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM);
try {
File file = new File(fileName);
FileReader reader = new FileReader(file);
model.read(reader,null);
} catch (Exception e) {
e.printStackTrace();
}

26/01/2009

4
Query Execution
Put the query as a string

PREFIX my:<http://www.something.com/myontology#>
PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>
SELECT ?stud ?dip
WHERE {
?stud
my:enrolledIn
}

?dip.

String sparqlQuery =
"PREFIX my:<http://www.something.com/myontology#>n" +
"PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>n" +
"n" +
"SELECT ?stud ?dip n" +
"WHERE {n" +
"
?stud
my:enrolledIn
?dip.n" +
"} ";

26/01/2009

5
Query Execution
Execute the Query

encapsulates a parsed query

read a textual query from a String
Query query = QueryFactory.create(sparqlQuery);
QueryExecution qe = QueryExecutionFactory.create(query, model);
ResultSet results = qe.execSelect();

a single execution of a query

26/01/2009

6
Query Execution
Print Query Results

result set

ResultSetFormatter.out(System.out, results, query);

textual format

standard output

----------------------------------| stud
| dip
|
===================================
| my:Simon_Thevenin | my:M2_BDIA |
| my:Raji_Ghawi
| my:Doctorat |
| my:Kamel_Boulil
| my:M2_BDIA |
-----------------------------------

26/01/2009

output

7
XML format
ResultSetFormatter.outputAsXML(System.out, results);

26/01/2009

<?xml version="1.0"?>
<sparql
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:xs="http://www.w3.org/2001/XMLSchema#"
xmlns="http://www.w3.org/2005/sparql-results#" >
<head>
<variable name="stud"/>
<variable name="dip"/>
</head>
<results ordered="false" distinct="false">
<result>
<binding name="stud">
<uri>http://www.something.com/myontology#Simon_Thevenin</uri>
</binding>
<binding name="dip">
<uri>http://www.something.com/myontology#M2_BDIA</uri>
</binding>
</result>
<result>
<binding name="stud">
<uri>http://www.something.com/myontology#Raji_Ghawi</uri>
</binding>
<binding name="dip">
<uri>http://www.something.com/myontology#Doctorat</uri>
</binding>
</result>
<result>
<binding name="stud">
<uri>http://www.something.com/myontology#Kamel_Boulil</uri>
</binding>
<binding name="dip">
<uri>http://www.something.com/myontology#M2_BDIA</uri>
</binding>
</result>
</results>
</sparql>

output

8
Query Execution
Save Query Results to String

MyOutputStream myOutput = new MyOutputStream();
ResultSetFormatter.out(myOutput, results, query);
String sparqlResults = myOutput.getString();

class MyOutputStream extends OutputStream {
StringBuffer buf;
public MyOutputStream(){
buf = new StringBuffer();
}
public void write(int character) throws IOException {
buf.append((char) character);
}
public String getString() {
return buf.toString();
}
}
26/01/2009

9
Query Execution
Retrieve Query Solutions
ResultSet results = qe.execSelect();
List vars = results.getResultVars();
while(results.hasNext()) {
QuerySolution qs = results.nextSolution();
System.out.println("--------- solution ---------");
for (int i = 0; i < vars.size(); i++) {
String var = vars.get(i).toString();
RDFNode node = qs.get(var);
System.out.println(var + "t" + node.toString());
}
}

--------stud
dip
--------stud
dip
--------stud
dip
26/01/2009

output

solution --------http://www.something.com/myontology#Guillermo_Gomez
http://www.something.com/myontology#These
solution --------http://www.something.com/myontology#Elie_Raad
http://www.something.com/myontology#M2-BDIA
solution --------http://www.something.com/myontology#Raji_Ghawi
http://www.something.com/myontology#M2-BDIA

10
ResultSet results = qe.execSelect();
List vars = results.getResultVars();
PrefixMapping pm = query.getPrefixMapping();
while (results.hasNext()) {
QuerySolution qs = results.nextSolution();
System.out.println("--------- solution ---------");
for (int i = 0; i < vars.size(); i++) {
String var = vars.get(i).toString();
RDFNode node = qs.get(var);
String text = "";
if(node.isURIResource()){
text = pm.shortForm(node.asNode().getURI());
} else {
text = node.toString();
}
System.out.println(var+"t"+text);
}
}
--------stud
dip
--------stud
dip
--------stud
dip
26/01/2009

solution --------my:Guillermo_Gomez
my:These
solution --------my:Elie_Raad
my:M2-BDIA
solution --------my:Raji_Ghawi
my:M2-BDIA

output

11
2. Query Analysis
Query Analysis

PREFIX my:<http://www.something.com/myontology#>
PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>
SELECT ?stud ?modName
WHERE {
?stud
rdf:type
my:Student .
?stud
my:enrolledIn
?dip .
?dip
my:hasModule
?mod .
?mod
my:moduleName
?modName.
FILTER
(?modName='Databases').
}

26/01/2009

13
Query Analysis
Put the Query in a String

String sparqlQuery =
"PREFIX my:<http://www.something.com/myontology#>n" +
"PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>n" +
"n" +
"SELECT ?stud ?modName n" +
"WHERE {n" +
"
?stud
rdf:type
my:Student .n" +
"
?stud
my:enrolledIn
?dip .n" +
"
?dip
my:hasModule
?mod .n" +
"
?mod
my:moduleName
?modName.n" +
"
FILTER(?modName='Databases').n" +
"} ";

26/01/2009

14
Query Analysis
Create the Query

Query query = QueryFactory.create(sparqlQuery);
System.out.println("---------- Query
System.out.println(query);

----------");

output

---------- Query ---------PREFIX rdf:
<http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX my:
<http://www.something.com/myontology#>
SELECT ?stud ?modName
WHERE
{ ?stud my:enrolledIn ?dip ;
rdf:type
my:Student ;
my:enrolledIn ?dip .
?dip
my:hasModule
?mod .
?mod
my:moduleName ?modName .
FILTER ( ?modName = "Databases" )
}
26/01/2009

15
Query Analysis
Prefix Mapping

System.out.println("------ Prefix Mapping ------");
Map map = query.getPrefixMapping().getNsPrefixMap();
Iterator pmIter= map.entrySet().iterator();
while (pmIter.hasNext()) {
Entry ent = (Entry) pmIter.next();
String prefix = ent.getKey().toString();
String namespace = ent.getValue().toString();
System.out.println(prefix+"t"+namespace);
}

------ Prefix Mapping -----rdf
http://www.w3.org/1999/02/22-rdf-syntax-ns#
my
http://www.something.com/myontology#

26/01/2009

output

16
Query Analysis
Retrieve Result Variables

System.out.println("------ Result Variables ------");
List varList = query.getResultVars();
for (int i = 0; i < varList.size(); i++) {
String var = varList.get(i).toString();
System.out.println(var);
}

------ Result Variables -----stud
modName

output

query.isQueryResultStar()
query.isDistinct()
26/01/2009

17
Query Analysis
Retrieve All Variables

System.out.println("------- All Variables --------");
Iterator varIter = query.getQueryBlock().varsMentioned().iterator();
while(varIter.hasNext()){
String var = varIter.next().toString();
System.out.println(var);
}

------- All Variables -------stud
dip
mod
modName

26/01/2009

output

18
Query Analysis
Fetch Query Elements
ElementGroup eg = (ElementGroup) query.getQueryBlock().getPatternElement();
List elemList = eg.getElements();
for(int i=0; i<elemList.size(); i++){
Element elem = (Element) elemList.get(i);
try{
if (elem instanceof ElementOptional) {
ElementOptional elOp = (ElementOptional) elem;
// ....
} else if (elem instanceof ElementFilter) {
ElementFilter elf = (ElementFilter) elem;
// ....
} else if (elem instanceof ElementTriplePattern) {
ElementTriplePattern etp = (ElementTriplePattern) elem;
// ....
}
} catch(ClassCastException e){
e.printStackTrace();
}
}

26/01/2009

19
Query Analysis
ElementOptional
ElementOptional elOp = (ElementOptional) elem;
Iterator iter = elOp.varsMentioned().iterator();
// ....
ElementGroup newElemGrp = (ElementGroup) elOp.getElement();
List elemList = eg.getElements();
for(int i=0; i<elemList.size(); i++){
// ....
}

26/01/2009

20
Query Analysis
ElementFilter
ElementFilter elf = (ElementFilter) elem;
Iterator iter = elf.varsMentioned().iterator();
// ....
Expr expr = elf.getConstraint().getExpr();
// ....

26/01/2009

21
Query Analysis
Expr

E_LogicalAnd
E_LogicalOr
E_Equals
E_NotEquals
E_LessThan
E_LessThanOrEqual
E_GreaterThan
E_GreaterThanOrEqual
E_LogicalNot

getLeft()
getRight()

getSubExpr()

E_Regex
NodeVar
if (expr instanceof E_LogicalAnd) {
getVarName()
E_LogicalAnd and = (E_LogicalAnd) expr;
NodeValueInteger
Expr left = and.getLeft();
NodeValueFloat
Expr right = and.getRight();
asString()
NodeValueDecimal
//
NodeValueString
} else if (expr instanceof E_LogicalOr) {
...
// .. ..
}
// .. ..
else if (expr instanceof E_Regex) {
E_Regex re = (E_Regex) expr;
String pattern = ((NodeValueString) re.getPattern()).asString();
String varName = re.getRegexExpr().getVarName().toString();
// .. ..
}
26/01/2009

22
Query Analysis
ElementTriplePattern
ElementTriplePattern etp = (ElementTriplePattern) elem;
Triple triple = etp.getTriple();
Node subject = triple.getSubject();
Node predicate = triple.getPredicate();
Node object = triple.getObject();






SELECT ?stud ?dip
WHERE {
?stud
my:enrolledIn
?dip
my:diplomaName
}

boolean isURI()
boolean isLiteral()
boolean isVariable()

Subject
Variable
26/01/2009

URI

Predicate

?dip.
"BDIA".

Object
Literal
23
Subject

Predicate

Object

URI

Literal
Variable

26/01/2009

24
Query Analysis
OrderBy

if(query.getOrderBy() != null){
Iterator orderBy = query.getOrderBy().iterator();
while (orderBy.hasNext()) {
SortCondition sc = (SortCondition) orderBy.next();
Expr exp = sc.getExpression();
if(exp.isVariable()){
String obv = exp.getVarName();
// ....
}
}
}

26/01/2009

25
References


ARQ - A SPARQL Processor for Jena




http://jena.sourceforge.net/ARQ/

Search RDF data with SPARQL


http://www.ibm.com/developerworks/xml/library/j-sparql

26/01/2009

26

More Related Content

PDF
Pwning in c++ (basic)
PDF
Universal metrics with Apache Beam
PDF
Node JS Crash Course
PPT
Spring data presentation
PDF
Spring Boot
PPTX
Java and OWL
PDF
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
PDF
In-memory OLTP storage with persistence and transaction support
Pwning in c++ (basic)
Universal metrics with Apache Beam
Node JS Crash Course
Spring data presentation
Spring Boot
Java and OWL
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
In-memory OLTP storage with persistence and transaction support

What's hot (20)

PPTX
Making Java more dynamic: runtime code generation for the JVM
PPTX
Java 8 Lambda and Streams
PDF
A Spring Data’s Guide to Persistence
PDF
Variable hoisting in JavaScript
PDF
Networking in Java with NIO and Netty
PDF
Kotlin Coroutines Reloaded
PPTX
關於SQL Injection的那些奇技淫巧
PDF
REST APIs with Spring
PDF
Java 8 Lambda Expressions
PPT
Jsp/Servlet
PDF
The innerHTML Apocalypse
PPT
Hive ICDE 2010
PDF
Java 8 Lambda Built-in Functional Interfaces
PDF
PUC SE Day 2019 - SpringBoot
PPTX
Uploading a file with php
PDF
The Joy of SciPy
PDF
Functional Programming Patterns (BuildStuff '14)
PPTX
Introduction to Apache Spark Developer Training
PPTX
Python- Regular expression
PDF
JavaScript Execution Context
Making Java more dynamic: runtime code generation for the JVM
Java 8 Lambda and Streams
A Spring Data’s Guide to Persistence
Variable hoisting in JavaScript
Networking in Java with NIO and Netty
Kotlin Coroutines Reloaded
關於SQL Injection的那些奇技淫巧
REST APIs with Spring
Java 8 Lambda Expressions
Jsp/Servlet
The innerHTML Apocalypse
Hive ICDE 2010
Java 8 Lambda Built-in Functional Interfaces
PUC SE Day 2019 - SpringBoot
Uploading a file with php
The Joy of SciPy
Functional Programming Patterns (BuildStuff '14)
Introduction to Apache Spark Developer Training
Python- Regular expression
JavaScript Execution Context
Ad

Viewers also liked (20)

PDF
Jena – A Semantic Web Framework for Java
PDF
An Introduction to the Jena API
PPTX
Jena Programming
PPT
070517 Jena
PPT
Database-to-Ontology Mapping Generation for Semantic Interoperability
PPT
Twinkle: A SPARQL Query Tool
PPT
Understanding Mobile Phone Requirements
PPT
Rdf And Rdf Schema For Ontology Specification
PDF
Selecting with SPARQL
PDF
Rest web services com Java
PDF
Semantic Technologies and Triplestores for Business Intelligence
PDF
Linked Data on the BBC
PPTX
Triplestore and SPARQL
PPT
OWL-XML-Summer-School-09
PDF
Diseño de Ontologías: Protégé - OWL: SPARQL
PDF
RuleML 2015: Ontology Reasoning using Rules in an eHealth Context
PDF
Challenge@RuleML2015 Transformation and aggregation preprocessing for top-k r...
PDF
정부3.0과직접민주주의
PDF
Learning sparql 2012 12
PDF
WebTech Tutorial Querying DBPedia
Jena – A Semantic Web Framework for Java
An Introduction to the Jena API
Jena Programming
070517 Jena
Database-to-Ontology Mapping Generation for Semantic Interoperability
Twinkle: A SPARQL Query Tool
Understanding Mobile Phone Requirements
Rdf And Rdf Schema For Ontology Specification
Selecting with SPARQL
Rest web services com Java
Semantic Technologies and Triplestores for Business Intelligence
Linked Data on the BBC
Triplestore and SPARQL
OWL-XML-Summer-School-09
Diseño de Ontologías: Protégé - OWL: SPARQL
RuleML 2015: Ontology Reasoning using Rules in an eHealth Context
Challenge@RuleML2015 Transformation and aggregation preprocessing for top-k r...
정부3.0과직접민주주의
Learning sparql 2012 12
WebTech Tutorial Querying DBPedia
Ad

Similar to Java and SPARQL (20)

PPTX
Sparql
PPTX
SPARQL
PPT
Jena framework
PPTX
What;s Coming In SPARQL2?
PPTX
4 sw architectures and sparql
PPTX
SWT Lecture Session 4 - SW architectures and SPARQL
PPTX
SPARQL Cheat Sheet
PPTX
Strategies for Processing and Explaining Distributed Queries on Linked Data
PDF
CliqueSquare processing
PPT
Semantic Web
PPT
Semantic Web
ODP
Fast, Faster and Super-Fast Queries
PDF
final_copy_camera_ready_paper (7)
PPTX
High-performance model queries
PDF
Querydsl fin jug - june 2012
PPTX
SPARQL introduction and training (130+ slides with exercices)
PPTX
Semantic web meetup – sparql tutorial
PPT
Querying the Semantic Web with SPARQL
PDF
Querydsl overview 2014
PDF
Solr Query Parsing
Sparql
SPARQL
Jena framework
What;s Coming In SPARQL2?
4 sw architectures and sparql
SWT Lecture Session 4 - SW architectures and SPARQL
SPARQL Cheat Sheet
Strategies for Processing and Explaining Distributed Queries on Linked Data
CliqueSquare processing
Semantic Web
Semantic Web
Fast, Faster and Super-Fast Queries
final_copy_camera_ready_paper (7)
High-performance model queries
Querydsl fin jug - june 2012
SPARQL introduction and training (130+ slides with exercices)
Semantic web meetup – sparql tutorial
Querying the Semantic Web with SPARQL
Querydsl overview 2014
Solr Query Parsing

More from Raji Ghawi (9)

PPTX
Database Programming Techniques
PPTX
Java and XML Schema
PPTX
Java and XML
PPTX
XQuery
PPTX
XPath
PPT
Ontology-based Cooperation of Information Systems
PPT
OWSCIS: Ontology and Web Service based Cooperation of Information Sources
PPT
Coopération des Systèmes d'Informations basée sur les Ontologies
PPT
Building Ontologies from Multiple Information Sources
Database Programming Techniques
Java and XML Schema
Java and XML
XQuery
XPath
Ontology-based Cooperation of Information Systems
OWSCIS: Ontology and Web Service based Cooperation of Information Sources
Coopération des Systèmes d'Informations basée sur les Ontologies
Building Ontologies from Multiple Information Sources

Recently uploaded (20)

PDF
Introduction to c language from lecture slides
PDF
Human Computer Interaction Miterm Lesson
PDF
Technical Debt in the AI Coding Era - By Antonio Bianco
PPTX
How to use fields_get method in Odoo 18
PPTX
Blending method and technology for hydrogen.pptx
PDF
Child-friendly e-learning for artificial intelligence education in Indonesia:...
PDF
NewMind AI Journal Monthly Chronicles - August 2025
PPTX
maintenance powerrpoint for adaprive and preventive
PDF
State of AI in Business 2025 - MIT NANDA
PPTX
Rise of the Digital Control Grid Zeee Media and Hope and Tivon FTWProject.com
PDF
“Introduction to Designing with AI Agents,” a Presentation from Amazon Web Se...
PDF
The Digital Engine Room: Unlocking APAC’s Economic and Digital Potential thro...
PDF
Uncertainty-aware contextual multi-armed bandits for recommendations in e-com...
PDF
ELLIE29.pdfWETWETAWTAWETAETAETERTRTERTER
PDF
EIS-Webinar-Regulated-Industries-2025-08.pdf
PDF
Intravenous drug administration application for pediatric patients via augmen...
PPTX
From Curiosity to ROI — Cost-Benefit Analysis of Agentic Automation [3/6]
PPTX
Strategic Picks — Prioritising the Right Agentic Use Cases [2/6]
PDF
The AI Revolution in Customer Service - 2025
PPTX
Information-Technology-in-Human-Society (2).pptx
Introduction to c language from lecture slides
Human Computer Interaction Miterm Lesson
Technical Debt in the AI Coding Era - By Antonio Bianco
How to use fields_get method in Odoo 18
Blending method and technology for hydrogen.pptx
Child-friendly e-learning for artificial intelligence education in Indonesia:...
NewMind AI Journal Monthly Chronicles - August 2025
maintenance powerrpoint for adaprive and preventive
State of AI in Business 2025 - MIT NANDA
Rise of the Digital Control Grid Zeee Media and Hope and Tivon FTWProject.com
“Introduction to Designing with AI Agents,” a Presentation from Amazon Web Se...
The Digital Engine Room: Unlocking APAC’s Economic and Digital Potential thro...
Uncertainty-aware contextual multi-armed bandits for recommendations in e-com...
ELLIE29.pdfWETWETAWTAWETAETAETERTRTERTER
EIS-Webinar-Regulated-Industries-2025-08.pdf
Intravenous drug administration application for pediatric patients via augmen...
From Curiosity to ROI — Cost-Benefit Analysis of Agentic Automation [3/6]
Strategic Picks — Prioritising the Right Agentic Use Cases [2/6]
The AI Revolution in Customer Service - 2025
Information-Technology-in-Human-Society (2).pptx

Java and SPARQL

  • 1. Processing SPARQL Queries using Java ARQ - A SPARQL Processor for Jena Raji GHAWI 26/01/2009
  • 4. Query Execution Read a file into a model String fileName = "../univ.owl"; // Model model = ModelFactory.createDefaultModel(); OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM); try { File file = new File(fileName); FileReader reader = new FileReader(file); model.read(reader,null); } catch (Exception e) { e.printStackTrace(); } 26/01/2009 4
  • 5. Query Execution Put the query as a string PREFIX my:<http://www.something.com/myontology#> PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#> SELECT ?stud ?dip WHERE { ?stud my:enrolledIn } ?dip. String sparqlQuery = "PREFIX my:<http://www.something.com/myontology#>n" + "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>n" + "n" + "SELECT ?stud ?dip n" + "WHERE {n" + " ?stud my:enrolledIn ?dip.n" + "} "; 26/01/2009 5
  • 6. Query Execution Execute the Query encapsulates a parsed query read a textual query from a String Query query = QueryFactory.create(sparqlQuery); QueryExecution qe = QueryExecutionFactory.create(query, model); ResultSet results = qe.execSelect(); a single execution of a query 26/01/2009 6
  • 7. Query Execution Print Query Results result set ResultSetFormatter.out(System.out, results, query); textual format standard output ----------------------------------| stud | dip | =================================== | my:Simon_Thevenin | my:M2_BDIA | | my:Raji_Ghawi | my:Doctorat | | my:Kamel_Boulil | my:M2_BDIA | ----------------------------------- 26/01/2009 output 7
  • 8. XML format ResultSetFormatter.outputAsXML(System.out, results); 26/01/2009 <?xml version="1.0"?> <sparql xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:xs="http://www.w3.org/2001/XMLSchema#" xmlns="http://www.w3.org/2005/sparql-results#" > <head> <variable name="stud"/> <variable name="dip"/> </head> <results ordered="false" distinct="false"> <result> <binding name="stud"> <uri>http://www.something.com/myontology#Simon_Thevenin</uri> </binding> <binding name="dip"> <uri>http://www.something.com/myontology#M2_BDIA</uri> </binding> </result> <result> <binding name="stud"> <uri>http://www.something.com/myontology#Raji_Ghawi</uri> </binding> <binding name="dip"> <uri>http://www.something.com/myontology#Doctorat</uri> </binding> </result> <result> <binding name="stud"> <uri>http://www.something.com/myontology#Kamel_Boulil</uri> </binding> <binding name="dip"> <uri>http://www.something.com/myontology#M2_BDIA</uri> </binding> </result> </results> </sparql> output 8
  • 9. Query Execution Save Query Results to String MyOutputStream myOutput = new MyOutputStream(); ResultSetFormatter.out(myOutput, results, query); String sparqlResults = myOutput.getString(); class MyOutputStream extends OutputStream { StringBuffer buf; public MyOutputStream(){ buf = new StringBuffer(); } public void write(int character) throws IOException { buf.append((char) character); } public String getString() { return buf.toString(); } } 26/01/2009 9
  • 10. Query Execution Retrieve Query Solutions ResultSet results = qe.execSelect(); List vars = results.getResultVars(); while(results.hasNext()) { QuerySolution qs = results.nextSolution(); System.out.println("--------- solution ---------"); for (int i = 0; i < vars.size(); i++) { String var = vars.get(i).toString(); RDFNode node = qs.get(var); System.out.println(var + "t" + node.toString()); } } --------stud dip --------stud dip --------stud dip 26/01/2009 output solution --------http://www.something.com/myontology#Guillermo_Gomez http://www.something.com/myontology#These solution --------http://www.something.com/myontology#Elie_Raad http://www.something.com/myontology#M2-BDIA solution --------http://www.something.com/myontology#Raji_Ghawi http://www.something.com/myontology#M2-BDIA 10
  • 11. ResultSet results = qe.execSelect(); List vars = results.getResultVars(); PrefixMapping pm = query.getPrefixMapping(); while (results.hasNext()) { QuerySolution qs = results.nextSolution(); System.out.println("--------- solution ---------"); for (int i = 0; i < vars.size(); i++) { String var = vars.get(i).toString(); RDFNode node = qs.get(var); String text = ""; if(node.isURIResource()){ text = pm.shortForm(node.asNode().getURI()); } else { text = node.toString(); } System.out.println(var+"t"+text); } } --------stud dip --------stud dip --------stud dip 26/01/2009 solution --------my:Guillermo_Gomez my:These solution --------my:Elie_Raad my:M2-BDIA solution --------my:Raji_Ghawi my:M2-BDIA output 11
  • 13. Query Analysis PREFIX my:<http://www.something.com/myontology#> PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#> SELECT ?stud ?modName WHERE { ?stud rdf:type my:Student . ?stud my:enrolledIn ?dip . ?dip my:hasModule ?mod . ?mod my:moduleName ?modName. FILTER (?modName='Databases'). } 26/01/2009 13
  • 14. Query Analysis Put the Query in a String String sparqlQuery = "PREFIX my:<http://www.something.com/myontology#>n" + "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>n" + "n" + "SELECT ?stud ?modName n" + "WHERE {n" + " ?stud rdf:type my:Student .n" + " ?stud my:enrolledIn ?dip .n" + " ?dip my:hasModule ?mod .n" + " ?mod my:moduleName ?modName.n" + " FILTER(?modName='Databases').n" + "} "; 26/01/2009 14
  • 15. Query Analysis Create the Query Query query = QueryFactory.create(sparqlQuery); System.out.println("---------- Query System.out.println(query); ----------"); output ---------- Query ---------PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX my: <http://www.something.com/myontology#> SELECT ?stud ?modName WHERE { ?stud my:enrolledIn ?dip ; rdf:type my:Student ; my:enrolledIn ?dip . ?dip my:hasModule ?mod . ?mod my:moduleName ?modName . FILTER ( ?modName = "Databases" ) } 26/01/2009 15
  • 16. Query Analysis Prefix Mapping System.out.println("------ Prefix Mapping ------"); Map map = query.getPrefixMapping().getNsPrefixMap(); Iterator pmIter= map.entrySet().iterator(); while (pmIter.hasNext()) { Entry ent = (Entry) pmIter.next(); String prefix = ent.getKey().toString(); String namespace = ent.getValue().toString(); System.out.println(prefix+"t"+namespace); } ------ Prefix Mapping -----rdf http://www.w3.org/1999/02/22-rdf-syntax-ns# my http://www.something.com/myontology# 26/01/2009 output 16
  • 17. Query Analysis Retrieve Result Variables System.out.println("------ Result Variables ------"); List varList = query.getResultVars(); for (int i = 0; i < varList.size(); i++) { String var = varList.get(i).toString(); System.out.println(var); } ------ Result Variables -----stud modName output query.isQueryResultStar() query.isDistinct() 26/01/2009 17
  • 18. Query Analysis Retrieve All Variables System.out.println("------- All Variables --------"); Iterator varIter = query.getQueryBlock().varsMentioned().iterator(); while(varIter.hasNext()){ String var = varIter.next().toString(); System.out.println(var); } ------- All Variables -------stud dip mod modName 26/01/2009 output 18
  • 19. Query Analysis Fetch Query Elements ElementGroup eg = (ElementGroup) query.getQueryBlock().getPatternElement(); List elemList = eg.getElements(); for(int i=0; i<elemList.size(); i++){ Element elem = (Element) elemList.get(i); try{ if (elem instanceof ElementOptional) { ElementOptional elOp = (ElementOptional) elem; // .... } else if (elem instanceof ElementFilter) { ElementFilter elf = (ElementFilter) elem; // .... } else if (elem instanceof ElementTriplePattern) { ElementTriplePattern etp = (ElementTriplePattern) elem; // .... } } catch(ClassCastException e){ e.printStackTrace(); } } 26/01/2009 19
  • 20. Query Analysis ElementOptional ElementOptional elOp = (ElementOptional) elem; Iterator iter = elOp.varsMentioned().iterator(); // .... ElementGroup newElemGrp = (ElementGroup) elOp.getElement(); List elemList = eg.getElements(); for(int i=0; i<elemList.size(); i++){ // .... } 26/01/2009 20
  • 21. Query Analysis ElementFilter ElementFilter elf = (ElementFilter) elem; Iterator iter = elf.varsMentioned().iterator(); // .... Expr expr = elf.getConstraint().getExpr(); // .... 26/01/2009 21
  • 22. Query Analysis Expr E_LogicalAnd E_LogicalOr E_Equals E_NotEquals E_LessThan E_LessThanOrEqual E_GreaterThan E_GreaterThanOrEqual E_LogicalNot getLeft() getRight() getSubExpr() E_Regex NodeVar if (expr instanceof E_LogicalAnd) { getVarName() E_LogicalAnd and = (E_LogicalAnd) expr; NodeValueInteger Expr left = and.getLeft(); NodeValueFloat Expr right = and.getRight(); asString() NodeValueDecimal // NodeValueString } else if (expr instanceof E_LogicalOr) { ... // .. .. } // .. .. else if (expr instanceof E_Regex) { E_Regex re = (E_Regex) expr; String pattern = ((NodeValueString) re.getPattern()).asString(); String varName = re.getRegexExpr().getVarName().toString(); // .. .. } 26/01/2009 22
  • 23. Query Analysis ElementTriplePattern ElementTriplePattern etp = (ElementTriplePattern) elem; Triple triple = etp.getTriple(); Node subject = triple.getSubject(); Node predicate = triple.getPredicate(); Node object = triple.getObject();    SELECT ?stud ?dip WHERE { ?stud my:enrolledIn ?dip my:diplomaName } boolean isURI() boolean isLiteral() boolean isVariable() Subject Variable 26/01/2009 URI Predicate ?dip. "BDIA". Object Literal 23
  • 25. Query Analysis OrderBy if(query.getOrderBy() != null){ Iterator orderBy = query.getOrderBy().iterator(); while (orderBy.hasNext()) { SortCondition sc = (SortCondition) orderBy.next(); Expr exp = sc.getExpression(); if(exp.isVariable()){ String obv = exp.getVarName(); // .... } } } 26/01/2009 25
  • 26. References  ARQ - A SPARQL Processor for Jena   http://jena.sourceforge.net/ARQ/ Search RDF data with SPARQL  http://www.ibm.com/developerworks/xml/library/j-sparql 26/01/2009 26