Search code examples
javastringsparql

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


Solution

  • 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.