class SBF::Client::SearchEndpoint

Public Instance Methods

find(model_type, search_text = nil, filters = [], geo_location = {}, options = {}) click to toggle source

Find entities in search matching the provided search term and/or filters.

@param [String|Array] model_type The type or types of entities to include in the results. @param [String] search_text A search term to filter the results. @param [Array] filters Filters to apply to the results. The array should contain hashes with the column, value and operator of the filter.

(i.e.) [{column: 'event_id', value: [11560, 11016,11378,11163], operator: 'in'}]

@param [Hash] geo_location The location details for performing a radius search. The hash should contain the lat, lon and distance.

(i.e.) {distance: 5, lat: 40.754567, lon: -96.695894}

@param [Hash] options An hash containing options for ordering, applying a limit and offset to the results. @option options [Hash] :order The ordering to apply to the results. The hash should contain the field_name to order on

as well as the direction. (i.e.) {field_name: 'foo', direction: 'asc'}

@option [Integer] :limit The maximum number of results to return. @option [Integer] :offset The query offset. @return [Client::Api::Response] The data attribute on a successful response will be

an array of search entities matching the model type(s) specified
# File lib/stbaldricks/endpoints/search.rb, line 21
def find(model_type, search_text = nil, filters = [], geo_location = {}, options = {})
  if [search_text, filters, geo_location].all?(&:empty?)
    raise SBF::Client::Error, 'Must provide either a search_text, filter or geo_location for the query'
  end

  model_type = Array(model_type).to_json unless model_type.empty?
  filters = filters.to_json unless filters.empty?
  geo_location = geo_location.to_json unless geo_location.empty?

  # Build the parameter list for search
  params = {}
  response_data = {}
  {model_type: model_type, search_text: search_text, filters: filters, geo_location: geo_location}.each do |k, v|
    params[k.to_sym] = v unless v.empty?
  end

  options.each do |k, v|
    params[k.to_sym] = v.is_a?(Hash) ? v.to_json : v unless v.empty?
  end

  response = SBF::Client::Api::Request.get_request("#{base_uri}/search", params)
  parsed_response_body = JSON.parse(response.body).symbolize!

  if ok?(response)
    response_data[:total_count] = parsed_response_body[:total]
    response_data[:results] = [].tap do |arr|
      parsed_response_body[:hits].each do |entity_data|
        arr << target_class.const_get(entity_data[:type].capitalize).new(entity_data[:source])
      end
    end

    data = response_data
  else
    data = nil
    error = SBF::Client::ErrorEntity.new(parsed_response_body)
  end

  SBF::Client::Api::Response.new(http_code: response.code, data: data, error: error)
end