SPARQL/UNION

From Wikibooks, open books for an open world
Jump to navigation Jump to search
FILTER SPARQL
UNION
SERVICE - Label

Suppose the set A: 28 capitals in European Union

SELECT ?city ?cityLabel
WHERE {
  wd:Q458 wdt:P150 ?country.   # European Union  contains administrative territorial entity
  ?country wdt:P36 ?city.      # capital
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
Try it!

Suppose the set B: 3 cities with millions of inhabitants in European Union.

SELECT ?city ?cityLabel
WHERE {
  wd:Q458 wdt:P150 ?country.   # European Union  contains administrative territorial entity
  ?city wdt:P17 ?country.      # city in a (European) country
  ?city wdt:P31 wd:Q1637706.   # city with millions of inhabitants
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
Try it!

The intersection of A and B, big capitals of the European Union, can simply be achieved by combining all the triples. This results in 1 citiy.

SELECT ?city ?cityLabel
WHERE {
  wd:Q458 wdt:P150 ?country.   # European Union  contains administrative territorial entity
  ?country wdt:P36 ?city.      # capital
  ?city wdt:P17 ?country.      # city in a (European) country
  ?city wdt:P31 wd:Q1637706.   # city with millions of inhabitants
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

Try it!

All capitals of the European union, excluding big cities can be achieved fy filtering using FILTER NOT EXISTS { }. This results in the other 27 capitals.

SELECT ?city ?cityLabel
WHERE {
  wd:Q458 wdt:P150 ?country.   # European Union  contains administrative territorial entity
  ?country wdt:P36 ?city.      # capital
  ?city wdt:P17 ?country.      # city in a (European) country
  FILTER NOT EXISTS{ ?city wdt:P31 wd:Q1637706. }  # NOT a city with millions of inhabitants
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

Try it!

Finally a UNION of capitals and big cities result in 30 cities. PS: without DISTINCT it would have the intersecting city doubled.

SELECT DISTINCT ?city ?cityLabel
WHERE {
  wd:Q458 wdt:P150 ?country.   # European Union  contains administrative territorial entity
  { ?country wdt:P36 ?city. }  # capital 
  UNION
  { ?city wdt:P17 ?country.    # city in a (European) country
    ?city wdt:P31 wd:Q1637706. # a city with millions of inhabitants
  }
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

Try it!

Mind that the 2 parts of the union should both be within brackets { ... } UNION { ... }.

Two simpler examples of UNION are

The last code can be simplified by using property path ?child wdt:P22|wdt:P25 ?parent.

An overview of all kind of joins:

Venn diagram Mathmatical SPARQL
Venn03.png And A.
B.
Venn05.png A.
FILTER NOT EXISTS{ B. }
Venn01MS.png A.
OPTIONAL{ B. }
Venn04.png Or { A. } UNION { B. }


FILTER SPARQL
UNION
SERVICE - Label