Module: Tire::Model::Search::ClassMethods

Included in:
ClassMethodsProxy
Defined in:
lib/tire/model/search.rb

Instance Method Summary collapse

Instance Method Details

#indexObject

Returns a Tire::Index instance for this model.

Example usage: ‘Article.index.refresh`.



106
107
108
109
# File 'lib/tire/model/search.rb', line 106

def index
  name = index_name.respond_to?(:to_proc) ? klass.instance_eval(&index_name) : index_name
  @index = Index.new(name)
end

#search(*args, &block) ⇒ Object

Returns search results for a given query.

Query can be passed simply as a String:

Article.search 'love'

Any options, such as pagination or sorting, can be passed as a second argument:

Article.search 'love', :per_page => 25, :page => 2
Article.search 'love', :sort => 'title'

For more powerful query definition, use the query DSL passed as a block:

Article.search do
  query { terms :tags, ['ruby', 'python'] }
  facet 'tags' { terms :tags }
end

You can pass options as the first argument, in this case:

Article.search :per_page => 25, :page => 2 do
  query { string 'love' }
end

This methods returns a Tire::Results::Collection instance, containing instances of Tire::Results::Item, populated by the data available in _ElasticSearch, by default.

If you’d like to load the “real” models from the database, you may use the ‘:load` option:

Article.search 'love', :load => true

You can pass options as a Hash to the model’s ‘find` method:

Article.search :load => { :include => 'comments' } do ... end


65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/tire/model/search.rb', line 65

def search(*args, &block)
  default_options = {:type => document_type, :index => index.name}

  if block_given?
    options = args.shift || {}
  else
    query, options = args
    options ||= {}
  end

  sort      = Array( options[:order] || options[:sort] )
  options   = default_options.update(options)

  s = Tire::Search::Search.new(options.delete(:index), options)
  s.size( options[:per_page].to_i ) if options[:per_page]
  s.from( options[:page].to_i <= 1 ? 0 : (options[:per_page].to_i * (options[:page].to_i-1)) ) if options[:page] && options[:per_page]
  s.sort do
    sort.each do |t|
      field_name, direction = t.split(' ')
      by field_name, direction
    end
  end unless sort.empty?

  if version = options.delete(:version); s.version(version); end

  if block_given?
    block.arity < 1 ? s.instance_eval(&block) : block.call(s)
  else
    s.query { string query }
    # TODO: Actualy, allow passing all the valid options from
    # <http://www.elasticsearch.org/guide/reference/api/search/uri-request.html>
    s.fields Array(options[:fields]) if options[:fields]
  end

  s.results
end