Last active
January 2, 2022 16:40
-
-
Save dshorthouse/f85d068a96d8d6a6fde53436ff6f3a2a to your computer and use it in GitHub Desktop.
Query wikidata using ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Install via command-line as 'gem install sparql-client' | |
require 'sparql/client' | |
headers = { 'User-Agent' => 'Ruby-Sparql-Client/1.0' } | |
@sparql = SPARQL::Client.new("https://query.wikidata.org/sparql", headers: headers, read_timeout: 120) | |
# A SPARQL query to find an item and an optional Twitter handle | |
def wikidata_by_orcid_query(orcid) | |
%Q( | |
SELECT ?item ?itemLabel ?twitter | |
WHERE { | |
VALUES ?orcid {"#{orcid}"} { | |
?item wdt:P496 ?orcid . | |
} | |
OPTIONAL { | |
?item wdt:P2002 ?twitter . | |
} | |
SERVICE wikibase:label { | |
bd:serviceParam wikibase:language "en" . | |
} | |
} | |
) | |
end | |
def twitter_from_orcid(orcid) | |
@sparql.query(wikidata_by_orcid_query(orcid)).each_solution do |solution| | |
return "@#{solution.to_h[:twitter]}" if solution | |
end | |
nil | |
end | |
# Let's try Roderic Page, https://orcid.org/0000-0002-7101-9767 | |
puts twitter_from_orcid("0000-0002-7101-9767") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment