/[Grep]/lib/Grep/Search/KinoSearch.pm
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Diff of /lib/Grep/Search/KinoSearch.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 53 by dpavlin, Wed Feb 21 16:06:25 2007 UTC revision 185 by dpavlin, Wed Apr 9 17:39:40 2008 UTC
# Line 2  package Grep::Search; Line 2  package Grep::Search;
2    
3  use strict;  use strict;
4  use warnings;  use warnings;
5    use base qw( Class::Accessor );
6    Grep::Search->mk_accessors( qw( create index_path hits ) );
7    
8  use Data::Dump qw/dump/;  use Data::Dump qw/dump/;
9  use Lucene;  use KinoSearch::InvIndexer;
10    use KinoSearch::Searcher;
11  use Jifty::Util;  use Jifty::Util;
12    
13  my $index_path = Jifty::Util->app_root . '/var/lucene';  my $debug = 1;
14    
15  my ( $analyzer, $store, $writer );  =head1 NAME
16    
17  my $debug = 1;  Grep::Search - full text search using L<KinoSearch>
18    
19  sub create {  =head1 METHODS
20    
21          my $create = 0;  =head2 new
         if (! -e "$index_path/segments") {  
                 $create = 1;  
                 Jifty->log->debug("create index $index_path") unless ($store);  
         } else {  
                 Jifty->log->debug("open index: $index_path") unless ($store);  
         }  
         return $create;  
 }  
22    
23  sub analyzer {    my $search = Grep::Search->new();
         my $self = shift;  
         $analyzer ||= new Lucene::Analysis::Standard::StandardAnalyzer();  
         return $analyzer;  
 }  
