29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
|
# File 'lib/mongoid-haystack/index.rb', line 29
def add(*args)
models_for(*args) do |model|
config = nil
if model.respond_to?(:to_haystack)
config = Map.for(model.to_haystack)
else
keywords = []
%w( keywords title ).each do |attr|
if model.respond_to?(attr)
keywords.push(*model.send(attr))
break
end
end
fulltext = []
%w( fulltext text content body description to_s ).each do |attr|
if model.respond_to?(attr)
fulltext.push(*model.send(attr))
break
end
end
config =
Map.for(
:keywords => keywords,
:fulltext => fulltext
)
end
unless %w( keywords fulltext facets score ).detect{|key| config.has_key?(key)}
raise ArgumentError, "you need to defined #{ model }#to_haystack"
end
keywords = Array(config[:keywords]).join(' ')
fulltext = Array(config[:fulltext]).join(' ')
facets = Map.for(config[:facets] || {})
score = config[:score]
index =
Haystack.find_or_create(
->{ where(:model => model).first },
->{ new(:model => model) },
)
if index.persisted?
Index.subtract(index)
end
keyword_scores = Hash.new{|h,k| h[k] = 0}
fulltext_scores = Hash.new{|h,k| h[k] = 0}
token_ids = []
values = Token.values_for(keywords)
tokens = Token.add(values)
token_index = tokens.inject({}){|hash, token| hash[token.value] = token; hash}
values.each do |value|
token = token_index.fetch(value)
id = token.id
token_ids.push(id)
keyword_scores[id] += 1
end
values = Token.values_for(fulltext)
tokens = Token.add(values)
token_index = tokens.inject({}){|hash, token| hash[token.value] = token; hash}
values.each do |value|
token = token_index.fetch(value)
id = token.id
token_ids.push(id)
fulltext_scores[id] += 1
end
index.keyword_scores = keyword_scores
index.fulltext_scores = fulltext_scores
index.score = score if score
index.facets = facets if facets
index.token_ids = token_ids
index.save!
end
end
|