| 1 | package KinoSearch1::Search::Similarity; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | use KinoSearch1::Util::ToolSet; | ||
| 5 | use base qw( KinoSearch1::Util::CClass ); | ||
| 6 | |||
| 7 | BEGIN { __PACKAGE__->init_instance_vars(); } | ||
| 8 | |||
| 9 | # See _float_to_byte. | ||
| 10 | *encode_norm = *_float_to_byte; | ||
| 11 | *decode_norm = *_byte_to_float; | ||
| 12 | |||
| 13 | # Calculate the Inverse Document Frequecy for one or more Term in a given | ||
| 14 | # collection (the Searcher represents the collection). | ||
| 15 | # | ||
| 16 | # If multiple Terms are supplied, their idfs are summed. | ||
| 17 | sub idf { | ||
| 18 | my ( $self, $term_or_terms, $searcher ) = @_; | ||
| 19 | my $max_doc = $searcher->max_doc; | ||
| 20 | my $terms | ||
| 21 | = ref $term_or_terms eq 'ARRAY' ? $term_or_terms : [$term_or_terms]; | ||
| 22 | |||
| 23 | return 1 unless $max_doc; # guard against log of zero error | ||
| 24 | |||
| 25 | # accumulate IDF | ||
| 26 | my $idf = 0; | ||
| 27 | for my $term (@$terms) { | ||
| 28 | my $doc_freq = $searcher->doc_freq($term); | ||
| 29 | $idf += 1 + log( $max_doc / ( 1 + $searcher->doc_freq($term) ) ); | ||
| 30 | } | ||
| 31 | return $idf; | ||
| 32 | } | ||
| 33 | |||
| 34 | # Normalize a Query's weight so that it is comparable to other Queries. | ||
| 35 | sub query_norm { | ||
| 36 | my ( $self, $sum_of_squared_weights ) = @_; | ||
| 37 | return 0 if ( $sum_of_squared_weights == 0 ); # guard against div by zero | ||
| 38 | return ( 1 / sqrt($sum_of_squared_weights) ); | ||
| 39 | } | ||
| 40 | |||
| 41 | # KLUDGE -- see comment at STORABLE_thaw. | ||
| 42 | sub STORABLE_freeze { | ||
| 43 | my ( $self, $cloning ) = @_; | ||
| 44 | return if $cloning; | ||
| 45 | return "1"; | ||
| 46 | } | ||
| 47 | |||
| 48 | package KinoSearch1::Search::TitleSimilarity; | ||
| 49 | use strict; | ||
| 50 | use warnings; | ||
| 51 | use KinoSearch1::Util::ToolSet; | ||
| 52 | use base qw( KinoSearch1::Search::Similarity ); | ||
| 53 | |||
| 54 | sub new { | ||
| 55 | my $self = shift->SUPER::new(@_); | ||
| 56 | $self->_use_title_tf; | ||
| 57 | return $self; | ||
| 58 | } | ||
| 59 | |||
| 60 | sub lengthnorm { | ||
| 61 | return 0 unless $_[1]; | ||
| 62 | return 1 / sqrt( $_[1] ); | ||
| 63 | } | ||
| 64 | |||
| 65 | 1; | ||
| 66 | |||
| 67 | __END__ |