Class: Pho::Sparql::SparqlHelper

Inherits:
Object
  • Object
show all
Defined in:
lib/pho/sparql.rb

Overview

Simple helper class for manipulating and executing SPARQL queries and manipulating the results

Constant Summary collapse

VARIABLE_MATCHER =
/(\?|\$)([a-zA-Z]+)/

Class Method Summary collapse

Class Method Details

.apply_initial_bindings(query, bindings = {}) ⇒ Object

Apply some initial bindings to parameters in a query

The keys in the values hash are used to replace variables in a query The values are supplied as is, allowing them to be provided as URIs, or typed literals according to Turtle syntax.

Any keys in the hash that are not in the query are ignored. Any variables not found in the hash remain unbound.

query

the query whose initial bindings are to be set

values

hash of query name to value



257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/pho/sparql.rb', line 257

def SparqlHelper.apply_initial_bindings(query, bindings={})
    copy = query.clone()
    copy.gsub!(VARIABLE_MATCHER) do |pattern|
      key = $2
      if bindings.has_key?(key)
        bindings[key].to_s
      else
        pattern
      end              
    end            
    return copy  
end

.ask(query, sparql_client) ⇒ Object

Performs an ASK query on an endpoint, returing a boolean true/false response

Will request the results using the SPARQL JSON results format, parse the resulting JSON results, and extract the true/false response.

query

the SPARQL SELECT query

sparql_client

a configured SparqlClient object



340
341
342
343
# File 'lib/pho/sparql.rb', line 340

def SparqlHelper.ask(query, sparql_client)
  json = SparqlHelper.select(query, sparql_client)
  return json["boolean"] == "true"
end

.construct_to_resource_hash(query, sparql_client) ⇒ Object

Perform a SPARQL CONSTRUCT query against an endpoint, requesting the results in JSON

Will request the results as application/json (with the expectation that it returns RDF_JSON), and parses the resulting JSON document.

query

the SPARQL SELECT query

sparql_client

a configured SparqlClient object



400
401
402
403
404
405
406
407
# File 'lib/pho/sparql.rb', line 400

def SparqlHelper.construct_to_resource_hash(query, sparql_client)
  #TODO: test whether endpoint supports json, and if not, switch to parsing XML
  resp = sparql_client.construct(query, "application/json")
  if resp.status != 200
    raise "Error performing sparql query: #{resp.status} #{resp.reason}\n#{resp.content}"
  end
  return Pho::ResourceHash::Converter.parse_json( resp.content )          
end

.describe_to_resource_hash(query, sparql_client) ⇒ Object

Perform a SPARQL DESCRIBE query against an endpoint, requesting the results in JSON

Will request the results as application/json (with the expectation that it returns RDF_JSON), and parses the resulting JSON document.

query

the SPARQL SELECT query

sparql_client

a configured SparqlClient object



416
417
418
419
420
421
422
423
# File 'lib/pho/sparql.rb', line 416

def SparqlHelper.describe_to_resource_hash(query, sparql_client)
  #TODO: test whether endpoint supports json, and if not, switch to parsing XML
  resp = sparql_client.describe(query, "application/json")
  if resp.status != 200
    raise "Error performing sparql query: #{resp.status} #{resp.reason}\n#{resp.content}"
  end
  return Pho::ResourceHash::Converter.parse_json( resp.content )          
end

.describe_uri(uri, sparql_client, type = :cbd) ⇒ Object

Describe a single URI using one of several forms of Bounded Description See SparqlClient.describe_uri

uri

resource to describe

sparql_client

configured SPARQL client

type

form of bounded description to generate



444
445
446
447
448
449
450
451
# File 'lib/pho/sparql.rb', line 444

def SparqlHelper.describe_uri(uri, sparql_client, type=:cbd)
  #TODO: test whether endpoint supports json, and if not, switch to parsing XML
  resp = sparql_client.describe_uri(uri, "application/json", type)
  if resp.status != 200
    raise "Error performing sparql query: #{resp.status} #{resp.reason}\n#{resp.content}"
  end
  return Pho::ResourceHash::Converter.parse_json( resp.content )                              
end

.exists(uri, sparql_client) ⇒ Object

Performs an ASK query on the SPARQL endpoint to test whether there are any statements in the triple store about the specified uri.

uri

the uri to test for

sparql_client

a configured SparqlClient object



350
351
352
# File 'lib/pho/sparql.rb', line 350

def SparqlHelper.exists(uri, sparql_client)
   return SparqlHelper.ask("ASK { <#{uri}> ?p ?o }", sparql_client)  
end

.multi_describe(uris, sparql_client) ⇒ Object

DESCRIBE multiple resources in a single SPARQL request

uris

an array of URIs

sparql_client

