Transforming SPARQL algebra

20 views
Skip to first unread message

Dan Davis

unread,
Apr 3, 2019, 10:32:06 AM4/3/19
to rdflib-dev
Does rdflib.plugins.sparql have any facilities for doing transforms?   I've tried to figure this out, but I cannot quite see the right way to do it.
It looks like it ought to be possible, but the documentation doesn't quite get me there.

I can prepare a query and print the query algebra:

     query = prepareQuery(querytext)
     query.algebra

I also see that there is a function rdflib.plugins.sparql.algebra.traverse, but I'm not quite sure how to transform a query with that.

A simple example would be great.

Also, if there's anyway to do a transformation on the SPARQL syntax tree separate from the algebra, that would be great too.

Thanks,

-Dan


Dan Davis

unread,
Apr 4, 2019, 2:31:32 PM4/4/19
to rdflib-dev
I will answer my own question, then.   In rdflib/plugins/sparql/algebra.py, the function translateQuery uses the traverse function to translate the second part of the query (after the prologue), and then further translates to create the query algebra.   The answer to my question then would be:

   * The traverse function acts on the Query syntax producing by parsing the query.   There is no real included capability to do a transform on the algebra.
   * To use traverse yourself, first use rdflib.plugins.sparql.parser.parseQuery to parse the query, and then use traverse to modify that query.
   * To translate it into algebra, pass it to rdflib.plugins.sparql.algebra.translateQuery directly.

However, there is no good way to unparse the query that I see.

Dan Davis

unread,
Apr 4, 2019, 2:48:01 PM4/4/19
to rdflib-dev
So, still cannot see how to unparse, but if I already know the structure of the query a bit, I can manipulate as follows

    import rdflib
    from rdflib.plugins.sparql.parser import parseQuery

    q = parseQuery(something)
    if q[1].where.part[2].triples[0][2] == rdflib.Variable('parent'):
        q[1].where.part[2].triples[0][2] = rdflib.URIRef('http://example.org/fubar#4')

This doesn't quite help with the SPARQLWrapper, because there is no great way to "unparse" the query, but it almost does.
Reply all
Reply to author
Forward
0 new messages