Class: PrettySearch::IndexedCollection

Inherits:
Collection
  • Object
show all
Defined in:
lib/pretty_search/collection/indexed_collection.rb

Overview

Example extension

PrettySearch::IndexedCollection is like MemoryCollection, but builds an index on a given field for faster searching. Ideal for multiple searches when memory size is not an issue

Instance Method Summary collapse

Methods inherited from Collection

load

Constructor Details

#initialize(data_file, index_field: nil, first: false) ⇒ IndexedCollection

Returns a new instance of IndexedCollection.



9
10
11
12
13
14
15
16
# File 'lib/pretty_search/collection/indexed_collection.rb', line 9

def initialize(data_file, index_field: nil, first: false)
  if index_field.nil?
    raise MissingParameter, 'Field name to be indexed required'
  end
  data = Yajl::Parser.parse(File.new(data_file))
  @index_field = index_field
  @index = build_index(data, index_field)
end

Instance Method Details

#search(query) ⇒ Object



18
19
20
21
22
23
24
# File 'lib/pretty_search/collection/indexed_collection.rb', line 18

def search(query)
  if query[@index_field].nil?
    raise "indexed field: \"#{@index_field}\" not used in query"
  end
  scoped = @index[query[@index_field]]
  scoped.select { |doc| query.match(doc) }
end