File: prepared_query.py

package info (click to toggle)
rdflib 7.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 77,852 kB
  • sloc: python: 59,555; sh: 153; makefile: 83; ruby: 74; xml: 45
file content (34 lines) | stat: -rw-r--r-- 969 bytes parent folder | download
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
30
31
32
33
34
"""
SPARQL Queries be prepared (i.e parsed and translated to SPARQL algebra)
by the [`prepareQuery`][rdflib.plugins.sparql.prepareQuery] method.

`initNs` can be used instead of PREFIX values.

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

from pathlib import Path

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

EXAMPLES_DIR = Path(__file__).parent

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

    g = rdflib.Graph()
    g.parse(f"{EXAMPLES_DIR / 'foaf.n3'}")

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

    for row in g.query(q, initBindings={"person": tim}):
        # For select queries, the Result object is an iterable of ResultRow
        # objects.
        assert isinstance(row, rdflib.query.ResultRow)
        print(row.name)