Bug 14419: Expanding facets (Show more) performs a new search
[koha.git] / t / db_dependent / Koha / SearchEngine / Elasticsearch / QueryBuilder.t
1 #!/usr/bin/perl
2 #
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18 use Modern::Perl;
19
20 use C4::Context;
21 use Test::Exception;
22 use t::lib::Mocks;
23 use t::lib::TestBuilder;
24 use Test::More tests => 6;
25
26 use Koha::Database;
27 use Koha::SearchEngine::Elasticsearch::QueryBuilder;
28
29 my $schema = Koha::Database->new->schema;
30 $schema->storage->txn_begin;
31
32 my $se = Test::MockModule->new( 'Koha::SearchEngine::Elasticsearch' );
33 $se->mock( 'get_elasticsearch_mappings', sub {
34     my ($self) = @_;
35
36     my %all_mappings;
37
38     my $mappings = {
39         data => {
40             properties => {
41                 title => {
42                     type => 'text'
43                 },
44                 title__sort => {
45                     type => 'text'
46                 },
47                 subject => {
48                     type => 'text'
49                 },
50                 itemnumber => {
51                     type => 'integer'
52                 },
53                 sortablenumber => {
54                     type => 'integer'
55                 },
56                 sortablenumber__sort => {
57                     type => 'integer'
58                 },
59                 Heading => {
60                     type => 'text'
61                 },
62                 Heading__sort => {
63                     type => 'text'
64                 }
65             }
66         }
67     };
68     $all_mappings{$self->index} = $mappings;
69
70     my $sort_fields = {
71         $self->index => {
72             title => 1,
73             subject => 0,
74             itemnumber => 0,
75             sortablenumber => 1,
76             mainentry => 1
77         }
78     };
79     $self->sort_fields($sort_fields->{$self->index});
80
81     return $all_mappings{$self->index};
82 });
83
84 subtest 'build_authorities_query_compat() tests' => sub {
85     plan tests => 36;
86
87     my $qb;
88
89     ok(
90         $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new({ 'index' => 'authorities' }),
91         'Creating new query builder object for authorities'
92     );
93
94     my $koha_to_index_name = $Koha::SearchEngine::Elasticsearch::QueryBuilder::koha_to_index_name;
95     my $search_term = 'a';
96     foreach my $koha_name ( keys %{ $koha_to_index_name } ) {
97         my $query = $qb->build_authorities_query_compat( [ $koha_name ],  undef, undef, ['contains'], [$search_term], 'AUTH_TYPE', 'asc' );
98         if ( $koha_name eq 'all' || $koha_name eq 'any' ) {
99             is( $query->{query}->{bool}->{must}[0]->{query_string}->{query},
100                 "a*");
101         } else {
102             is( $query->{query}->{bool}->{must}[0]->{query_string}->{query},
103                 "a*");
104         }
105     }
106
107     $search_term = 'Donald Duck';
108     foreach my $koha_name ( keys %{ $koha_to_index_name } ) {
109         my $query = $qb->build_authorities_query_compat( [ $koha_name ],  undef, undef, ['contains'], [$search_term], 'AUTH_TYPE', 'asc' );
110         if ( $koha_name eq 'all' || $koha_name eq 'any' ) {
111             is( $query->{query}->{bool}->{must}[0]->{query_string}->{query},
112                 "(Donald*) AND (Duck*)");
113         } else {
114             is( $query->{query}->{bool}->{must}[0]->{query_string}->{query},
115                 "(Donald*) AND (Duck*)");
116         }
117     }
118
119     foreach my $koha_name ( keys %{ $koha_to_index_name } ) {
120         my $query = $qb->build_authorities_query_compat( [ $koha_name ],  undef, undef, ['is'], [$search_term], 'AUTH_TYPE', 'asc' );
121         if ( $koha_name eq 'all' || $koha_name eq 'any' ) {
122             is( $query->{query}->{bool}->{must}[0]->{match_phrase}->{"_all.phrase"},
123                 "donald duck");
124         } else {
125             is( $query->{query}->{bool}->{must}[0]->{match_phrase}->{$koha_to_index_name->{$koha_name}.".phrase"},
126                 "donald duck");
127         }
128     }
129
130     foreach my $koha_name ( keys %{ $koha_to_index_name } ) {
131         my $query = $qb->build_authorities_query_compat( [ $koha_name ],  undef, undef, ['start'], [$search_term], 'AUTH_TYPE', 'asc' );
132         if ( $koha_name eq 'all' || $koha_name eq 'any' ) {
133             is( $query->{query}->{bool}->{must}[0]->{match_phrase_prefix}->{"_all.phrase"},
134                 "donald duck");
135         } else {
136             is( $query->{query}->{bool}->{must}[0]->{match_phrase_prefix}->{$koha_to_index_name->{$koha_name}.".phrase"},
137                 "donald duck");
138         }
139     }
140
141     # Sorting
142     my $query = $qb->build_authorities_query_compat( [ 'mainentry' ],  undef, undef, ['start'], [$search_term], 'AUTH_TYPE', 'HeadingAsc' );
143     is_deeply(
144         $query->{sort},
145         [
146             {
147                 'heading__sort' => 'asc'
148             }
149         ],
150         "ascending sort parameter properly formed"
151     );
152     $query = $qb->build_authorities_query_compat( [ 'mainentry' ],  undef, undef, ['start'], [$search_term], 'AUTH_TYPE', 'HeadingDsc' );
153     is_deeply(
154         $query->{sort},
155         [
156             {
157                 'heading__sort' => 'desc'
158             }
159         ],
160         "descending sort parameter properly formed"
161     );
162
163     # Failing case
164     throws_ok {
165         $qb->build_authorities_query_compat( [ 'tomas' ],  undef, undef, ['contains'], [$search_term], 'AUTH_TYPE', 'asc' );
166     }
167     'Koha::Exceptions::WrongParameter',
168         'Exception thrown on invalid value in the marclist param';
169 };
170
171 subtest 'build_query tests' => sub {
172     plan tests => 35;
173
174     my $qb;
175
176     ok(
177         $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new({ 'index' => 'biblios' }),
178         'Creating new query builder object for biblios'
179     );
180
181     my @sort_by = 'title_asc';
182     my @sort_params = $qb->_convert_sort_fields(@sort_by);
183     my %options;
184     $options{sort} = \@sort_params;
185     my $query = $qb->build_query('test', %options);
186
187     is_deeply(
188         $query->{sort},
189         [
190             {
191             'title__sort.phrase' => {
192                     'order' => 'asc'
193                 }
194             }
195         ],
196         "sort parameter properly formed"
197     );
198
199     t::lib::Mocks::mock_preference('FacetMaxCount','37');
200     $query = $qb->build_query('test', %options);
201     ok( defined $query->{aggregations}{ccode}{terms}{size},'we need to ask for a size or we get only 5 facet' );
202     is( $query->{aggregations}{ccode}{terms}{size}, 37,'we ask for the size as defined by the syspref FacetMaxCount');
203
204     t::lib::Mocks::mock_preference('DisplayLibraryFacets','both');
205     $query = $qb->build_query();
206     ok( defined $query->{aggregations}{homebranch},
207         'homebranch added to facets if DisplayLibraryFacets=both' );
208     ok( defined $query->{aggregations}{holdingbranch},
209         'holdingbranch added to facets if DisplayLibraryFacets=both' );
210     t::lib::Mocks::mock_preference('DisplayLibraryFacets','holding');
211     $query = $qb->build_query();
212     ok( !defined $query->{aggregations}{homebranch},
213         'homebranch not added to facets if DisplayLibraryFacets=holding' );
214     ok( defined $query->{aggregations}{holdingbranch},
215         'holdingbranch added to facets if DisplayLibraryFacets=holding' );
216     t::lib::Mocks::mock_preference('DisplayLibraryFacets','home');
217     $query = $qb->build_query();
218     ok( defined $query->{aggregations}{homebranch},
219         'homebranch added to facets if DisplayLibraryFacets=home' );
220     ok( !defined $query->{aggregations}{holdingbranch},
221         'holdingbranch not added to facets if DisplayLibraryFacets=home' );
222
223     t::lib::Mocks::mock_preference( 'QueryAutoTruncate', '' );
224
225     ( undef, $query ) = $qb->build_query_compat( undef, ['donald duck'] );
226     is(
227         $query->{query}{query_string}{query},
228         "(donald duck)",
229         "query not altered if QueryAutoTruncate disabled"
230     );
231
232     ( undef, $query ) = $qb->build_query_compat( undef, ['donald duck'], ['title'] );
233     is(
234         $query->{query}{query_string}{query},
235         '(title:(donald duck))',
236         'multiple words in a query term are enclosed in parenthesis'
237     );
238
239     ( undef, $query ) = $qb->build_query_compat( ['AND'], ['donald duck', 'disney'], ['title', 'author'] );
240     is(
241         $query->{query}{query_string}{query},
242         '(title:(donald duck)) AND (author:disney)',
243         'multiple query terms are enclosed in parenthesis while a single one is not'
244     );
245
246     my ($simple_query, $query_cgi, $query_desc);
247     ( undef, $query, $simple_query, $query_cgi, $query_desc ) = $qb->build_query_compat( undef, ['"donald duck"', 'walt disney'], ['ti', 'au'] );
248     is($query_cgi, 'idx=ti&q=%22donald%20duck%22&idx=au&q=walt%20disney', 'query cgi ok for multiterm query');
249     is($query_desc, '(title:("donald duck")) (author:(walt disney))', 'query desc ok for multiterm query');
250
251     t::lib::Mocks::mock_preference( 'QueryAutoTruncate', '1' );
252
253     ( undef, $query ) = $qb->build_query_compat( undef, ['donald duck'] );
254     is(
255         $query->{query}{query_string}{query},
256         "(donald* duck*)",
257         "simple query is auto truncated when QueryAutoTruncate enabled"
258     );
259
260     # Ensure reserved words are not truncated
261     ( undef, $query ) = $qb->build_query_compat( undef,
262         ['donald or duck and mickey not mouse'] );
263     is(
264         $query->{query}{query_string}{query},
265         "(donald* or duck* and mickey* not mouse*)",
266         "reserved words are not affected by QueryAutoTruncate"
267     );
268
269     ( undef, $query ) = $qb->build_query_compat( undef, ['donald* duck*'] );
270     is(
271         $query->{query}{query_string}{query},
272         "(donald* duck*)",
273         "query with '*' is unaltered when QueryAutoTruncate is enabled"
274     );
275
276     ( undef, $query ) = $qb->build_query_compat( undef, ['donald duck and the mouse'] );
277     is(
278         $query->{query}{query_string}{query},
279         "(donald* duck* and the* mouse*)",
280         "individual words are all truncated and stopwords ignored"
281     );
282
283     ( undef, $query ) = $qb->build_query_compat( undef, ['*'] );
284     is(
285         $query->{query}{query_string}{query},
286         "(*)",
287         "query of just '*' is unaltered when QueryAutoTruncate is enabled"
288     );
289
290     ( undef, $query ) = $qb->build_query_compat( undef, ['"donald duck"'] );
291     is(
292         $query->{query}{query_string}{query},
293         '("donald duck")',
294         "query with quotes is unaltered when QueryAutoTruncate is enabled"
295     );
296
297
298     ( undef, $query ) = $qb->build_query_compat( undef, ['"donald duck" and "the mouse"'] );
299     is(
300         $query->{query}{query_string}{query},
301         '("donald duck" and "the mouse")',
302         "all quoted strings are unaltered if more than one in query"
303     );
304
305     ( undef, $query ) = $qb->build_query_compat( undef, ['barcode:123456'] );
306     is(
307         $query->{query}{query_string}{query},
308         '(barcode:123456*)',
309         "query of specific field is truncated"
310     );
311
312     ( undef, $query ) = $qb->build_query_compat( undef, ['Local-number:"123456"'] );
313     is(
314         $query->{query}{query_string}{query},
315         '(local-number:"123456")',
316         "query of specific field including hyphen and quoted is not truncated, field name is converted to lower case"
317     );
318
319     ( undef, $query ) = $qb->build_query_compat( undef, ['Local-number:123456'] );
320     is(
321         $query->{query}{query_string}{query},
322         '(local-number:123456*)',
323         "query of specific field including hyphen and not quoted is truncated, field name is converted to lower case"
324     );
325
326     ( undef, $query ) = $qb->build_query_compat( undef, ['Local-number.raw:123456'] );
327     is(
328         $query->{query}{query_string}{query},
329         '(local-number.raw:123456*)',
330         "query of specific field including period and not quoted is truncated, field name is converted to lower case"
331     );
332
333     ( undef, $query ) = $qb->build_query_compat( undef, ['Local-number.raw:"123456"'] );
334     is(
335         $query->{query}{query_string}{query},
336         '(local-number.raw:"123456")',
337         "query of specific field including period and quoted is not truncated, field name is converted to lower case"
338     );
339
340     ( undef, $query ) = $qb->build_query_compat( undef, ['J.R.R'] );
341     is(
342         $query->{query}{query_string}{query},
343         '(J.R.R*)',
344         "query including period is truncated but not split at periods"
345     );
346
347     ( undef, $query ) = $qb->build_query_compat( undef, ['title:"donald duck"'] );
348     is(
349         $query->{query}{query_string}{query},
350         '(title:"donald duck")',
351         "query of specific field is not truncated when surrounded by quotes"
352     );
353
354     ( undef, $query ) = $qb->build_query_compat( undef, ['donald duck'], ['title'] );
355     is(
356         $query->{query}{query_string}{query},
357         '(title:(donald* duck*))',
358         'words of a multi-word term are properly truncated'
359     );
360
361     ( undef, $query ) = $qb->build_query_compat( ['AND'], ['donald duck', 'disney'], ['title', 'author'] );
362     is(
363         $query->{query}{query_string}{query},
364         '(title:(donald* duck*)) AND (author:disney*)',
365         'words of a multi-word term and single-word term are properly truncated'
366     );
367
368     ( undef, $query ) = $qb->build_query_compat( undef, ['title:"donald duck"'], undef, undef, undef, undef, undef, { suppress => 1 } );
369     is(
370         $query->{query}{query_string}{query},
371         '(title:"donald duck") AND suppress:0',
372         "query of specific field is added AND suppress:0"
373     );
374
375     ( undef, $query, $simple_query, $query_cgi, $query_desc ) = $qb->build_query_compat( undef, ['title:"donald duck"'], undef, undef, undef, undef, undef, { suppress => 0 } );
376     is(
377         $query->{query}{query_string}{query},
378         '(title:"donald duck")',
379         "query of specific field is not added AND suppress:0"
380     );
381     is($query_cgi, 'idx=&q=title%3A%22donald%20duck%22', 'query cgi');
382     is($query_desc, 'title:"donald duck"', 'query desc ok');
383 };
384
385
386 subtest 'build query from form subtests' => sub {
387     plan tests => 5;
388
389     my $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new({ 'index' => 'authorities' }),
390     #when searching for authorities from a record the form returns marclist with blanks for unentered terms
391     my @marclist = ('mainmainentry','mainentry','match', 'all');
392     my @values   = ( undef,         'Hamilton',  undef,   undef);
393     my @operator = ( 'contains', 'contains', 'contains', 'contains');
394
395     my $query = $qb->build_authorities_query_compat( \@marclist, undef,
396                     undef, \@operator , \@values, 'AUTH_TYPE', 'asc' );
397     is($query->{query}->{bool}->{must}[0]->{query_string}->{query}, "Hamilton*","Expected search is populated");
398     is( scalar @{ $query->{query}->{bool}->{must} }, 1,"Only defined search is populated");
399
400     @values[2] = 'Jefferson';
401     $query = $qb->build_authorities_query_compat( \@marclist, undef,
402                     undef, \@operator , \@values, 'AUTH_TYPE', 'asc' );
403     is($query->{query}->{bool}->{must}[0]->{query_string}->{query}, "Hamilton*","First index searched as expected");
404     is($query->{query}->{bool}->{must}[1]->{query_string}->{query}, "Jefferson*","Second index searched when populated");
405     is( scalar @{ $query->{query}->{bool}->{must} }, 2,"Only defined searches are populated");
406
407
408 };
409
410 subtest 'build_query with weighted fields tests' => sub {
411     plan tests => 4;
412
413     my $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new( { index => 'mydb' } );
414     my $db_builder = t::lib::TestBuilder->new();
415
416     Koha::SearchFields->search({})->delete;
417
418     $db_builder->build({
419         source => 'SearchField',
420         value => {
421             name    => 'acqdate',
422             label   => 'acqdate',
423             weight  => undef
424         }
425     });
426
427     $db_builder->build({
428         source => 'SearchField',
429         value => {
430             name    => 'title',
431             label   => 'title',
432             weight  => 25
433         }
434     });
435
436     $db_builder->build({
437         source => 'SearchField',
438         value => {
439             name    => 'subject',
440             label   => 'subject',
441             weight  => 15
442         }
443     });
444
445     my ( undef, $query ) = $qb->build_query_compat( undef, ['title:"donald duck"'], undef, undef,
446     undef, undef, undef, { weighted_fields => 1 });
447
448     my $fields = $query->{query}{query_string}{fields};
449     is(scalar(@$fields), 3, 'Search is done on 3 fields');
450     is($fields->[0], '_all', 'First search field is _all');
451     is($fields->[1], 'title^25.00', 'Second search field is title');
452     is($fields->[2], 'subject^15.00', 'Third search field is subject');
453 };
454
455 subtest "_convert_sort_fields() tests" => sub {
456     plan tests => 3;
457
458     my $qb;
459
460     ok(
461         $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new({ 'index' => 'biblios' }),
462         'Creating new query builder object for biblios'
463     );
464
465     my @sort_by = $qb->_convert_sort_fields(qw( call_number_asc author_dsc ));
466     is_deeply(
467         \@sort_by,
468         [
469             { field => 'local-classification', direction => 'asc' },
470             { field => 'author',  direction => 'desc' }
471         ],
472         'sort fields should have been split correctly'
473     );
474
475     # We could expect this to pass, but direction is undef instead of 'desc'
476     @sort_by = $qb->_convert_sort_fields(qw( call_number_asc author_desc ));
477     is_deeply(
478         \@sort_by,
479         [
480             { field => 'local-classification', direction => 'asc' },
481             { field => 'author',  direction => 'desc' }
482         ],
483         'sort fields should have been split correctly'
484     );
485 };
486
487 subtest "_sort_field() tests" => sub {
488     plan tests => 5;
489
490     my $qb;
491
492     ok(
493         $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new({ 'index' => 'biblios' }),
494         'Creating new query builder object for biblios'
495     );
496
497     my $f = $qb->_sort_field('title');
498     is(
499         $f,
500         'title__sort.phrase',
501         'title sort mapped correctly'
502     );
503
504     $f = $qb->_sort_field('subject');
505     is(
506         $f,
507         'subject.raw',
508         'subject sort mapped correctly'
509     );
510
511     $f = $qb->_sort_field('itemnumber');
512     is(
513         $f,
514         'itemnumber',
515         'itemnumber sort mapped correctly'
516     );
517
518     $f = $qb->_sort_field('sortablenumber');
519     is(
520         $f,
521         'sortablenumber__sort',
522         'sortablenumber sort mapped correctly'
523     );
524 };
525
526 $schema->storage->txn_rollback;