Class: FuzzyMatch

Inherits:
Object
  • Object
show all
Defined in:
lib/fuzzy_match.rb,
lib/fuzzy_match/rule.rb,
lib/fuzzy_match/score.rb,
lib/fuzzy_match/record.rb,
lib/fuzzy_match/result.rb,
lib/fuzzy_match/version.rb,
lib/fuzzy_match/similarity.rb,
lib/fuzzy_match/score/amatch.rb,
lib/fuzzy_match/cached_result.rb,
lib/fuzzy_match/rule/grouping.rb,
lib/fuzzy_match/rule/identity.rb,
lib/fuzzy_match/score/pure_ruby.rb

Overview

require ‘pry’

Defined Under Namespace

Classes: CachedResult, Record, Result, Rule, Score, Similarity

Constant Summary collapse

DEFAULT_ENGINE =
:pure_ruby
DEFAULT_OPTIONS =

TODO refactor at least all the :find_X things

{
  :must_match_grouping => false,
  :must_match_at_least_one_word => false,
  :gather_last_result => false,
  :find_all => false,
  :find_all_with_score => false,
  :threshold => nil,
  :find_best => false,
  :find_with_score => false,
}
VERSION =
'2.1.0'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(haystack, options_and_rules = {}) ⇒ FuzzyMatch

haystack - a bunch of records that will compete to see who best matches the needle

Rules (can only be specified at initialization or by using a setter)

  • :identities - regexps

  • :groupings - regexps

  • :stop_words - regexps

  • :read - how to interpret each record in the ‘haystack’, either a Proc or a symbol

