Useful Snippets for Writing SPARQL Queries

Stuff, I googled at least twice.

multiple properties

SELECT ?item ?itemLabel ?value ?valueLabel WHERE {
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
  ?item (wdt:P268|wdt:P338) ?value                             
}

create a list of values in order to refer to them later

SELECT DISTINCT ?item ?itemLabel ?value ?valueLabel WHERE {
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
  # some properties of interest that can be fetched with ?relations
  VALUES ?relations {
    wdt:P419
    wdt:P66
  }
  ?item ?relations ?values.
}

get all properties and values of an item

SELECT ?p ?o WHERE {
  wd:Q406029 ?p ?o
 }

exclude values from result

MINUS { ?item wdt:P2 wd:Q7. }

filter labels for certain strings

# Uses FILTER and CONTAINS https://www.wikidata.org/wiki/Wikidata:SPARQL_tutorial#FILTER  
 SELECT DISTINCT ?item ?label  WHERE {
   ?item wdt:P131 wd:Q400012;
     rdfs:label ?label.
 FILTER((LANG(?label)) = "[AUTO_LANGUAGE]") # auto language, specify with "en", "de", etc.
 FILTER(CONTAINS(?label, "CSD")) # search string, can be extended to a regex see: https://www.wikidata.org/wiki/Wikidata:SPARQL_tutorial#FILTER
 }

get property label

Property labels need to be fetched with `wikibase:directClaim`, see:

#defaultView:Table
SELECT DISTINCT ?item ?itemLabel ?value ?valueLabel ?property ?propertyLabel WHERE {
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
  VALUES ?relations {
    wdt:P419
  }
  ?item ?relations ?values.
  ?property wikibase:directClaim ?relations.
}
LIMIT 10

get wikidata QID of an item (in Factgrid)

PREFIX fg: <https://database.factgrid.de/entity/>

SELECT ?item ?itemLabel ?link ?wd_item WHERE {
  SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
# bind variable, makes rest easier
  BIND(fg:Q225307 as ?item)
  ?link schema:about ?item .
  ?link schema:isPartOf <https://www.wikidata.org/> . 
  ?link schema:name ?qid.
  BIND(IRI(CONCAT(STR(wd:), ?qid)) AS ?wd_item)
}

Schreibe einen Kommentar