SPARQL parser for Java Code

后端 未结 2 1544
庸人自扰
庸人自扰 2021-01-04 22:52

Is any easy way to parse sparql query in variables for java, like Fyzz in python? How can Jena or sesame APIs been used?

2条回答
  •  执笔经年
    2021-01-04 23:56

    Here's how you can parse and manipulate a SPARQL query using Sesame:

    To parse:

    ParsedQuery pq = QueryParserUtil.parseQuery(QueryLanguage.SPARQL, queryString);
    

    The output of this is a ParsedQuery, which is an algebraic object representation of the query. If you wish to specifically get the parse tree itself, that is also possible:

    ASTQueryContainer parseTree = SyntaxTreeBuilder.parseQuery(queryString);
    

    You can then directly manipulate this abstract syntax tree by implementing a custom SyntaxTreeBuilderVisitor (tip: extend ASTVisitorBase so you only have to override the methods where you actually want to do something).

    If we go back to the algebraic model, you can execute the ParsedQuery on a Sesame Sail Repository:

    if (pq instanceof ParsedTupleQuery) {
            SailTupleQuery query = new SailTupleQuery(pq, repositoryConnection);
            TupleQueryResult result = query.evaluate();
    } else if (pq instanceof ParsedGraphQuery) {
            // etc for other query types
    }
    

    To manipulate the ParsedQuery before executing it, use a QueryModelVisitor implementation, e.g. your own custom query manipulator:

    QueryModelVisitor myVisitor = new MyCustomQueryModelVisitor();
    pq.getTupleExpr().visit(myVisitor);
    

    With such a custom query model visitor you have complete control over the query, to optimize it or indeed to rewrite into a different syntax.

    Whether to do this manipulation at the level of the abstract syntax tree (AST) or at the level of the query model is a matter of taste: the query model gives you more flexbility in terms of query planning/optimization and partial rewrites (for later execution on a Sesame store), while if your goal is to completely rewrite the query for another purpose (e.g. executing it on a non-Sesame store), manipulating the syntax tree directly might be easier.

    As an aside, the above way to parse and execute a query is a roundabout way of doing things. If you do not need to manipulate the parsed query before executing it, you can simply prepare and execute a query on a repository like so:

    String queryString = "SELECT ...";
    RepositoryConnection conn = repo.getConnection();
    try {
       TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString);
       TupleQueryResult result = tq.evaluate();
    }
    finally {
       conn.close();
    }
    

提交回复
热议问题