Options (can be specified at initialization or when calling #find)

  • :must_match_grouping - don’t return a match unless the needle fits into one of the groupings you specified

  • :must_match_at_least_one_word - don’t return a match unless the needle shares at least one word with the match

  • :gather_last_result - enable last_result

  • :threshold - set a score threshold below which not to return results (not generally recommended - please test the results of setting a threshold thoroughly - one set of results and their scores probably won’t be enough to determine the appropriate number). Only checked against the Pair Distance score and ignored when one string or the other is of length 1.



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/fuzzy_match.rb', line 68

def initialize(haystack, options_and_rules = {})
  o = options_and_rules.dup

  # rules
  @read = o.delete(:read) || o.delete(:haystack_reader)
  @groupings = (o.delete(:groupings) || o.delete(:blockings) || []).map { |regexp| Rule::Grouping.make(regexp) }.flatten
  @identities = (o.delete(:identities) || []).map { |regexp| Rule::Identity.new(regexp) }
  @stop_words = o.delete(:stop_words) || []
  
  # options
  if deprecated = o.delete(:must_match_blocking)
    o[:must_match_grouping] = deprecated
  end
  @default_options = DEFAULT_OPTIONS.merge(o).freeze

  @haystack = haystack.map { |original| Record.new original, :stop_words => @stop_words, :read => @read }
end

Instance Attribute Details

#default_optionsObject (readonly)

Returns the value of attribute default_options.



53
54
55
# File 'lib/fuzzy_match.rb', line 53

def default_options
  @default_options
end

#groupingsObject (readonly)

Returns the value of attribute groupings.



49
50
51
# File 'lib/fuzzy_match.rb', line 49

def groupings
  @groupings
end

#haystackObject (readonly)

Returns the value of attribute haystack.



48
49
50
# File 'lib/fuzzy_match.rb', line 48

def haystack
  @haystack
end

#identitiesObject (readonly)

Returns the value of attribute identities.



50
51
52
# File 'lib/fuzzy_match.rb', line 50

def identities
  @identities
end

#readObject

Returns the value of attribute read.



52
53
54
# File 'lib/fuzzy_match.rb', line 52

def read
  @read
end

#stop_wordsObject (readonly)

Returns the value of attribute stop_words.



51
52
53
# File 'lib/fuzzy_match.rb', line 51

def stop_words
  @stop_words
end

Class Method Details

.engineObject



12
13
14
# File 'lib/fuzzy_match.rb', line 12

def engine
  @engine
end

.engine=(alt_engine) ⇒ Object



16
17
18
# File 'lib/fuzzy_match.rb', line 16

def engine=(alt_engine)
  @engine = alt_engine
end

.score_classObject



20
21
22
23
24
25
26
27
28
29
# File 'lib/fuzzy_match.rb', line 20

def score_class
  case engine
  when :pure_ruby
    Score::PureRuby
  when :amatch
    Score::Amatch
  else
    raise ::ArgumentError, "[fuzzy_match] #{engine.inspect} is not a recognized engine."
  end
end

Instance Method Details

#explain(needle, options = {}) ⇒ Object

Explain is like mysql’s EXPLAIN command. You give it a needle and it tells you about how it was located (successfully or not) in the haystack.

d = FuzzyMatch.new ['737', '747', '757' ]
d.explain 'boeing 737-100'


331
332
333
334
# File 'lib/fuzzy_match.rb', line 331

def explain(needle, options = {})
  find needle, options.merge(:gather_last_result => true)
  last_result.explain
end

#find(needle, options = {}) ⇒ Object



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# File 'lib/fuzzy_match.rb', line 114

def find(needle, options = {})
  options = default_options.merge options
  
  threshold = options[:threshold]
  gather_last_result = options[:gather_last_result]
  is_find_all_with_score = options[:find_all_with_score]
  is_find_with_score = options[:find_with_score]
  is_find_best = options[:find_best]
  is_find_all = options[:find_all] || is_find_all_with_score || is_find_best
  must_match_grouping = options[:must_match_grouping]
  must_match_at_least_one_word = options[:must_match_at_least_one_word]
  
  if gather_last_result
    @last_result = Result.new
    last_result.read = read
    last_result.haystack = haystack
    last_result.options = options
  end
  
  if gather_last_result
    last_result.identities = identities
    last_result.groupings = groupings
    last_result.stop_words = stop_words
  end
  
  needle = case needle
  when String
    Record.new needle
  else
    Record.new needle, :read => read
  end
  
  if gather_last_result
    last_result.needle = needle
  end

  if groupings.any?
    first_grouping = groupings.detect { |grouping| grouping.xmatch? needle }
    if gather_last_result
      if first_grouping
        last_result.timeline << "Grouping: #{first_grouping.inspect}"
      else
        last_result.timeline << "No grouping."
      end
    end
  end

  if must_match_grouping and not first_grouping
    if gather_last_result
      last_result.timeline << <<-EOS
The needle didn't match any of the #{groupings.length} groupings, which was a requirement.
\t#{groupings.map(&:inspect).join("\n\t")}
EOS
    end
    if is_find_all
      return []
    else
      return nil
    end
  end

  if groupings.any? and not first_grouping
    passed_grouping_requirement = haystack.reject do |straw|
      groupings.any? { |grouping| grouping.xmatch? straw }
    end
  else
    passed_grouping_requirement = haystack
  end

  if must_match_at_least_one_word
    passed_word_requirement = passed_grouping_requirement.select do |straw|
      (needle.words & straw.words).any?
    end
    if gather_last_result
      last_result.timeline << <<-EOS
Since :must_match_at_least_one_word => true, the competition was reduced to records sharing at least one word with the needle.
\tNeedle words: #{needle.words.map(&:inspect).join(', ')}
\tPassed (first 3): #{passed_word_requirement[0,3].map(&:inspect).join(', ')}
\tFailed (first 3): #{(passed_grouping_requirement-passed_word_requirement)[0,3].map(&:inspect).join(', ')}
EOS
    end
  else
    passed_word_requirement = passed_grouping_requirement
  end
      
  if first_grouping
    joint = passed_word_requirement.select do |straw|
      first_grouping.xjoin? needle, straw
    end
    # binding.pry      
    if gather_last_result
      last_result.timeline << <<-EOS
Since there were groupings, the competition was reduced to #{joint.length} records in the same group as the needle.
\t#{joint.map(&:inspect).join("\n\t")}
EOS
    end
  else
    joint = passed_word_requirement.dup
  end
  
  if joint.none?
    if must_match_grouping
      if gather_last_result
        last_result.timeline << <<-EOS
Since :must_match_at_least_one_word => true and none of the competition was in the same group as the needle, the search stopped.
EOS
      end
      if is_find_all
        return []
      else
        return nil
      end
    else
      joint = passed_word_requirement.dup
    end
  end
      
  if identities.any?
    possibly_identical = joint.select do |straw|
      identities.all? do |identity|
        answer = identity.identical? needle, straw
        answer.nil? or answer == true
      end
    end
    if gather_last_result
      last_result.timeline << <<-EOS
Since there were identities, the competition was reduced to records that might be identical to the needle (in other words, are not certainly different)
\tIdentities (first 10 of #{identities.length}): #{identities[0,9].map(&:inspect).join(', ')}
\tPassed (first 10 of #{possibly_identical.length}): #{possibly_identical[0,9].map(&:inspect).join(', ')}
\tFailed (first 10 of #{(joint-possibly_identical).length}): #{(joint-possibly_identical)[0,9].map(&:inspect).join(', ')}
EOS
    end
  else
    possibly_identical = joint.dup
  end
  
  similarities = possibly_identical.map { |straw| needle.similarity straw }.sort.reverse
      
  if gather_last_result
    last_result.timeline << <<-EOS
The competition was sorted in order of similarity to the needle.
\t#{similarities[0,9].map { |s| "#{s.record2.similarity(needle).inspect}" }.join("\n\t")}
EOS
  end
  
  if is_find_all_with_score
    memo = []
    similarities.each do |similarity|
      if similarity.satisfy?(needle, threshold)
        bs = similarity.best_score
        memo << [similarity.record2.original, bs.dices_coefficient_similar, bs.levenshtein_similar]
      end
    end
    return memo
  end

  if is_find_best
    memo = []
    best_bs = nil
    similarities.each do |similarity|
      if similarity.satisfy?(needle, threshold)
        bs = similarity.best_score
        best_bs ||= bs
        if bs >= best_bs
          memo << similarity.record2.original
        else
          break
        end
      end
    end
    return memo
  end

  if is_find_all
    memo = []
    similarities.each do |similarity|
      if similarity.satisfy?(needle, threshold)
        memo << similarity.record2.original
      end
    end
    return memo
  end
  
  best_similarity = similarities.first
  winner = nil

  if best_similarity and best_similarity.satisfy?(needle, threshold)
    winner = best_similarity.record2.original
    if gather_last_result
      last_result.winner = winner
      last_result.score = best_similarity.best_score.dices_coefficient_similar
      last_result.timeline << <<-EOS
A winner was determined because the Dice's Coefficient similarity (#{'%0.5f' % best_similarity.best_score.dices_coefficient_similar}) is greater than zero or because it shared a word with the needle.
EOS
    end
    if is_find_with_score
      bs = best_similarity.best_score
      return [winner, bs.dices_coefficient_similar, bs.levenshtein_similar]
    else
      return winner
    end
  elsif gather_last_result
    best_similarity_record = if best_similarity and best_similarity.record2
      best_similarity.record2.original
    end
    last_result.timeline << <<-EOS
No winner assigned because the score of the best similarity (#{best_similarity_record.inspect}) was zero and it didn't match any words with the needle (#{needle.inspect}).
EOS
  end

  nil # ugly
end

#find_all(needle, options = {}) ⇒ Object

Return everything in sorted order



91
92
93
94
# File 'lib/fuzzy_match.rb', line 91

def find_all(needle, options = {})
  options = options.merge(:find_all => true)
  find needle, options
end

#find_all_with_score(needle, options = {}) ⇒ Object

Return everything in sorted order with score



103
104
105
106
# File 'lib/fuzzy_match.rb', line 103

def find_all_with_score(needle, options = {})
  options = options.merge(:find_all_with_score => true)
  find needle, options
end

#find_best(needle, options = {}) ⇒ Object

Return the top results with the same score



97
98
99
100
# File 'lib/fuzzy_match.rb', line 97

def find_best(needle, options = {})
  options = options.merge(:find_best => true)
  find needle, options
end

#find_with_score(needle, options = {}) ⇒ Object

Return one with score



109
110
111
112
# File 'lib/fuzzy_match.rb', line 109

def find_with_score(needle, options = {})
  options = options.merge(:find_with_score => true)
  find needle, options
end

#last_resultObject



86
87
88
# File 'lib/fuzzy_match.rb', line 86

def last_result
  @last_result or raise("You can't access the last result until you've run a find with :gather_last_result => true")
end