How can I translate a TupleExpr or a ParsedTupleQuery into the Query String?

60 Views Asked by At

I want to parse a query using rdf4j's SPARQLParser, modify the underlying query tree (=TupleExpr) and translate it back into a query string. Is there a way to do that with rdf4j?

I tried the following but it didn't work

 SPARQLParser parser = new SPARQLParser();
 ParsedQuery originalQuery =  parser.parseQuery(query, null);
    if (originalQuery instanceof ParsedTupleQuery) {
        TupleExpr queryTree = originalQuery.getTupleExpr();
        queryTree.visit(myQueryModelVisitor());
        originalQuery.setTupleExpr(queryTree);
        System.out.println(queryTree);
        ParsedQuery tsQuery = new ParsedTupleQuery(queryTree);
        System.out.println(tsQuery.getSourceString());

    }

the printed output is null.

1

There are 1 best solutions below

0
On

You'll want to use the org.eclipse.rdf4j.queryrender.sparql.experimental.SparqlQueryRenderer which is specifically designed to transform a TupleExpr back into a SPARQL query string.

Roughly, like this:

SPARQLParser parser = new SPARQLParser();
 ParsedQuery originalQuery =  parser.parseQuery(query, null);
    if (originalQuery instanceof ParsedTupleQuery) {
        TupleExpr queryTree = originalQuery.getTupleExpr();
        queryTree.visit(myQueryModelVisitor());
        originalQuery.setTupleExpr(queryTree);
        System.out.println(queryTree);
        ParsedQuery tsQuery = new ParsedTupleQuery(queryTree);
        String transformedQuery = new SparqlQueryRenderer().render(tsQuery);
}

Note that this component is still experimental, and does not have guaranteed complete coverage of all SPARQL 1.1 features.

As an aside, the reason getSourceString() does not work here is that method is designed to return the input source string from which the parsed query was generated. Since in your case you've just created a new ParsedQuery object from scratch, there is no source string.