blib/lib/Search/OpenSearch/Engine/Xapian.pm

filter: Statementstmt 83.3% 10 / 12 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 4 / 4 Podpod n/a totaltotal 87.5% 14 / 16 CC 1 SCAR 0.7
CC
1
Cov
83%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
↑ Summary
1 package Search::OpenSearch::Engine::Xapian;
2 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use base 'Search::OpenSearch::Engine';
Subroutine BEGIN: called CC=1 SCAR=0.0
5 0 ▶use SWISH::Prog::Xapian::Searcher;
Subroutine BEGIN: called CC=1 SCAR=2.6
6 use SWISH::Prog::Xapian::Indexer;
7 use SWISH::Prog::Xapian::InvIndex;
8 use SWISH::Prog::Doc;
9 use SWISH::Prog::Aggregator;
10 use SWISH::3 qw( :constants );
11 use Carp;
12 use Data::Dump qw( dump );
13 use Scalar::Util qw( blessed );
14  
15 our $VERSION = '0.05';
16  
17 =head1 NAME
18  
19 Search::OpenSearch::Engine::Xapian - Xapian engine for OpenSearch results
20  
21 =head1 SYNOPSIS
22  
23 use Search::OpenSearch::Engine::Xapian;
24 my $engine = Search::OpenSearch::Engine::Xapian->new(
25 index => [qw( path/to/index1 path/to/index2 )],
26 facets => {
27 names => [qw( color size flavor )],
28 sample_size => 10_000,
29 },
30 fields => [qw( color size flavor )], # result attributes in response
31 indexer_config => {
32 somekey => somevalue,
33 },
34 searcher_config => {
35 anotherkey => anothervalue,
36 },
37 cache => CHI->new(
38 driver => 'File',
39 dir_create_mode => 0770,
40 file_create_mode => 0660,
41 root_dir => "/tmp/opensearch_cache",
42 ),
43 cache_ttl => 3600,
44 do_not_hilite => [qw( color )],
45 snipper_config => { as_sentences => 1 }, # see Search::Tools::Snipper
46 hiliter_config => { class => 'h', tag => 'b' }, # see Search::Tools::HiLiter
47 parser_config => {}, # see Search::Query::Parser
48
49 );
50 my $response = $engine->search(
51 q => 'quick brown fox', # query
52 s => 'rank desc', # sort order
53 o => 0, # offset
54 p => 25, # page size
55 h => 1, # highlight query terms in results
56 c => 0, # count total only (same as f=0 r=0)
57 L => 'field|low|high', # limit results to inclusive range
58 f => 1, # include facets
59 r => 1, # include results
60 t => 'XML', # or JSON
61 u => 'http://yourdomain.foo/opensearch/',
62 b => 'AND', # or OR
63 );
64 print $response;
65  
66 =head1 DESCRIPTION
67  
68 =head1 METHODS
69  
70 =head2 init_searcher
71  
72 Returns a SWISH::Prog::Xapian::Searcher object.
73  
74 =head2 init_indexer
75  
76 Returns a SWISH::Prog::Xapian::Indexer object (used by the REST API).
77  
78 =head2 init_suggester
79  
80 Returns undefined. Available to support Engine API.
81  
82 =head2 get_allowed_http_methods
83  
84 Returns array of GET, POST, PUT, DELETE. Available to support Engine API.
85  
86 =head2 build_facets( I<query>, I<results> )
87  
88 Returns hash ref of facets from I<results>. See Search::OpenSearch::Engine.
89  
90 =head2 process_result( I<args> )
91  
92 Overrides base method to preserve multi-value fields as arrays.
93  
94 =head2 has_rest_api
95  
96 Returns true.
97  
98 =head2 PUT( I<doc> )
99  
100 =head2 POST( I<doc> )
101  
102 =head2 DELETE( I<uri> )
103  
104 =head2 GET( I<uri> )
105  
106 =cut
107  
108 sub init_searcher {
109 my $self = shift;
110 my $index = $self->index or croak "index not defined";
111 my $searcher = SWISH::Prog::Xapian::Searcher->new(
112 invindex => $index,
113 debug => $self->debug,
114 %{ $self->searcher_config },
115 );
116 if ( !$self->fields ) {
117 $self->fields( [ keys %{ $searcher->prop_id_map } ] );
118 }
119 return $searcher;
120 }
121  
122 sub init_indexer {
123 my $self = shift;
124  
125 # unlike a Searcher, which has an array of invindex objects,
126 # the Indexer wants only one. We take the first by default,
127 # but a subclass could do more subtle logic here.
128  
129 my $indexer = SWISH::Prog::Xapian::Indexer->new(
130  
131 # first the index value to stringify in case it is an InvIndex
132 # object. Otherwise, the indexer and searcher can end up sharing
133 # the same xdb handle, which we definitely do not want.
134 invindex => $self->index->[0] . "",
135 debug => $self->debug,
136 %{ $self->indexer_config },
137 );
138 return $indexer;
139 }
140  
141 sub build_facets {
142 my $self = shift;
143 my $query = shift or croak "query required";
144 my $results = shift or croak "results required";
145 if ( $self->debug and $self->logger ) {
146 $self->logger->log(
147 "build_facets check for self->facets=" . $self->facets );
148 }
149 my $facetobj = $self->facets or return;
150  
151 my @facet_names = @{ $facetobj->names };
152 my $sample_size = $facetobj->sample_size || 0;
153 if ( $self->debug and $self->logger ) {
154 $self->logger->log( "building facets for "
155 . dump( \@facet_names )
156 . " with sample_size=$sample_size" );
157 }
158 my $searcher = $self->searcher;
159  
160 # run the search, aborting after $sample_size for speed
161 my $facet_results = $searcher->search(
162 $query,
163 { get_facets => \@facet_names,
164 facet_sample => $sample_size
165 }
166 );
167  
168 # turn the struct inside out a bit, esp for XML
169 my %facet_struct;
170 my $facets = $facet_results->facets;
171 for my $f ( keys %$facets ) {
172 for my $n ( keys %{ $facets->{$f} } ) {
173 push @{ $facet_struct{$f} },
174 { term => $n, count => $facets->{$f}->{$n} };
175 }
176 }
177 return \%facet_struct;
178 }
179  
180 sub has_rest_api {1}
181 sub get_allowed_http_methods { return qw( GET PUT POST DELETE ) }
182 sub init_suggester { }
183  
184 sub _massage_rest_req_into_doc {
185 my ( $self, $req ) = @_;
186  
187 #dump $req;
188 my $doc;
189  
190 if ( !blessed($req) ) {
191 $doc = SWISH::Prog::Doc->new(
192 version => 3,
193 %$req
194 );
195 }
196 else {
197  
198 #dump $req->headers;
199  
200 # $req should act like a HTTP::Request object.
201 my %args = (
202 version => 3,
203 url => $req->uri->path, # TODO test
204 content => $req->content,
205 size => $req->content_length,
206 type => $req->content_type,
207  
208 # type
209 # action
210 # parser
211 # modtime
212 );
213  
214 #dump \%args;
215  
216 $doc = SWISH::Prog::Doc->new(%args);
217  
218 }
219  
220 # use set_parser_from_type so that SWISH::3 does the Right Thing
221 # instead of looking at the original mime-type.
222 my $aggregator
223 = SWISH::Prog::Aggregator->new( set_parser_from_type => 1 );
224 $aggregator->swish_filter($doc);
225  
226 return $doc;
227 }
228  
229 # PUT only if it does not yet exist
230 sub PUT {
231 my $self = shift;
232 my $req = shift or croak "request required";
233 my $doc = $self->_massage_rest_req_into_doc($req);
234 my $uri = $doc->url;
235  
236 # edge case: index might not yet exist.
237 my $exists;
238 my $indexer = $self->init_indexer();
239 if ( -s $indexer->invindex->path->file('swish.xml') ) {
240 $exists = $self->GET($uri);
241 if ( $exists->{code} == 200 ) {
242 return { code => 409, msg => "Document $uri already exists" };
243 }
244 }
245 $indexer->process($doc);
246 my $total = $indexer->finish();
247 $exists = $self->GET( $doc->url );
248 if ( $exists->{code} != 200 ) {
249 return { code => 500, msg => 'Failed to PUT doc' };
250 }
251 return { code => 201, total => $total, doc => $exists->{doc} };
252 }
253  
254 # POST allows new and updates
255 sub POST {
256 my $self = shift;
257 my $req = shift or croak "request required";
258 my $doc = $self->_massage_rest_req_into_doc($req);
259 my $uri = $doc->url;
260 my $indexer = $self->init_indexer();
261 $indexer->process($doc);
262 my $total = $indexer->finish();
263 my $exists = $self->GET( $doc->url );
264  
265 if ( $exists->{code} != 200 ) {
266 return { code => 500, msg => 'Failed to POST doc' };
267 }
268 return { code => 200, total => $total, doc => $exists->{doc} };
269 }
270  
271 sub DELETE {
272 my $self = shift;
273 my $uri = shift or croak "uri required";
274 my $existing = $self->GET($uri);
275 if ( $existing->{code} != 200 ) {
276 return {
277 code => 404,
278 msg => "$uri cannot be deleted because it does not exist"
279 };
280 }
281 my $indexer = $self->init_indexer();
282 $indexer->start;
283 my $xdb = $indexer->invindex->xdb;
284 my $term = join( '', SWISH_PREFIX_URL(), $uri );
285 $xdb->delete_document_by_term($term);
286 $indexer->finish();
287 return {
288 code => 204, # no content in response
289 };
290 }
291  
292 sub GET {
293 my $self = shift;
294 my $uri = shift or croak "uri required";
295  
296 # TODO get by term
297 my $term = join( '', SWISH_PREFIX_URL(), $uri );
298 my $xdb = $self->searcher()->invindex->[0]->xdb;
299  
300 #warn "got xdb $xdb";
301 # always reopen in case handle is stale from a POST or PUT
302 $xdb->reopen();
303  
304 #warn "xdb->reopen $xdb";
305 if ( !$xdb->term_exists($term) ) {
306 return { code => 404, };
307 }
308  
309 # get all fields
310 my %doc;
311 my $fields = $self->fields;
312 my $doc_id = $xdb->postlist_begin($term);
313 my $x_doc = $xdb->get_document($doc_id);
314 my $prop_id_map = $self->searcher->prop_id_map;
315 for my $field (@$fields) {
316 if ( !exists $prop_id_map->{$field} ) {
317 croak "No such field: $field";
318 }
319 my $str = $x_doc->get_value( $prop_id_map->{$field} );
320 $doc{$field} = [ split( m/\003/, defined $str ? $str : "" ) ];
321 }
322 $doc{title} = $x_doc->get_value( $prop_id_map->{swishtitle} );
323 $doc{summary} = $x_doc->get_value( $prop_id_map->{'swishdescription'} );
324 $doc{mtime} = $x_doc->get_value( $prop_id_map->{'swishlastmodified'} );
325  
326 my $ret = {
327 code => 200,
328 doc => \%doc,
329 };
330  
331 #dump $ret;
332  
333 return $ret;
334 }
335  
336 1;
337  
338 __END__
↑ Summary