[英]How can I translate a TupleExpr or a ParsedTupleQuery into the Query String?
I want to parse a query using rdf4j's SPARQLParser, modify the underlying query tree (=TupleExpr) and translate it back into a query string.我想使用 rdf4j 的 SPARQLParser 解析查询,修改底层查询树 (=TupleExpr) 并将其转换回查询字符串。 Is there a way to do that with rdf4j?
有没有办法用 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.打印出来的 output 是 null。
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.您需要使用
org.eclipse.rdf4j.queryrender.sparql.experimental.SparqlQueryRenderer
,它专门设计用于将 TupleExpr 转换回 SPARQL 查询字符串。
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.请注意,此组件仍处于实验阶段,不能保证完全涵盖所有 SPARQL 1.1 功能。
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.顺便说一句,
getSourceString()
在这里不起作用的原因是该方法旨在返回生成解析查询的输入源字符串。 Since in your case you've just created a new ParsedQuery
object from scratch, there is no source string.由于在您的情况下您刚刚从头开始创建了一个新的
ParsedQuery
object,因此没有源字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.