Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With SPARQL, how to SELECT for node by identifer, specifically in wikidata?

Using the Wikidata SPARQL service, I would like to get the list of the 50 states and include the District of Columbia from Wikidata. I have come up with a kludgy query to do so:

#-- wdt:P31 = instance of;  wd:Q35657 = list of states

SELECT ?state ?stateLabel
   WHERE {
     {?state wdt:P31 wd:Q35657} UNION 
     {?state wdt:P3403 wd:Q3551781} . #-- coextensive with District of Columbia
   SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
}

My query works but the way I extract DC into the results is ugly. (It's possible that future changes to data in Wikidata will break this query.) What I'd like to be able to say is something like

UNION {?state == wd:Q61}

to directly include Washington, D.C. (Q61). However, as a SPARQL newbie, I can't figure out the SPARQL syntax for doing so. I'd be grateful for any help to rewrite this query to directly pull in wd:Q61.

like image 234
Raymond Yee Avatar asked Dec 14 '22 01:12

Raymond Yee


2 Answers

You can use SPARQL 1.1 BIND to add fixed resources to the resultset, i.e.

SELECT ?state ?stateLabel WHERE {
     {?state wdt:P31 wd:Q35657} 
       UNION 
     {BIND(wd:Q61 as ?state)}
     SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
}
like image 96
UninformedUser Avatar answered Feb 01 '23 23:02

UninformedUser


You could use an external identifier to uniquely identify Washington, D.C., if you're worried about the property that you're currently using being unstable.

For example, to use the Geonames ID for Washington, D.C. in your UNION statement, you could use the following:

# wdt:P31 = instance of;  wd:Q35657 = list of states; wdt:P1566 = Geonames ID

SELECT ?state ?stateLabel
   WHERE {
     {?state wdt:P31 wd:Q35657} UNION 
     {?state wdt:P1566 "4138106"} . # we want wd:Q61
   SERVICE wikibase:label { bd:serviceParam wikibase:language "en" }
}
like image 40
Dan Scott Avatar answered Feb 02 '23 01:02

Dan Scott