File: sparql_query_example.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 (36 lines) | stat: -rw-r--r-- 1,155 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
35
36
"""
SPARQL Query using [`Graph.query`][rdflib.graph.Graph.query]

The method returns a [`Result`][rdflib.query.Result], iterating over
this yields [`ResultRow`][rdflib.query.ResultRow] objects

The variable bindings can be accessed as attributes of the row objects
For variable names that are not valid python identifiers, dict access
(i.e. with `row[var] / __getitem__`) is also possible.

[`Result.vars`][rdflib.query.Result.vars] contains the variables
"""

import logging
import sys
from pathlib import Path

import rdflib

EXAMPLES_DIR = Path(__file__).parent

if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG, stream=sys.stderr)

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

    # The QueryProcessor knows the FOAF prefix from the graph
    # which in turn knows it from reading the N3 RDF file
    for row in g.query("SELECT ?s WHERE { [] foaf:knows ?s .}"):
        # For select queries, the Result object is an iterable of ResultRow
        # objects.
        assert isinstance(row, rdflib.query.ResultRow)
        print(row.s)
        # or row["s"]
        # or row[rdflib.Variable("s")]