24    
25  sub store {    my $search = Grep::Search->new( create => 1 );
26          my $self = shift;  
27    =cut
28    
29    sub log { Jifty->web->log }
30    
31    sub new {
32            my $class = shift;        
33            my $self = $class->SUPER::new(@_);
34    
35            my $index_path = Jifty::Util->app_root . '/var/invindex';
36    
37          $store ||= Lucene::Store::FSDirectory->getDirectory( $index_path, $self->create );          $self->index_path( $index_path );
38          return $store;  
39            return $self;
40  }  }
41    
42  sub writer {  =head2 invindexer
43    
44    Accessor to call any method defined on L<KinoSearch::InvIndexer>
45    
46      $search->invindexer->delete_by_term( 'id', 42 );
47    
48    =cut
49    
50    my $indexes;
51    
52    sub invindexer {
53          my $self = shift;          my $self = shift;
54          $writer ||= new Lucene::Index::IndexWriter( $self->store, $self->analyzer, $self->create );          my $invindexer;
55          return $writer;          my $index_path = $self->index_path or die "no index_path?";
56    
57            if ( $invindexer = $indexes->{$index_path} ) {
58                    $self->log->debug("Using cached index $index_path");
59            } else {
60                    if ( ! -e "$index_path" || $self->create ) {
61                            $self->log->debug("Creating new index $index_path");
62                            my $invindexer = KinoSearch::InvIndexer->new( invindex => Grep::Search::Schema->clobber( $index_path ) );
63                    } else {
64                            $self->log->debug("Opening index: $index_path");
65                            $invindexer = KinoSearch::InvIndexer->new( invindex => Grep::Search::Schema->open( $index_path ) );
66                    }
67                    $indexes->{$index_path} = $invindexer;
68            }
69    
70            $self->invindexer( $invindexer );
71    
72  }  }
73    
74  =head2 add  =head2 add
75    
76    Grep::Search->add( $record );    $search->add( $record, $owner_id );
77    
78  =cut  =cut
79    
# Line 54  sub add { Line 81  sub add {
81          my $self = shift;          my $self = shift;
82    
83          my $i = shift or die "no record to add";          my $i = shift or die "no record to add";
84            my $uid = shift;
85    
86          die "record not Jifty::Record but ", ref $i unless ($i->isa('Jifty::Record'));          die "record not Jifty::Record but ", ref $i unless ($i->isa('Jifty::Record'));
87    
88          my $pk = { $i->primary_keys };          my $pk = { $i->primary_keys };
89    
90          my $doc = new Lucene::Document;          my $doc;
91    
92          my @columns = map { $_->name } $i->columns;          my @columns = map { $_->name } $i->columns;
93    
# Line 75  sub add { Line 103  sub add {
103                                          my $col = $c . '_' . $f_c;                                          my $col = $c . '_' . $f_c;
104                                          if ( $f_v ) {                                          if ( $f_v ) {
105                                                  warn "  # $col = $f_v\n" if ($debug);                                                  warn "  # $col = $f_v\n" if ($debug);
106                                                  $doc->add(Lucene::Document::Field->Text( $col, $f_v ));                                                  $doc->{ $col } = $f_v;
107                                          } else {                                          } else {
108                                                  warn "  . $col is NULL\n" if ($debug);                                                  warn "  . $col is NULL\n" if ($debug);
109                                          }                                          }
# Line 84  sub add { Line 112  sub add {
112    
113                          if ($v->isa('Jifty::DateTime')) {                          if ($v->isa('Jifty::DateTime')) {
114                                  warn "  d $c = $v\n" if ($debug);                                  warn "  d $c = $v\n" if ($debug);
115                                  $doc->add(Lucene::Document::Field->Keyword( $c, "$v" ));                                  $doc->{$c} = $v;
116                          } else {                          } else {
117                                  warn "  s $c = $v [",ref($v),"]\n" if ($debug);                                  warn "  s $c = $v [",ref($v),"]\n" if ($debug);
118                          }                          }
# Line 93  sub add { Line 121  sub add {
121    
122                  next if (! defined($v) || $v eq '');                  next if (! defined($v) || $v eq '');
123    
124                  $v =~ s/<[^>]+>/ /gs;                  eval { $v =~ s/<[^>]+>/ /gs; };
125                    if ($@) {
126                            Jifty->log->error("can't strip html from $c in item ", $i->id);
127                            next;
128                    }
129    
130                  if ( defined( $pk->{$c} ) ) {                  if ( defined( $pk->{$c} ) ) {
131                          $doc->add(Lucene::Document::Field->Keyword( $c, $v ));                          $doc->{ $c } = $v;
132                          warn "  * $c = $v\n" if ($debug);                          warn "  * $c = $v\n" if ($debug);
133                  } else {                  } else {
134                          $doc->add(Lucene::Document::Field->Text( $c, $v ));                          $doc->{ $c } = $v;
135                          warn "  + $c = ", $self->snippet( 50, $v ), "\n" if ($debug);                          warn "  + $c = ", $self->snippet( 50, $v ), "\n" if ($debug);
136                  }                  }
137          }          }
138    
139          $self->writer->addDocument($doc);          # add _owner_id to speed up filtering of search results
140            $uid ||= Jifty->web->current_user->id;
141            $doc->{ '_owner_id' } = $uid;
142    
143            $self->invindexer->add_doc( $doc );
144    
145            $self->log->debug("added ", $i->id, " for user $uid to index");
146    
147          Jifty->log->debug("added ", $i->id, " to index");          return 1;
148  }  }
149    
150  =head2  =head2 collection
151    
152    Return C<Grep::Model::ItemCollection> which is result of C<search query>
153    
154      my $ItemCollection = $search->collection( 'search query' );
155    
156    =head2 hits
157    
158    my $ItemCollection = Grep::Search->collection( 'search query' );  Return number of results from last C<collection> call
159    
160      my $num_results = $search->hits;
161    
162  =cut  =cut
163    
# Line 120  sub collection { Line 166  sub collection {
166    
167          my $q = shift or die "no q?";          my $q = shift or die "no q?";
168    
169          my $searcher = new Lucene::Search::IndexSearcher($self->store);          my $searcher = KinoSearch::Searcher->new(
170          my $parser = new Lucene::QueryParser("content", $self->analyzer);                  invindex => Grep::Search::Schema->open( $self->index_path ), );
171          my $query = $parser->parse( $q );          $self->log->debug("$searcher created");
172    
173          Jifty->log->debug("searching for '$q'");          my $full_q = "($q)";
174    
175            my $uid = Jifty->web->current_user->id;
176            $full_q .= ' AND _owner_id:' . $uid if (defined $uid);
177    
178            $self->log->debug("searching for '$q' using $full_q");
179    
180            my $query_parser = KinoSearch::QueryParser->new(
181                    schema => Grep::Search::Schema->new,
182                    fields => [ qw/ title link content summary category author / ],
183            );
184            $query_parser->set_heed_colons(1);       # enable field:value AND/OR/NOT syntax
185            my $query = $query_parser->parse( $full_q );
186            my $hits = $searcher->search(
187                    query           => $query,
188    #               offset          => $offset,
189    #               num_wanted      => $hits_per_page,
190            );
191    
192          my $hits = $searcher->search($query);          $self->hits( $hits->total_hits );
         my $num_hits = $hits->length();  
