Reputation: 459
I'm playing around with Sesame's queryparser-sparql lib, but I can't seem to get OPTIONAL
statements from a parsed query.
Given the query:
PREFIX ex: <http://example.com/#>
SELECT * WHERE {
?s a ex:Foo .
OPTIONAL { ?s ex:someProperty ?property }
} LIMIT 10
Parsing it with the following code (using Sesame 2.7.2):
SPARQLParserFactory factory = new SPARQLParserFactory();
QueryParser parser = factory.getParser();
ParsedQuery parsedQuery = parser.parseQuery(sparqlQuery, null);
StatementPatternCollector collector = new StatementPatternCollector();
TupleExpr tupleExpr = parsedQuery.getTupleExpr();
tupleExpr.visit(collector);
for (StatementPattern pattern : collector.getStatementPatterns()) {
System.out.println(pattern);
}
printing parsedQuery
gives:
Slice ( limit=10 )
Projection
ProjectionElemList
ProjectionElem "s"
ProjectionElem "property"
LeftJoin
StatementPattern
Var (name=s)
Var (name=-const-1, value=http://www.w3.org/1999/02/22-rdf-syntax-ns#type, anonymous)
Var (name=-const-2, value=http://example.com/#Foo, anonymous)
StatementPattern
Var (name=s)
Var (name=-const-3, value=http://example.com/#someProperty, anonymous)
Var (name=property)
printing each pattern
gives:
StatementPattern
Var (name=s)
Var (name=-const-1, value=http://www.w3.org/1999/02/22-rdf-syntax-ns#type, anonymous)
Var (name=-const-2, value=http://example.com/#Foo, anonymous)
StatementPattern
Var (name=s)
Var (name=-const-3, value=http://example.com/#someProperty, anonymous)
Var (name=property)
How can I get information from a StatementPattern
on whether or not it is OPTIONAL
?
Upvotes: 1
Views: 520
Reputation: 22052
The only way to figure that out is to check whether it occurs as (part of) a right-hand argument of a LeftJoin
. A relatively simply way to figure that out is to implement a QueryModelVisitor
that sets a flag of some sort whenever it encounters a left join and descends down its right-hand side argument.
Alternatively, you can propagate back up in the query model from the StatementPattern
via getParent
and inspect the tree like that - this may be more difficult though as the LeftJoin
may not necessarily be the immediate parent of the SP.
Upvotes: 1