a configured SparqlClient objec



429
430
431
432
433
434
435
436
# File 'lib/pho/sparql.rb', line 429

def SparqlHelper.multi_describe(uris, sparql_client)
  #TODO: test whether endpoint supports json, and if not, switch to parsing XML
  resp = sparql_client.multi_describe(uris, "application/json")
  if resp.status != 200
    raise "Error performing sparql query: #{resp.status} #{resp.reason}\n#{resp.content}"
  end
  return Pho::ResourceHash::Converter.parse_json( resp.content )                    
end

.result_to_query_binding(result) ⇒ Object

Convert a SPARQL query result binding into a hash suitable for passing to the apply_initial_bindings method.

The result param is assumed to be a Ruby hash that reflects the structure of a binding in a SELECT query result (i.e. the result of parsing the application/sparql-results+json format and extracting an specific result binding.

The method is intended to be used to support cases where an initial select query is performed to extract some variables that can later be plugged into a subsequent query

result

hash conforming to structure of a binding in the SPARQL JSON format



282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
# File 'lib/pho/sparql.rb', line 282

def SparqlHelper.result_to_query_binding(result)
  hash = {}
  result.each_pair do |key, value|
    if value["type"] == "uri"
      hash[key] = "<#{value["value"]}>"
    elsif (value["type"] == "literal" && !value.has_key?("datatype"))
      hash[key] = "\"#{value["value"]}\""
    elsif (value["type"] == "literal" && value.has_key?("datatype"))
      hash[key] = "\"#{value["value"]}\"^^#{value["datatype"]}"             
    else
      #do nothing for bnodes
    end
  end
  return hash
end

.results_to_query_bindings(results) ⇒ Object

Convert Ruby hash structured according to SPARQL JSON format into an array of hashes by calling result_to_query_binding on each binding into the results.

E.g: results = Pho::Sparql::SparqlHelper.select(query, sparql_client) bindings = Pho::Sparql::SparqlHelper.results_to_query_bindings(results)

results

hash conforming to SPARQL SELECT structure



307
308
309
310
311
312
313
314
# File 'lib/pho/sparql.rb', line 307

def SparqlHelper.results_to_query_bindings(results)
  bindings = []
  
  results["results"]["bindings"].each do |result|
    bindings << result_to_query_binding(result)
  end
  return bindings
end

.select(query, sparql_client) ⇒ Object

Perform a simple SELECT query on an endpoint. Will request the results using the SPARQL JSON results format, and parse the resulting JSON results. The result will therefore be a simple ruby hash of the results

An error will be raised if the response is HTTP OK.

query

the SPARQL SELECT query

sparql_client

a configured SparqlClient object



324
325
326
327
328
329
330
331
# File 'lib/pho/sparql.rb', line 324

def SparqlHelper.select(query, sparql_client)
  #TODO: test whether endpoint supports json, and if not, switch to parsing XML
  resp = sparql_client.select(query, Pho::Sparql::SPARQL_RESULTS_JSON)
  if resp.status != 200
    raise "Error performing sparql query: #{resp.status} #{resp.reason}\n#{resp.content}"
  end
  return JSON.parse( resp.content )
end

.select_single_value(query, sparql_client) ⇒ Object

Perform a simple SELECT query on an endpoint and return a single result

Will request the results using the SPARQL JSON results format, and parse the resulting JSON results. The assumption is that the SELECT query returns a single value (i.e single variable, with single binding)

Note this will lose any type information, only the value of the binding is returned

query

the SPARQL SELECT query

sparql_client

a configured SparqlClient object



387
388
389
390
391
# File 'lib/pho/sparql.rb', line 387

def SparqlHelper.select_single_value(query, sparql_client)
  results = SparqlHelper.select(query, sparql_client)
  v = results["head"]["vars"][0];
  return results["results"]["bindings"][0][v]["value"]           
end

.select_values(query, sparql_client) ⇒ Object

Perform a simple SELECT query on an endpoint and return a simple array of values

Will request the results using the SPARQL JSON results format, and parse the resulting JSON results. The assumption is that the SELECT query contains a single “column” of values, which will be returned as an array

Note this will lose any type information, only the value of the bindings are returned

Also note that if row has an empty binding for the selected variable, then this row will be dropped from the resulting array

query

the SPARQL SELECT query

sparql_client

a configured SparqlClient object



367
368
369
370
371
372
373
374
375
# File 'lib/pho/sparql.rb', line 367

def SparqlHelper.select_values(query, sparql_client)
   results = SparqlHelper.select(query, sparql_client)
   v = results["head"]["vars"][0];
   values = [];
   results["results"]["bindings"].each do |binding|
     values << binding[v]["value"] if binding[v]
   end
   return values           
end