193    
194          Jifty->log->debug("found $num_hits results");          $self->log->debug("found ", $self->hits, " results");
195    
196          my $collection = Grep::Model::ItemCollection->new();          my $collection = Grep::Model::ItemCollection->new();
197    
198          my @results;          my @results;
199    
200          for ( my $i = 0; $i < $num_hits; $i++ ) {          my $i = 0;
201            while ( my $hit = $hits->fetch_hit ) {
202    
203                  my $doc = $hits->doc( $i );                  my $score = $hit->{score};
204                    my $title = $hit->{title};
205                    my $id = $hit->{id};
206    
207                  my $score = $hits->score($i);                  $self->log->debug("result $i [$id] $title $score");
                 my $title = $doc->get("title");  
                 my $id = $doc->get("id");  
   
                 warn "## $i $score $title\n";  
208    
209                  my $item = Grep::Model::Item->new();                  my $item = Grep::Model::Item->new();
210                  my ($ok,$msg) = $item->load_by_cols( id => $id );                  my ($ok,$msg) = $item->load_by_cols( id => $id );
# Line 156  sub collection { Line 217  sub collection {
217    
218          }          }
219    
220          undef $hits;          $self->log->debug("finished search");
         undef $query;  
         undef $parser;  
         undef $searcher;  
221    
222          return $collection;          return $collection;
223  }  }
224    
225  =head2 finish  =head2 finish
226    
227    Grep::Search->finish    $search->finish
228    
229  =cut  =cut
230    
231  sub finish {  sub finish {
232          my $self = shift;          my $self = shift;
233          if ($writer) {          if ($self->invindexer) {
234                  warn "closing index\n";                  $self->log->debug("closing index");
235                  $writer->close;                  $self->invindexer->finish;
236          }          }
         undef $writer;  
 }  
237    
238  sub _signal {          $self->log->debug("finish");
         my $s = shift;  
         warn "catched SIG $s\n";  
         finish();  
         exit(0);  
 }  
239    
240  $SIG{'__DIE__'} = \&_signal;          undef $self;
 $SIG{'INT'} = \&_signal;  
 $SIG{'QUIT'} = \&_signal;  
241    
242            return 1;
243    }
244    
245  =head2 snippet  =head2 snippet
246    
247    my $short = $self->snippet( 50, $text );    my $short = $self->snippet( 50, $text );
248    
   
249  =cut  =cut
250    
251  sub snippet {  sub snippet {
# Line 213  sub snippet { Line 263  sub snippet {
263          }          }
264  }  }
265    
266    package Grep::Search::KeywordField;
267    use base qw( KinoSearch::Schema::FieldSpec );
268    sub analyzed { 0 }
269    #sub indexed { 1 }
270    #sub stored { 1 }
271    sub vectorized { 0 }
272    
273    package Grep::Search::Schema;
274    
275    =head1 NAME
276    
277    Grep::Search::Schema - schema definition for full-text search
278    
279    =cut
280    
281    use base 'KinoSearch::Schema';
282    use KinoSearch::Analysis::PolyAnalyzer;
283    
284    our %fields = (
285            id                              => 'Grep::Search::KeywordField',
286    
287            in_feed_id              => 'Grep::Search::KeywordField',
288            in_feed_url             => 'Grep::Search::KeywordField',
289            in_feed_title   => 'KinoSearch::Schema::FieldSpec',
290            in_feed_owner   => 'Grep::Search::KeywordField',
291            in_feed_created_on      => 'Grep::Search::KeywordField',
292    
293            title                   => 'KinoSearch::Schema::FieldSpec',
294            link                    => 'Grep::Search::KeywordField',
295            content                 => 'KinoSearch::Schema::FieldSpec',
296            summary                 => 'KinoSearch::Schema::FieldSpec',
297            category                => 'KinoSearch::Schema::FieldSpec',
298            author                  => 'KinoSearch::Schema::FieldSpec',
299            created_on              => 'Grep::Search::KeywordField',
300            last_update             => 'Grep::Search::KeywordField',
301    
302            _owner_id               => 'Grep::Search::KeywordField',
303    );
304    
305    sub analyzer {
306            return KinoSearch::Analysis::PolyAnalyzer->new( language => 'en' );
307    }
308    
309  1;  1;

Legend:
Removed from v.53  
changed lines
  Added in v.185

  ViewVC Help
Powered by ViewVC 1.1.26