summaryrefslogtreecommitdiff
path: root/examples/prepared_query.py
blob: 828ed052a169a9c920a66f802437269ad18dd85c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
"""
SPARQL Queries be prepared (i.e parsed and translated to SPARQL algebra)
by the :meth:`rdflib.plugins.sparql.prepareQuery` method.

``initNs`` can be used instead of PREFIX values.

When executing, variables can be bound with the
``initBindings`` keyword parameter.
"""

import rdflib
from rdflib.plugins.sparql import prepareQuery
from rdflib.namespace import FOAF


if __name__ == "__main__":

    q = prepareQuery(
        "SELECT ?name WHERE { ?person foaf:knows/foaf:name ?name . }",
        initNs={"foaf": FOAF},
    )

    g = rdflib.Graph()
    g.parse("foaf.n3")

    tim = rdflib.URIRef("http://www.w3.org/People/Berners-Lee/card#i")

    for row in g.query(q, initBindings={"person": tim}):
        print(row.name)