Module: Tripod::SparqlClient::Query

Defined in:
lib/tripod/sparql_client.rb

Class Method Summary collapse

Class Method Details

.query(sparql, accept_header, extra_params = {}) ⇒ RestClient::Response

Runs a sparql query against the endpoint. Returns a RestClient response object.

Examples:

Run a query

Tripod::SparqlClient::Query.query('SELECT * WHERE {?s ?p ?o}')

Parameters:

  • sparql (String)

    The sparql query.

  • accept_header (String)

    The accept header to send with the request

  • any (Hash)

    extra params to send with the request

Returns:

  • (RestClient::Response)


17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/tripod/sparql_client.rb', line 17

def self.query(sparql, accept_header, extra_params={})

  params = {:query => sparql}.merge(extra_params)
  request_url = Tripod.query_endpoint + '?' + params.to_query
  streaming_opts = {:accept => accept_header, :timeout_seconds => Tripod.timeout_seconds}
  streaming_opts.merge!(:response_limit_bytes => Tripod.response_limit_bytes) if Tripod.response_limit_bytes

  # Hash.to_query from active support core extensions
  stream_data = -> {
    Tripod.logger.debug "TRIPOD: About to run query: #{sparql}"
    Tripod.logger.debug "TRIPOD: Streaming fron url: #{request_url}"
    Tripod.logger.debug "TRIPOD: Streaming opts: #{streaming_opts.inspect}"

    Tripod::Streaming.get_data(request_url, streaming_opts)
  }

  if Tripod.cache_store # if a cache store is configured
    Tripod.logger.debug "TRIPOD: caching is on!"
    # SHA-2 the key to keep the it within the small limit for many cache stores (e.g. Memcached is 250bytes)
    # Note: SHA2's are pretty certain to be unique http://en.wikipedia.org/wiki/SHA-2.
    cache_key = 'SPARQL-QUERY-' + Digest::SHA2.hexdigest([extra_params, accept_header, sparql].join("-"))
    Tripod.cache_store.fetch(cache_key, &stream_data)
  else
    Tripod.logger.debug "TRIPOD caching is off!"
    stream_data.call()
  end

end

.select(query) ⇒ Hash, String

Runs a SELECT query against the endpoint. Returns a Hash of the results.

  Tripod::SparqlClient::Query.select(‘SELECT * WHERE ?p ?o’)

Examples:

Run a SELECT query

Parameters:

  • query (String)

    The query to run

Returns:

  • (Hash, String)


54
55
56
57
# File 'lib/tripod/sparql_client.rb', line 54

def self.select(query)
  query_response = self.query(query, "application/sparql-results+json")
  JSON.parse(query_response)["results"]["bindings"]
end