RDF and SPARQL: match patterns, preserve bindings
RDF 与 SPARQL
Evaluate a small basic graph pattern and distinguish graph sets from duplicate query answers.
rdf-sparqlFive facts can produce two identical answers
Two people called Lin work at the same laboratory. The laboratory is in Harbor. Store each person’s name and employer, plus the laboratory’s city: five distinct triples. Ask for the name and city of everyone working there. The answer can contain “Lin, Harbor” twice. The graph has no duplicate facts; the query has two different people as witnesses.
RDF defines a data model. SPARQL defines a query language over that model. Keeping these roles separate makes the duplicate answer unsurprising. This article implements a small basic graph pattern evaluator with exact terms, shared-variable joins and projection. It does not implement a complete SPARQL parser or endpoint. RDF §3.1 SPARQL §2
A term is more precise than a displayed string
Let I, B and L be disjoint sets of IRIs, blank nodes and literals. The positions of an RDF triple obey:
The predicate is an IRI; the subject cannot be a literal. An IRI is a globally scoped identifier, not a command to fetch a web page. A blank node represents an unnamed resource; a serialization label such as b0 has local scope. Two input documents both using b0 must not accidentally identify their blank nodes. Our code includes an explicit document scope in its internal blank-node key. §3.1 and §3.4
A literal records a lexical form and datatype, with a language tag for a language-tagged string. Equal values need not be equal terms. Let l₁ and l₂ be integer literals with lexical forms “1” and “01”:
Both forms can denote the same integer while remaining distinct RDF terms. Our matching core tests term equality, not numerical conversion. The demonstration calls Python’s int separately to illustrate the value comparison; it is not a SPARQL FILTER implementation. Language tags also matter: “Lin”@en and “Lin”@zh are different terms. §3.3
A triple pattern may replace any position with a variable. A binding μ maps variables to terms. For a basic pattern P without query blank nodes, a solution replaces all its variables consistently so that every instantiated triple exists:
The same variable must receive the same term wherever it occurs. The pattern (?x, knows, ?x) therefore requires a self-loop; an arbitrary knows edge does not match it. When combining partial solutions, retain pairs that agree on their shared variables:
Our nested-loop evaluator starts with one empty binding and extends compatible rows one pattern at a time. An empty pattern has one empty solution even on an empty graph, rather than zero solutions. §5.2.1
Finally SELECT projects the bindings to chosen variables. Different full bindings may become identical after removing a person ID. With bag multiplicity, the projected row’s count is the sum of the counts of its full witnesses:
DISTINCT keeps one copy of each projected binding. RDF’s set of triples and SPARQL’s duplicate-preserving solution sequence are compatible rules at different stages. Do not silently deduplicate before the reader has chosen DISTINCT. §15.3
Evaluate the join, without hiding it behind a parser
This complete Python 3.12 program uses only the standard library. Constructed terms are tuples with a kind and payload. Patterns are Python triples with variable strings; the input is not SPARQL source text. The IRI and language-tag constructors apply only their documented lightweight checks, not full Unicode/IRI/BCP47 validation. Use a standards-compliant library for production parsing.
"""Original RDF-term/BGP core. No Turtle/SPARQL parser or entailment engine.
Named nodes, scoped blank nodes, exact literal terms, joins and projection only.
"""
import json
def iri(value):
if not isinstance(value, str) or ":" not in value or any(c.isspace() for c in value):
raise ValueError("Example requires an absolute, whitespace-free identifier")
return ("iri", value, "")
def literal(value, datatype="http://www.w3.org/2001/XMLSchema#string", lang=None):
if not isinstance(value, str):
raise ValueError("Lexical form must be text")
if lang is not None:
if not isinstance(lang, str) or not lang:
raise ValueError("Nonempty language tag required")
# The example stores normalized tags, not a complete BCP47 validator.
return ("lang", value, lang.lower())
return ("literal", value, iri(datatype)[1])
def blank(scope, label):
if not scope or not label:
raise ValueError("Explicit nonempty blank-node scope and label required")
return ("blank", scope, label)
def term(x):
return isinstance(x, tuple) and len(x) == 3 and x[0] in {"iri", "literal", "lang", "blank"}
def variable(x):
return isinstance(x, str) and x.startswith("?") and len(x) > 1
def graph(triples):
result = set()
for t in triples:
if len(t) != 3 or not all(term(x) for x in t):
raise ValueError("Expected three constructed RDF terms")
s, p, _ = t
if s[0] not in {"iri", "blank"} or p[0] != "iri":
raise ValueError("Invalid subject/predicate term kind")
result.add(tuple(t))
return result
def match(g, patterns):
"""Nested-loop basic graph pattern evaluation, with bag results."""
g = graph(g)
rows = [{}]
for pattern in patterns:
if len(pattern) != 3 or not all(variable(x) or term(x) for x in pattern):
raise ValueError("Expected three variables or constructed terms")
out = []
for row in rows:
for triple in sorted(g):
candidate = dict(row)
for pattern_term, value in zip(pattern, triple):
if variable(pattern_term):
if pattern_term in candidate and candidate[pattern_term] != value:
break
candidate[pattern_term] = value
elif pattern_term != value:
break
else:
out.append(candidate)
rows = out
return rows
def project(rows, names, distinct=False):
if len(set(names)) != len(names) or not all(variable(x) for x in names):
raise ValueError("Projection requires unique variables")
values = [tuple(row.get(name) for name in names) for row in rows]
return list(dict.fromkeys(values)) if distinct else values
def demo():
a, b, lab = map(iri, ["urn:person:a", "urn:person:b", "urn:lab:x"])
name, works, city = map(iri, ["urn:name", "urn:worksAt", "urn:city"])
g = graph([(a, name, literal("Lin")), (b, name, literal("Lin")),
(a, works, lab), (b, works, lab), (lab, city, literal("Harbor")),
(a, name, literal("Lin"))])
rows = match(g, [("?p", name, "?name"), ("?p", works, "?lab"), ("?lab", city, "?city")])
integer = "http://www.w3.org/2001/XMLSchema#integer"
return dict(graph_size=len(g), joined_rows=len(rows),
projected_rows=len(project(rows, ["?name", "?city"])),
distinct_rows=len(project(rows, ["?name", "?city"], True)),
same_integer_term=literal("1", integer) == literal("01", integer),
same_integer_value=int("1") == int("01"),
blank_scope_equal=blank("file1", "b0") == blank("file2", "b0"),
empty_pattern_rows=len(match(set(), [])))
if __name__ == "__main__":
print(json.dumps(demo(), indent=2))
The program reports five graph triples, two joined solutions, two projected rows and one DISTINCT row. The integer literals have different terms but equal separately converted values. The two b0 labels in different scopes remain different. The empty pattern returns one empty binding.
For k patterns, m graph triples and at most B intermediate rows, the straightforward join work is O(kBm), excluding sorting and key-width costs. The current implementation sorts m triples for each input row, so a conservative bound is O(kBm log(m+1)); it prioritizes deterministic inspection over speed. Peak intermediate storage can grow with the join output. Predicate indexes and join-order planning can reduce actual work, but a large answer still costs space to emit.
The tests compare a two-edge join against an independent Cartesian-product reference, check repeated variables, and distinguish duplicate graph input from duplicate projection output. None of these tests establishes complete SPARQL conformance.
Matching a graph is not deriving every consequence
This evaluator returns matches in the supplied graph. It does not apply RDFS subclass rules or infer missing triples. RDF entailment requires a declared regime, while query matching needs a precise dataset and active graph. RDF §1.7 A production system must also specify default versus named graphs and its inference settings.
The subset excludes query blank nodes, OPTIONAL, FILTER, UNION, property paths, aggregates, update, remote access and explicit ordering. Unbound projected variables are represented by None. The returned deterministic order is an implementation choice, not a guarantee of SPARQL order without ORDER BY. Numerical comparisons, malformed literals and datatype errors require more than the term matching shown here.
Follow the bindings
- Can a string literal be an RDF predicate? Answer: No. A predicate must be an IRI. A literal is allowed in the object position, not as a subject or predicate.
- Why do two people with the same name produce two identical name-only rows? Answer: Their person bindings differ before projection. Projection preserves both solution occurrences; DISTINCT explicitly removes duplicate projected rows.
- Does (?x, knows, ?x) match an edge from a to b when a and b are distinct terms? Answer: No. The second occurrence must reuse the first binding, so a self-loop is required.
- Importing two files each containing _:b0 produced an unintended join. What should change? Answer: Scope or rename their blank-node identifiers during ingestion. Reusing a serialization label across unrelated files is not identity evidence.
Use the standard to define the boundaries
RDF Concepts defines the terms and triple positions; SPARQL’s simple-query, empty-pattern and duplicate-solution sections define the behavior inspected here. The original evaluator demonstrates those bounded operations with authored data. It is useful to compare it with a full implementation such as RDFLib, while testing exact query behavior rather than assuming that any triple store has the same inference settings. Knowledge graphs explains the larger identity and evidence problem; graph completion studies predictions beyond stored edges.
Make a prediction, then check
Two different people share a name. SELECT returns only that name, without DISTINCT. How many rows remain?
Learning objectives
- Explain typed terms, scoped blank nodes, repeated variables, joins and DISTINCT with exact examples.
- Predict empty-pattern and projection cardinalities, then account for intermediate rows and sorting in query cost.
Prerequisites & connections
Explore related knowledge →References
- RDF 1.1 Concepts and Abstract Syntax — 25 February 2014
W3C RDF Working Group · 2014 - SPARQL 1.1 Query Language — 21 March 2013
W3C SPARQL Working Group · 2013
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-23 · Single AI author. Scoped reading: Read extracted §1.7 entailment/equivalence/inconsistency, §3/3.1 terms and triples, §3.3 literal equality and §3.4 blank-node scope. Initial web opening also showed §1.1–1.5. Teaching core is not a complete parser, datatype validator or entailment implementation. Read §2 opening/2.1–2.2, §5.2 opening/5.2.1–5.2.2 and §15.3 duplicate solution semantics; adjacent OFFSET text also read. Implements structured BGP joins and projection only, without query parsing, FILTER, OPTIONAL, ordering or entailment. 6 paired equations and four explained exercises. Checked BGP joins against an independent Cartesian reference, repeated variables, bag projection, DISTINCT, empty-pattern identity, literal-term equality and blank-node scope. No SPARQL parser or complete conformance claim.
- Checked BGP joins against an independent Cartesian reference, repeated variables, bag projection, DISTINCT, empty-pattern identity, literal-term equality and blank-node scope. No SPARQL parser or complete conformance claim.
- Four computed SVG variants per topic;14 numeric/geometry tests and36 responsive cases passed. Twelve selected current captures visually checked: seven identical to previously viewed images and five re-viewed final captures; TransE arrow revision retained. Full article acceptance recorded separately.
Source locations checked:
- RDF 1.1 Concepts and Abstract Syntax — 25 February 2014 · Read extracted §1.7 entailment/equivalence/inconsistency, §3/3.1 terms and triples, §3.3 literal equality and §3.4 blank-node scope. Initial web opening also showed §1.1–1.5. Teaching core is not a complete parser, datatype validator or entailment implementation.
- SPARQL 1.1 Query Language — 21 March 2013 · Read §2 opening/2.1–2.2, §5.2 opening/5.2.1–5.2.2 and §15.3 duplicate solution semantics; adjacent OFFSET text also read. Implements structured BGP joins and projection only, without query parsing, FILTER, OPTIONAL, ordering or entailment.
Related topics