Class: Chef::Solr::Query

Inherits:
Chef::Solr show all
Defined in:
lib/chef/solr/query.rb

Instance Attribute Summary

Attributes inherited from Chef::Solr

#http, #solr_url

Instance Method Summary collapse

Methods inherited from Chef::Solr

#post_to_solr, #rebuild_index, #solr_add, #solr_commit, #solr_delete_by_id, #solr_delete_by_query, #solr_optimize, #solr_rollback, #solr_select

Constructor Details

#initialize(solr_url = Chef::Config[:solr_url], database = Chef::Config[:couchdb_database]) ⇒ Query

Create a new Query object - takes the solr_url and optional couchdb_database to inflate objects into.



34
35
36
37
38
# File 'lib/chef/solr/query.rb', line 34

def initialize(solr_url=Chef::Config[:solr_url], database=Chef::Config[:couchdb_database])
  super(solr_url)
  @database = database
  @couchdb = Chef::CouchDB.new(nil, database)
end

Instance Method Details

#raw(type, options = {}) ⇒ Object

A raw query against CouchDB - takes the type of object to find, and raw Solr options.

You’ll wind up having to page things yourself.



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/chef/solr/query.rb', line 44

def raw(type, options={})
  qtype = case type
          when "role",:role,"node",:node,"client",:client
            type
          else
            [ "data_bag_item", type ]
          end
  results = solr_select(@database, qtype, options)
  Chef::Log.debug("Searching #{@database} #{qtype.inspect} for #{options.inspect} with results:\n#{results.inspect}") 
  objects = if results["response"]["docs"].length > 0
              bulk_objects = @couchdb.bulk_get( results["response"]["docs"].collect { |d| d["X_CHEF_id_CHEF_X"] } )
              Chef::Log.debug("bulk get of objects: #{bulk_objects.inspect}")
              bulk_objects
            else
              []
            end
  [ objects, results["response"]["start"], results["response"]["numFound"], results["responseHeader"] ] 
end

#search(type, query = "*:*", sort = nil, start = 0, rows = 20, &block) ⇒ Object

Search Solr for objects of a given type, for a given query. If you give it a block, it will handle the paging for you dynamically.



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/chef/solr/query.rb', line 65

def search(type, query="*:*", sort=nil, start=0, rows=20, &block)
  options = {
    :q => query,
    :start => start,
    :rows => rows 
  }
  options[:sort] = sort if sort && ! sort.empty?
  objects, start, total, response_header = raw(type, options)
  if block
    objects.each { |o| block.call(o) }
    unless (start + objects.length) >= total
      nstart = start + rows
      search(type, query, sort, nstart, rows, &block)
    end
    true
  else
    [ objects, start, total ]
  end
end