So far, we've written SPARQL queries that retrieve data matching a single graph pattern. For example, we might retrieve all superheroes, all villains, or all actors from a dataset.
But what happens when we want to combine results from different types of entities into a single result set?
Suppose we want to generate a unified list containing:
· Names of all superheroes
· Names of all people
Even though superheroes and people are represented by different RDF graph patterns, we want the results returned as one combined list.
This is where the UNION keyword becomes useful. UNION allows us to perform a logical OR operation between graph patterns. A solution is returned if it matches either the first pattern, the second pattern, or both.
This is particularly useful when:
· Building combined search results
· Creating stacked lists of related entities
· Merging information from multiple classes
· Querying alternative graph structures
Syntax
SELECT ?variable
WHERE {
{
graph pattern 1
}
UNION
{
graph pattern 2
}
}
Let's see how this works using our Marvel dataset.
1. The Problem
We want to create a single list containing:
All superhero names
All person names
All real names (Who Portrayed the character)
Expected examples include:
· Black Widow
· Captain America
· Hulk
· Iron Man
· Star-Lord
· Thor
· Bruce Banner
· Natasha Romanoff
· Peter Quill
· Steve Rogers
· Tony Stark
· Chris Evans
· Chris Pratt
· Mark Ruffalo
· Robert Downey Jr.
· Scarlett Johansson
Rather than running three separate queries, we can combine them using UNION.
PREFIX : <http://example.org/marvel/> SELECT ?name WHERE { { ?hero a :Superhero ; :name ?name . } UNION { ?person a :Person ; :name ?name . } UNION { ?person a :Person ; :portrayedBy ?portrayed . ?portrayed :name ?name } }
Ordering the Results
To make the output easier to read, we can sort the results alphabetically.
PREFIX : <http://example.org/marvel/> SELECT ?name WHERE { { ?hero a :Superhero ; :name ?name . } UNION { ?person a :Person ; :name ?name . } UNION { ?person a :Person ; :portrayedBy ?portrayed . ?portrayed :name ?name } } ORDER BY ?name
In summary,
· UNION combines the results of multiple graph patterns.
· It behaves like a logical OR operation.
· Each graph pattern must be enclosed in its own set of curly braces.
· Variables with the same name across union branches are merged into the same result columns.
· ORDER BY can be used after the union to sort the combined results.
· UNION is useful when creating consolidated lists from different RDF classes or relationship structures.
Previous Next Home
No comments:
Post a Comment