Class: Polecat::IndexSearcher

Inherits:
Object
  • Object
show all
Defined in:
lib/polecat/index_searcher.rb

Overview

interface for searching an index

Build on top of an Polecat::IndexReader, this class let’s you search through all documents stored in an index.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ IndexSearcher

creates a new Polecat::IndexSearcher

Create a new Polecat::IndexSearcher to search documents. Either a path to a directory or a Polecat::IndexReader has to be given, to make this searcher work.

Examples:

# the following has the same meaning
IndexSearcher.new 'index_dir'
IndexSearcher.new(IndexReader.new 'index_dir')


19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/polecat/index_searcher.rb', line 19

def initialize options
  if options.has_key? :path
    @reader = Polecat::IndexReader.new(options[:path])
  elsif options.has_key? :reader 
    @reader = options[:reader]
    raise ArgumentError, 'no reader' unless @reader.kind_of?(Polecat::IndexReader)
  end

  if options.has_key? :default_field
    @default_field = options[:default_field]
  end
end

Instance Attribute Details

#default_fieldObject (readonly)

Returns the value of attribute default_field.



8
9
10
# File 'lib/polecat/index_searcher.rb', line 8

def default_field
  @default_field
end

#readerObject (readonly)

Returns the value of attribute reader.



7
8
9
# File 'lib/polecat/index_searcher.rb', line 7

def reader
  @reader
end

Instance Method Details

#pathString

returns the path of the index directory

Returns:

  • (String)

    path of the index directory



34
35
36
# File 'lib/polecat/index_searcher.rb', line 34

def path
  @reader.path
end

#search(query) ⇒ Array

searches through all documents

Run the query against the @default_field@ of every stored document to get a list of all matching documents.

Parameters:

  • query (String)

    a String which get’s matched against the documents

Returns:

  • (Array)

    a list of all matching documents



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

def search query
  @reader.read.select do |doc|
    #doc.attributes.fetch(@default_field).fetch(:value) == query
    rs = []
    query.terms.each do |term|
      val = doc.send(term.field.to_sym)
      if compare val, term.operator, term.value
        rs << true
      end
    end
    if query.relation == :and
      rs.count == query.terms.count
    else
      !rs.empty?
    end
  end
end