Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build SPARQL queries in java?

Is there a library, which is able to build SPARQL queries programmatically like the CriteriaBuilder in JPA or to build the queries like with a PreparedStatement for SQL?

Similar (for SQL): Cleanest way to build an SQL string in Java

like image 367
Martin Schlagnitweit Avatar asked Aug 30 '11 21:08

Martin Schlagnitweit


1 Answers

You can build queries programmatically in Jena using two methods: syntax or algebra. There's an introduction in the jena wiki.

Using the algebra you'd do something like:

Op op;
BasicPattern pat = new BasicPattern();                 // Make a pattern
pat.add(pattern);                                      // Add our pattern match
op = new OpBGP(pat);                                   // Make a BGP from this pattern
op = OpFilter.filter(e, op);                           // Filter that pattern with our expression
op = new OpProject(op, Arrays.asList(Var.alloc("s"))); // Reduce to just ?s
Query q = OpAsQuery.asQuery(op);                       // Convert to a query
q.setQuerySelectType();                                // Make is a select query

(taken from the wiki page)

It's not CriteriaBuilder (nor was it intended to be), but is some of the way there. You OpJoin rather than AND, OpUnion when you want to OR, etc. The pain points are expressions in my experience: you probably want to parse them from a string.

like image 113
user205512 Avatar answered Sep 22 '22 03:09

user205512