Skip to content

Instantly share code, notes, and snippets.

@mcritchlow
Last active December 26, 2015 21:39
Show Gist options
  • Save mcritchlow/7217355 to your computer and use it in GitHub Desktop.
Save mcritchlow/7217355 to your computer and use it in GitHub Desktop.
This is a sample script for doing linked data lookup starting with string input. The code pings the Library Of Congress /authorities/suggest OpenSearch service. If it finds an exact match, it will query the RDF graph looking for particular Predicates/Values. Further reasoning would be possible here as well. If it doesn't find a match, it will re…
require 'net/http'
require 'json'
require 'linkeddata'
# API reference http://ruby-rdf.github.io/rdf/
#returned results from lookup
result = Hash.new
#define MADS vocabulary for RDF.ruby
MADS = RDF::Vocabulary.new("http://www.loc.gov/mads/rdf/v1#")
def get_loc_term(q)
http = Net::HTTP.new("id.loc.gov")
request = Net::HTTP::Get.new("/authorities/suggest/?q=#{q}")
response = http.request(request)
if response.code != "200"
puts "id.loc request error (status-code: #{response.code})\n#{response.body}"
else
data = JSON.parse(response.body)
if q.eql? data[1][0] #if the search term matches the first hit exactly
get_rdf(data[3][0]) #return the first result URI
else
data[1] #return search result set for user to choose
end
end
end
def get_rdf(uri)
d = Hash.new
d[:valueURI] = uri
RDF::Reader.open(uri) do |reader|
reader.each_statement do |statement|
d[:scheme] = statement.object if statement.predicate == MADS.isMemberOfMADSScheme && statement.subject == uri
d[:madsCollection] = statement.object if statement.predicate == MADS.isMemberOfMADSCollection && statement.subject == uri
d[:authoritativeLabel] = statement.object if statement.predicate == MADS.authoritativeLabel && statement.subject == uri
end
end
d
end
#sample
a = "Anti-fascist movements--Spain--Posters".split("--")
a.each { |term|
result[term] = get_loc_term(term)
}
#print results
puts result.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment