Search code examples
sparqlrdf4j

Parse portions of SPARQL and reuse them in RDF4j SparqlBuilder


I use some configuration logic to generate Sparql queries with RDF4j and the SparqlBuilder.

// prepare selectVariables, prefixes and whereCondition according to configuration

SelectQuery mainQuery = Queries.SELECT(selectVariables)
            .prefix(prefixes)
            .where(whereCondition)

Now I wish to allow for users to configure custom WHERE conditions to be used as SubSelects and composed with the rest of the query logic.

Since the configuration is YAML and the users are trained in Sparql, I wished to let users specify custom patterns as YAML multiline strings like this example

customQuery: |
  ?_ wdt:P31 wd:Q5;       
     wdt:P19/wdt:P131* wd:Q60.

This way I can let the users customize freely the different queries that I will generate based on the configured condition.

The problem

I already managed to parse the query fragment using RDFj SparqlParser:

SPARQLParserFactory PARSER_FACTORY = new SPARQLParserFactory();
QueryParser parser = PARSER_FACTORY.getParser();
ParsedQuery parsed = parser.parseQuery(query, null);
ProjectionVisitor projectionVisitor = new ProjectionVisitor();
parsed.getTupleExpr().visit(projectionVisitor);

TupleExpr parsedExpression = projectionVisitor.getProjectionArg();

but I can't use the parsedExpression into the SparqlBuilder methods, the nodes representation for the parser looks incompatible with the ones for the fluent builder.

Is there any way to use parsed expressions inside the SparqlBuilder?


Solution

  • No, it is not possible to use parsed expressions in the SparqlBuilder. What you could probably do instead though (freewheeling here) is use the SparqlBuilder to generate a query with a placeholder pattern of some sort, parse that, and then use a parse tree visitor to find that placeholder pattern and replace it with the custom parsed expression you got from the user.