Class: Marsdawn::Search::Rroonga

Inherits:
Object
  • Object
show all
Defined in:
lib/marsdawn/search/rroonga.rb

Instance Method Summary collapse

Constructor Details

#initialize(opts, storage) ⇒ Rroonga

Returns a new instance of Rroonga.



5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/marsdawn/search/rroonga.rb', line 5

def initialize opts, storage
  unless Module.const_defined?('Groonga')
    raise "Gem 'rroonga' should be installed." unless require 'groonga'
  end
  raise "The groonga database path should be specified" unless opts.key?(:path)
  @opts = {
    index_table: {}
  }.merge(opts)
  @storage = storage
  Groonga::Database.open(opts[:path])
  @table_prefix = "#{@storage.key}-#{@storage.lang}-#{@storage.version.tr('.','_')}"
end

Instance Method Details

#create_indexObject



40
41
42
43
44
45
46
47
48
49
# File 'lib/marsdawn/search/rroonga.rb', line 40

def create_index
  drop_tables
  create_tables
  docs = table('documents')
  index = @storage.get_document_info[:site_index]
  index.each do |uri, title|
    page = @storage.get(uri)
    docs.add(uri, :title => title, :content => Marsdawn::Util.strip_tags(page[:content]))
  end
end

#create_tablesObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/marsdawn/search/rroonga.rb', line 18

def create_tables
  index_table = {
    :type => :patricia_trie,
    :normalizer => :NormalizerAuto,
    :default_tokenizer => 'TokenBigram'
  }.merge(@opts[:index_table])
  Groonga::Schema.create_table(table_name('documents'), :type => :hash) do |tbl|
    tbl.text('title')
    tbl.text('content')
  end
  Groonga::Schema.create_table(table_name('terms'), index_table) do |tbl|
    tbl.index(col_name('documents', 'title'))
    tbl.index(col_name('documents', 'content'))
  end
end

#drop_tablesObject



34
35
36
37
38
# File 'lib/marsdawn/search/rroonga.rb', line 34

def drop_tables
  Groonga::Schema.remove_table(table_name('documents'))
  Groonga::Schema.remove_table(table_name('terms'))
rescue Groonga::Schema::TableNotExists
end

#search(keyword, opts = {}) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/marsdawn/search/rroonga.rb', line 51

def search keyword, opts={}
  snippet = Groonga::Snippet.new(html_escape: true, default_open_tag: '<strong>', default_close_tag: '</strong>', normalize: true)
  words = keyword.scan(/(?:\w|"[^"]*")+/).map{|w| w.delete('"')}
  words.each{|word| snippet.add_keyword(word, opts)}
  docs = table('documents')
  docs.select do |rec|
    expression = nil
    words.each do |word|
      sub_exp = (rec.content =~ word)
      if expression.nil?
        expression = sub_exp
      else
        expression &= sub_exp
      end
    end
    expression
  end.map{|rec| {uri: rec.key.key, title: rec.title, results: snippet.execute(rec.content)}}
end