]> git.koha-community.org Git - koha.git/blob - t/db_dependent/Koha/SearchEngine/Elasticsearch/QueryBuilder.t
Bug 23089: Fix QueryBuilder tests.
[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 => 45;
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         is( $query->{query}->{bool}->{must}[0]->{query_string}->{analyze_wildcard}, JSON::true, 'Set analyze_wildcard true' );
106     }
107
108     $search_term = 'Donald Duck';
109     foreach my $koha_name ( keys %{ $koha_to_index_name } ) {
110         my $query = $qb->build_authorities_query_compat( [ $koha_name ],  undef, undef, ['contains'], [$search_term], 'AUTH_TYPE', 'asc' );
111         if ( $koha_name eq 'all' || $koha_name eq 'any' ) {
112             is( $query->{query}->{bool}->{must}[0]->{query_string}->{query},
113                 "(Donald*) AND (Duck*)");
114         } else {
115             is( $query->{query}->{bool}->{must}[0]->{query_string}->{query},
116                 "(Donald*) AND (Duck*)");
117         }
118     }
119
120     foreach my $koha_name ( keys %{ $koha_to_index_name } ) {
121         my $query = $qb->build_authorities_query_compat( [ $koha_name ],  undef, undef, ['is'], [$search_term], 'AUTH_TYPE', 'asc' );
122         if ( $koha_name eq 'all' || $koha_name eq 'any' ) {
123             is( $query->{query}->{bool}->{must}[0]->{match_phrase}->{"_all.phrase"},
124                 "donald duck");
125         } else {
126             is( $query->{query}->{bool}->{must}[0]->{match_phrase}->{$koha_to_index_name->{$koha_name}.".phrase"},
127                 "donald duck");
128         }
129     }
130
131     foreach my $koha_name ( keys %{ $koha_to_index_name } ) {
132         my $query = $qb->build_authorities_query_compat( [ $koha_name ],  undef, undef, ['start'], [$search_term], 'AUTH_TYPE', 'asc' );
133         if ( $koha_name eq 'all' || $koha_name eq 'any' ) {
134             is( $query->{query}->{bool}->{must}[0]->{match_phrase_prefix}->{"_all.phrase"},
135                 "donald duck");
136         } else {
137             is( $query->{query}->{bool}->{must}[0]->{match_phrase_prefix}->{$koha_to_index_name->{$koha_name}.".phrase"},
138                 "donald duck");
139         }
140     }
141
142     # Sorting
143     my $query = $qb->build_authorities_query_compat( [ 'mainentry' ],  undef, undef, ['start'], [$search_term], 'AUTH_TYPE', 'HeadingAsc' );
144     is_deeply(
145         $query->{sort},
146         [
147             {
148                 'heading__sort' => 'asc'
149             }
150         ],
151         "ascending sort parameter properly formed"
152     );
153     $query = $qb->build_authorities_query_compat( [ 'mainentry' ],  undef, undef, ['start'], [$search_term], 'AUTH_TYPE', 'HeadingDsc' );
154     is_deeply(
155         $query->{sort},
156         [
157             {
158                 'heading__sort' => 'desc'
159             }
160         ],
161         "descending sort parameter properly formed"
162     );
163
164     # Authorities type
165     $query = $qb->build_authorities_query_compat( [ 'mainentry' ],  undef, undef, ['contains'], [$search_term], 'AUTH_TYPE', 'asc' );
166     is_deeply(
167         $query->{query}->{bool}->{filter},
168         { term => { 'authtype' => 'auth_type' } },
169         "authorities type code is used as filter"
170     );
171
172     # Failing case
173     throws_ok {
174         $qb->build_authorities_query_compat( [ 'tomas' ],  undef, undef, ['contains'], [$search_term], 'AUTH_TYPE', 'asc' );
175     }
176     'Koha::Exceptions::WrongParameter',
177         'Exception thrown on invalid value in the marclist param';
178 };
179
180 subtest 'build_query tests' => sub {
181     plan tests => 38;
182
183     my $qb;
184
185     ok(
186         $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new({ 'index' => 'biblios' }),
187         'Creating new query builder object for biblios'
188     );
189
190     my @sort_by = 'title_asc';
191     my @sort_params = $qb->_convert_sort_fields(@sort_by);
192     my %options;
193     $options{sort} = \@sort_params;
194     my $query = $qb->build_query('test', %options);
195
196     is_deeply(
197         $query->{sort},
198         [
199             {
200             'title__sort' => {
201                     'order' => 'asc'
202                 }
203             }
204         ],
205         "sort parameter properly formed"
206     );
207
208     t::lib::Mocks::mock_preference('DisplayLibraryFacets','both');
209     $query = $qb->build_query();
210     ok( defined $query->{aggregations}{homebranch},
211         'homebranch added to facets if DisplayLibraryFacets=both' );
212     ok( defined $query->{aggregations}{holdingbranch},
213         'holdingbranch added to facets if DisplayLibraryFacets=both' );
214     t::lib::Mocks::mock_preference('DisplayLibraryFacets','holding');
215     $query = $qb->build_query();
216     ok( !defined $query->{aggregations}{homebranch},
217         'homebranch not added to facets if DisplayLibraryFacets=holding' );
218     ok( defined $query->{aggregations}{holdingbranch},
219         'holdingbranch added to facets if DisplayLibraryFacets=holding' );
220     t::lib::Mocks::mock_preference('DisplayLibraryFacets','home');
221     $query = $qb->build_query();
222     ok( defined $query->{aggregations}{homebranch},
223         'homebranch added to facets if DisplayLibraryFacets=home' );
224     ok( !defined $query->{aggregations}{holdingbranch},
225         'holdingbranch not added to facets if DisplayLibraryFacets=home' );
226
227     t::lib::Mocks::mock_preference( 'QueryAutoTruncate', '' );
228
229     ( undef, $query ) = $qb->build_query_compat( undef, ['donald duck'] );
230     is(
231         $query->{query}{query_string}{query},
232         "(donald duck)",
233         "query not altered if QueryAutoTruncate disabled"
234     );
235
236     ( undef, $query ) = $qb->build_query_compat( undef, ['donald duck'], ['title'] );
237     is(
238         $query->{query}{query_string}{query},
239         '(title:(donald duck))',
240         'multiple words in a query term are enclosed in parenthesis'
241     );
242
243     ( undef, $query ) = $qb->build_query_compat( ['AND'], ['donald duck', 'disney'], ['title', 'author'] );
244     is(
245         $query->{query}{query_string}{query},
246         '(title:(donald duck)) AND (author:disney)',
247         'multiple query terms are enclosed in parenthesis while a single one is not'
248     );
249
250     my ($simple_query, $query_cgi, $query_desc);
251     ( undef, $query, $simple_query, $query_cgi, $query_desc ) = $qb->build_query_compat( undef, ['"donald duck"', 'walt disney'], ['ti', 'au'] );
252     is($query_cgi, 'idx=ti&q=%22donald%20duck%22&idx=au&q=walt%20disney', 'query cgi ok for multiterm query');
253     is($query_desc, '(title:("donald duck")) (author:(walt disney))', 'query desc ok for multiterm query');
254
255     ( undef, $query ) = $qb->build_query_compat( undef, ['2019'], ['yr,st-year'] );
256     is(
257         $query->{query}{query_string}{query},
258         '(date-of-publication:2019)',
259         'Year in an st-year search is handled properly'
260     );
261
262     ( undef, $query ) = $qb->build_query_compat( undef, ['2018-2019'], ['yr,st-year'] );
263     is(
264         $query->{query}{query_string}{query},
265         '(date-of-publication:[2018 TO 2019])',
266         'Year range in an st-year search is handled properly'
267     );
268
269     ( undef, $query ) = $qb->build_query_compat( undef, ['-2019'], ['yr,st-year'] );
270     is(
271         $query->{query}{query_string}{query},
272         '(date-of-publication:[* TO 2019])',
273         'Open start year in year range of an st-year search is handled properly'
274     );
275
276     ( undef, $query ) = $qb->build_query_compat( undef, ['2019-'], ['yr,st-year'] );
277     is(
278         $query->{query}{query_string}{query},
279         '(date-of-publication:[2019 TO *])',
280         'Open end year in year range of an st-year search is handled properly'
281     );
282
283     ( undef, $query ) = $qb->build_query_compat( undef, ['2019-'], ['yr,st-year'], ['yr,st-numeric=-2019'] );
284     is(
285         $query->{query}{query_string}{query},
286         '(date-of-publication:[2019 TO *]) AND copydate:[* TO 2019]',
287         'Open end year in year range of an st-year search is handled properly'
288     );
289
290     # Enable auto-truncation
291     t::lib::Mocks::mock_preference( 'QueryAutoTruncate', '1' );
292
293     ( undef, $query ) = $qb->build_query_compat( undef, ['donald duck'] );
294     is(
295         $query->{query}{query_string}{query},
296         "(donald* duck*)",
297         "simple query is auto truncated when QueryAutoTruncate enabled"
298     );
299
300     # Ensure reserved words are not truncated
301     ( undef, $query ) = $qb->build_query_compat( undef,
302         ['donald or duck and mickey not mouse'] );
303     is(
304         $query->{query}{query_string}{query},
305         "(donald* or duck* and mickey* not mouse*)",
306         "reserved words are not affected by QueryAutoTruncate"
307     );
308
309     ( undef, $query ) = $qb->build_query_compat( undef, ['donald* duck*'] );
310     is(
311         $query->{query}{query_string}{query},
312         "(donald* duck*)",
313         "query with '*' is unaltered when QueryAutoTruncate is enabled"
314     );
315
316     ( undef, $query ) = $qb->build_query_compat( undef, ['donald duck and the mouse'] );
317     is(
318         $query->{query}{query_string}{query},
319         "(donald* duck* and the* mouse*)",
320         "individual words are all truncated and stopwords ignored"
321     );
322
323     ( undef, $query ) = $qb->build_query_compat( undef, ['*'] );
324     is(
325         $query->{query}{query_string}{query},
326         "(*)",
327         "query of just '*' is unaltered when QueryAutoTruncate is enabled"
328     );
329
330     ( undef, $query ) = $qb->build_query_compat( undef, ['"donald duck"'] );
331     is(
332         $query->{query}{query_string}{query},
333         '("donald duck")',
334         "query with quotes is unaltered when QueryAutoTruncate is enabled"
335     );
336
337
338     ( undef, $query ) = $qb->build_query_compat( undef, ['"donald duck" and "the mouse"'] );
339     is(
340         $query->{query}{query_string}{query},
341         '("donald duck" and "the mouse")',
342         "all quoted strings are unaltered if more than one in query"
343     );
344
345     ( undef, $query ) = $qb->build_query_compat( undef, ['barcode:123456'] );
346     is(
347         $query->{query}{query_string}{query},
348         '(barcode:123456*)',
349         "query of specific field is truncated"
350     );
351
352     ( undef, $query ) = $qb->build_query_compat( undef, ['Local-number:"123456"'] );
353     is(
354         $query->{query}{query_string}{query},
355         '(local-number:"123456")',
356         "query of specific field including hyphen and quoted is not truncated, field name is converted to lower case"
357     );
358
359     ( undef, $query ) = $qb->build_query_compat( undef, ['Local-number:123456'] );
360     is(
361         $query->{query}{query_string}{query},
362         '(local-number:123456*)',
363         "query of specific field including hyphen and not quoted is truncated, field name is converted to lower case"
364     );
365
366     ( undef, $query ) = $qb->build_query_compat( undef, ['Local-number.raw:123456'] );
367     is(
368         $query->{query}{query_string}{query},
369         '(local-number.raw:123456*)',
370         "query of specific field including period and not quoted is truncated, field name is converted to lower case"
371     );
372
373     ( undef, $query ) = $qb->build_query_compat( undef, ['Local-number.raw:"123456"'] );
374     is(
375         $query->{query}{query_string}{query},
376         '(local-number.raw:"123456")',
377         "query of specific field including period and quoted is not truncated, field name is converted to lower case"
378     );
379
380     ( undef, $query ) = $qb->build_query_compat( undef, ['J.R.R'] );
381     is(
382         $query->{query}{query_string}{query},
383         '(J.R.R*)',
384         "query including period is truncated but not split at periods"
385     );
386
387     ( undef, $query ) = $qb->build_query_compat( undef, ['title:"donald duck"'] );
388     is(
389         $query->{query}{query_string}{query},
390         '(title:"donald duck")',
391         "query of specific field is not truncated when surrounded by quotes"
392     );
393
394     ( undef, $query ) = $qb->build_query_compat( undef, ['donald duck'], ['title'] );
395     is(
396         $query->{query}{query_string}{query},
397         '(title:(donald* duck*))',
398         'words of a multi-word term are properly truncated'
399     );
400
401     ( undef, $query ) = $qb->build_query_compat( ['AND'], ['donald duck', 'disney'], ['title', 'author'] );
402     is(
403         $query->{query}{query_string}{query},
404         '(title:(donald* duck*)) AND (author:disney*)',
405         'words of a multi-word term and single-word term are properly truncated'
406     );
407
408     ( undef, $query ) = $qb->build_query_compat( undef, ['title:"donald duck"'], undef, undef, undef, undef, undef, { suppress => 1 } );
409     is(
410         $query->{query}{query_string}{query},
411         '(title:"donald duck") AND suppress:0',
412         "query of specific field is added AND suppress:0"
413     );
414
415     ( undef, $query, $simple_query, $query_cgi, $query_desc ) = $qb->build_query_compat( undef, ['title:"donald duck"'], undef, undef, undef, undef, undef, { suppress => 0 } );
416     is(
417         $query->{query}{query_string}{query},
418         '(title:"donald duck")',
419         "query of specific field is not added AND suppress:0"
420     );
421     is($query_cgi, 'idx=&q=title%3A%22donald%20duck%22', 'query cgi');
422     is($query_desc, 'title:"donald duck"', 'query desc ok');
423 };
424
425
426 subtest 'build query from form subtests' => sub {
427     plan tests => 5;
428
429     my $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new({ 'index' => 'authorities' }),
430     #when searching for authorities from a record the form returns marclist with blanks for unentered terms
431     my @marclist = ('mainmainentry','mainentry','match', 'all');
432     my @values   = ( undef,         'Hamilton',  undef,   undef);
433     my @operator = ( 'contains', 'contains', 'contains', 'contains');
434
435     my $query = $qb->build_authorities_query_compat( \@marclist, undef,
436                     undef, \@operator , \@values, 'AUTH_TYPE', 'asc' );
437     is($query->{query}->{bool}->{must}[0]->{query_string}->{query}, "Hamilton*","Expected search is populated");
438     is( scalar @{ $query->{query}->{bool}->{must} }, 1,"Only defined search is populated");
439
440     @values[2] = 'Jefferson';
441     $query = $qb->build_authorities_query_compat( \@marclist, undef,
442                     undef, \@operator , \@values, 'AUTH_TYPE', 'asc' );
443     is($query->{query}->{bool}->{must}[0]->{query_string}->{query}, "Hamilton*","First index searched as expected");
444     is($query->{query}->{bool}->{must}[1]->{query_string}->{query}, "Jefferson*","Second index searched when populated");
445     is( scalar @{ $query->{query}->{bool}->{must} }, 2,"Only defined searches are populated");
446
447
448 };
449
450 subtest 'build_query with weighted fields tests' => sub {
451     plan tests => 4;
452
453     my $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new( { index => 'mydb' } );
454     my $db_builder = t::lib::TestBuilder->new();
455
456     Koha::SearchFields->search({})->delete;
457
458     $db_builder->build({
459         source => 'SearchField',
460         value => {
461             name    => 'acqdate',
462             label   => 'acqdate',
463             weight  => undef
464         }
465     });
466
467     $db_builder->build({
468         source => 'SearchField',
469         value => {
470             name    => 'title',
471             label   => 'title',
472             weight  => 25
473         }
474     });
475
476     $db_builder->build({
477         source => 'SearchField',
478         value => {
479             name    => 'subject',
480             label   => 'subject',
481             weight  => 15
482         }
483     });
484
485     my ( undef, $query ) = $qb->build_query_compat( undef, ['title:"donald duck"'], undef, undef,
486     undef, undef, undef, { weighted_fields => 1 });
487
488     my $fields = $query->{query}{query_string}{fields};
489     is(scalar(@$fields), 3, 'Search is done on 3 fields');
490     is($fields->[0], '_all', 'First search field is _all');
491     is($fields->[1], 'title^25.00', 'Second search field is title');
492     is($fields->[2], 'subject^15.00', 'Third search field is subject');
493 };
494
495 subtest "_convert_sort_fields() tests" => sub {
496     plan tests => 3;
497
498     my $qb;
499
500     ok(
501         $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new({ 'index' => 'biblios' }),
502         'Creating new query builder object for biblios'
503     );
504
505     my @sort_by = $qb->_convert_sort_fields(qw( call_number_asc author_dsc ));
506     is_deeply(
507         \@sort_by,
508         [
509             { field => 'local-classification', direction => 'asc' },
510             { field => 'author',  direction => 'desc' }
511         ],
512         'sort fields should have been split correctly'
513     );
514
515     # We could expect this to pass, but direction is undef instead of 'desc'
516     @sort_by = $qb->_convert_sort_fields(qw( call_number_asc author_desc ));
517     is_deeply(
518         \@sort_by,
519         [
520             { field => 'local-classification', direction => 'asc' },
521             { field => 'author',  direction => 'desc' }
522         ],
523         'sort fields should have been split correctly'
524     );
525 };
526
527 subtest "_sort_field() tests" => sub {
528     plan tests => 5;
529
530     my $qb;
531
532     ok(
533         $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new({ 'index' => 'biblios' }),
534         'Creating new query builder object for biblios'
535     );
536
537     my $f = $qb->_sort_field('title');
538     is(
539         $f,
540         'title__sort',
541         'title sort mapped correctly'
542     );
543
544     $f = $qb->_sort_field('subject');
545     is(
546         $f,
547         'subject.raw',
548         'subject sort mapped correctly'
549     );
550
551     $f = $qb->_sort_field('itemnumber');
552     is(
553         $f,
554         'itemnumber',
555         'itemnumber sort mapped correctly'
556     );
557
558     $f = $qb->_sort_field('sortablenumber');
559     is(
560         $f,
561         'sortablenumber__sort',
562         'sortablenumber sort mapped correctly'
563     );
564 };
565
566 $schema->storage->txn_rollback;