Xapian/Indexer.pm

filter: Statementstmt 86.6% 13 / 15 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 5 / 5 Podpod n/a totaltotal 90.0% 18 / 20 CC 1 SCAR 0.6
CC
1
Cov
87%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« Xapian/Results.pm ↑ Summary Xapian/Searcher.pm »
1 package SWISH::Prog::Xapian::Indexer;
2 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use base qw( SWISH::Prog::Indexer );
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 0 ▶use SWISH::Prog::Xapian::InvIndex;
Subroutine BEGIN: called CC=1 SCAR=2.6
7 use Search::Xapian::Document;
8 use Search::Xapian::TermGenerator;
9 use SWISH::3 qw( :constants );
10 use Scalar::Util qw( blessed );
11 use Data::Dump qw( dump );
12 use Path::Class::File::Lockable;
13  
14 our $VERSION = '0.09';
15  
16 =head1 NAME
17  
18 SWISH::Prog::Xapian::Indexer - Swish3 Xapian backend Indexer
19  
20 =head1 SYNOPSIS
21  
22 # see SWISH::Prog::Indexer
23
24 =cut
25  
26 =head1 METHODS
27  
28 Only new and overridden methods are documented here. See
29 the L<SWISH::Prog::Indexer> documentation.
30  
31 =head2 init
32  
33 =cut
34  
35 sub init {
36 my $self = shift;
37 $self->SUPER::init(@_);
38  
39 $self->{invindex} ||= SWISH::Prog::Xapian::InvIndex->new;
40  
41 if ( $self->{invindex} && !blessed( $self->{invindex} ) ) {
42 $self->{invindex}
43 = SWISH::Prog::Xapian::InvIndex->new( path => $self->{invindex} );
44 }
45  
46 unless ( $self->invindex->isa('SWISH::Prog::Xapian::InvIndex') ) {
47 croak ref($self)
48 . " requires SWISH::Prog::Xapian::InvIndex-derived object";
49 }
50  
51 $self->{flush} ||= 100000;
52  
53 # config resolution order
54 # 1. default config via SWISH::3->new
55  
56 # TODO can pass s3 in?
57 $self->{s3} ||= SWISH::3->new(
58 handler => sub {
59 $self->_handler(@_);
60 }
61 );
62  
63 # 2. any existing header file.
64 my $swish_3_index = $self->invindex->path->file( SWISH_HEADER_FILE() );
65 if ( -r $swish_3_index ) {
66 $self->{s3}->config->add("$swish_3_index");
67 }
68  
69 # 3. via 'config' param passed to this method
70 if ( exists $self->{config} ) {
71  
72 # this utility method defined in base SWISH::Prog::Indexer class.
73 $self->_verify_swish3_config();
74 }
75  
76 # 4. always turn off tokenizer, preferring Xapian do it
77 $self->{s3}->analyzer->set_tokenize(0);
78  
79 my $config = $self->{s3}->config;
80 my $lang = $config->get_index->get( SWISH_INDEX_STEMMER_LANG() )
81 || 'none';
82 $self->{_lang} = $lang; # cache for finish()
83  
84 # TODO apply stemming
85  
86 return $self;
87  
88 }
89  
90 # trick is mapping between the basic SWISH::3::Doc structure
91 # and the Xapian::Document structure
92 # not much to it really: just save properties as 'value'
93 # and tokens as 'posting'
94 # swishdescription could be saved as 'data'
95 # uri gets saved as 'term' (xapian uses for unique id)
96  
97 # set_data() can be used to store whatever you want
98 # but can't be sorted on. so it's like an unsortable property
99  
100 # add_value() is similar to Swish-e properties
101 # results can be sorted by 'value'
102 # and each 'value' needs a unique number (like a property id)
103  
104 # add_term() is where you would add a word with no positional info
105 # could have META: prefixed however and optional 'weight' as second param
106 # we use uri as unique term
107  
108 # add_posting() is for adding specific words with positional info
109 # can take 'weight' as optional 3rd param
110 # we add twice so a word can be found 'naked' and with explicit metaname prefix
111  
112 sub _handler {
113 my ( $self, $data ) = @_;
114  
115 #warn "handler called";
116  
117 # MetaNames and PropertyNames may be added for each new doc.
118 my $PropertyNames = $data->config->get_properties;
119 my $MetaNames = $data->config->get_metanames;
120 my $PNames = $PropertyNames->keys;
121 my $MNames = $MetaNames->keys;
122  
123 my $xdoc = Search::Xapian::Document->new
124 or croak "can't create Search::Xapian::Document object";
125  
126 my $docinfo = $data->doc;
127  
128 # unique identifier
129 my $uri = join( '', SWISH_PREFIX_URL(), $docinfo->uri );
130 $xdoc->add_term($uri);
131 $xdoc->add_term( join( '', SWISH_PREFIX_MTIME(), $docinfo->mtime ) );
132  
133 #warn "add $uri";
134  
135 # TODO add date parts as terms like swish_xapian.cpp does
136  
137 # data record like swish_xapian.cpp does
138 my $record = join( "\n",
139 'url=' . $docinfo->uri,
140 'title='
141 . ( join( "\n", @{ $data->properties->{'swishtitle'} } ) || '' ),
142 'type=' . $docinfo->mime,
143 'modtime=' . $docinfo->mtime,
144 'size=' . $docinfo->size );
145 $xdoc->set_data($record);
146  
147 # example
148 # for my $p (@$PNames) {
149 # my $prop = $PropertyNames->get($p);
150 # my $property = {
151 # id => $prop->id,
152 # name => $prop->name,
153 # type => $prop->type,
154 # ignore_case => $prop->ignore_case,
155 # verbatim => $prop->verbatim,
156 #
157 # #alias_for => $prop->alias_for,
158 # max => $prop->max,
159 # sort => $prop->sort,
160 # };
161 #
162 # }
163 #
164 # # same thing for MetaNames
165 # for my $m (@$MNames) {
166 # next if exists $self->{_metanames}->{$m};
167 # my $meta = $MetaNames->get($m);
168 # my $metaname = {
169 # id => $meta->id,
170 # name => $meta->name,
171 # bias => $meta->bias,
172 #
173 # #alias_for => $m->alias_for
174 # };
175 # }
176  
177 # TODO add_posting() is the most intensive and should likely be XS-ified.
178 # for now, use TermGenerator instead.
179 # MAKE SURE TO TURN TOKENIZER OFF in parser,
180 # since otherwise we tokenize 2x.
181  
182 # the TermGenerator tokenizes using the same algorithm as the QueryParser
183 # http://thread.gmane.org/gmane.comp.search.xapian.general/6905/focus=6907
184 my $analyzer = Search::Xapian::TermGenerator->new;
185 $analyzer->set_document($xdoc);
186  
187 #warn "set document";
188  
189 my $metanames = $data->metanames;
190 for my $metaname (@$MNames) {
191 my $meta = $MetaNames->get($metaname);
192 my $name = $meta->name;
193  
194 # TODO allow negative values
195 my $weight = $meta->bias > 0 ? $meta->bias : 1;
196  
197 #warn "meta $name weight $weight";
198 #warn dump $metanames->{$name};
199  
200 $analyzer->index_text(
201 join( SWISH_TOKENPOS_BUMPER(), @{ $metanames->{$name} } ),
202 $weight, $meta->id . ':' );
203  
204 # index swishdefault and swishtitle without any prefix as well
205 if ( $name eq SWISH_DEFAULT_METANAME()
206 or $name eq SWISH_TITLE_METANAME() )
207 {
208 $analyzer->index_text(
209 join( SWISH_TOKENPOS_BUMPER(), @{ $metanames->{$name} } ),
210 $weight );
211 }
212  
213 }
214  
215 # add_value() is similar to Swish-e properties
216 # results can be sorted by 'value'
217 # and each 'value' needs a unique number (like a property id)
218 for my $d ( SWISH_DOC_FIELDS() ) {
219 next if $d eq 'ext';
220  
221 #warn "docinfo $d -> " . $docinfo->$d;
222 $xdoc->add_value( SWISH_DOC_FIELDS_MAP()->{$d}, $docinfo->$d );
223 }
224  
225 # ProperyNames
226 my $properties = $data->properties;
227 for my $prop_name (@$PNames) {
228 my $prop_value = $properties->{$prop_name};
229 my $prop_id = $PropertyNames->get($prop_name)->id;
230  
231 #warn "prop $prop_name id $prop_id";
232 #warn dump $prop_value;
233  
234 # TODO best way to join() ?
235 $xdoc->add_value( $prop_id, join( "\n", @$prop_value ) );
236  
237 #warn "add_value $prop_id";
238 }
239  
240 #warn "xdoc prepped";
241  
242 my $action = $docinfo->action || 'add_or_update';
243 my $method = '_' . $action;
244  
245 #warn "$method on $uri";
246 my $doc_id = $self->$method( $xdoc, $uri ); # TODO stash doc_id?
247  
248 }
249  
250 =head2 process
251  
252 =cut
253  
254 sub process {
255 my $self = shift;
256 my $sdoc = $self->SUPER::process(@_);
257 $self->{s3}->parse_buffer("$sdoc");
258 if ( $self->count > $self->flush ) {
259 $self->invindex->xdb->flush;
260 }
261 return $sdoc;
262 }
263  
264 sub _add_or_update {
265 my ( $self, $xdoc, $uri ) = @_;
266  
267 if ( $self->invindex->xdb->term_exists($uri) ) {
268 return $self->_update( $xdoc, $uri );
269 }
270 else {
271 return $self->_add($xdoc);
272 }
273 }
274  
275 sub _add {
276 my ( $self, $xdoc, $uri ) = @_;
277 $self->debug and carp "add document $uri";
278 return $self->invindex->xdb->add_document($xdoc);
279 }
280  
281 sub _update {
282 my ( $self, $xdoc, $uri ) = @_;
283 my $doc_id = $self->invindex->xdb->postlist_begin($uri)
284 or croak "no such doc in index $self->{invindex}: $uri";
285 $self->debug and carp "update document $uri";
286 $self->invindex->xdb->replace_document( $doc_id, $xdoc );
287 return $doc_id;
288 }
289  
290 sub _delete {
291 my ( $self, $xdoc, $uri ) = @_;
292 my $doc_id = $self->invindex->xdb->postlist_begin($uri)
293 or croak "no such doc in index: $uri";
294  
295 $self->invindex->xdb->delete_document($doc_id);
296 return $doc_id;
297 }
298  
299 =head2 finish
300  
301 Write the index header and flush the index.
302  
303 =cut
304  
305 my @chars = ( 'a' .. 'z', 'A' .. 'Z', 0 .. 9 );
306  
307 sub finish {
308 my $self = shift;
309  
310 return 0 if $self->{_is_finished};
311  
312 # get a lock on our header file till
313 # this entire transaction is complete.
314 # Note that we trust the Lucy locking feature
315 # to have prevented any other process
316 # from getting a lock on the invindex itself,
317 # but we want to make sure nothing interrupts
318 # us from writing our own header after calling ->commit().
319 my $xdb = $self->invindex->xdb;
320 my $invindex = $self->invindex->path;
321 my $header = $invindex->file( SWISH_HEADER_FILE() )->stringify;
322 my $lock_file = Path::Class::File::Lockable->new($header);
323 if ( $lock_file->locked ) {
324 croak "Lock file found on $header -- cannot commit indexing changes";
325 }
326 $lock_file->lock;
327  
328 # write header
329 my $index = $self->{s3}->config->get_index;
330  
331 my $doc_count = $xdb->get_doccount();
332  
333 # poor man's uuid
334 my $uuid = join( "", @chars[ map { rand @chars } ( 1 .. 24 ) ] );
335  
336 $index->set( SWISH_INDEX_NAME(), "$invindex" );
337 $index->set( SWISH_INDEX_FORMAT(), 'Xapian' );
338 $index->set( SWISH_INDEX_STEMMER_LANG(), $self->{_lang} );
339 $index->set( "DocCount", $doc_count );
340  
341 #$self->{s3}->config->set_index($index);
342  
343 $self->{s3}->config->write($header);
344  
345 # transaction complete
346 $lock_file->unlock;
347  
348 $self->debug and carp "wrote $header with $uuid";
349  
350 $self->{s3} = undef; # just to avoid mem leak warnings
351  
352 $self->{_is_finished} = 1;
353  
354 $self->SUPER::finish(@_);
355 }
356  
357 1;
358  
359 __END__
« Xapian/Results.pm ↑ Summary Xapian/Searcher.pm »