3 # Copyright (C) 2007 LibLime, 2012 C & P Bibliography Services
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
26 use Koha
::SearchEngine
;
27 use Koha
::SearchEngine
::Search
;
31 C4::Matcher - find MARC records matching another one
35 my @matchers = C4::Matcher::GetMatcherList();
37 my $matcher = C4::Matcher->new($record_type);
38 $matcher->threshold($threshold);
39 $matcher->code($code);
40 $matcher->description($description);
42 $matcher->add_simple_matchpoint('isbn', 1000, '020', 'a', -1, 0, '');
43 $matcher->add_simple_matchpoint('Date', 1000, '008', '', 7, 4, '');
44 $matcher->add_matchpoint('isbn', 1000, [ { tag => '020', subfields => 'a', norms => [] } ]);
46 $matcher->add_simple_required_check('245', 'a', -1, 0, '', '245', 'a', -1, 0, '');
47 $matcher->add_required_check([ { tag => '245', subfields => 'a', norms => [] } ],
48 [ { tag => '245', subfields => 'a', norms => [] } ]);
50 my @matches = $matcher->get_matches($marc_record, $max_matches);
52 foreach $match (@matches) {
54 # matches already sorted in order of
56 print "record ID: $match->{'record_id'};
57 print "score: $match->{'score'};
61 my $matcher_description = $matcher->dump();
69 my @matchers = C4::Matcher::GetMatcherList();
71 Returns an array of hashrefs list all matchers
72 present in the database. Each hashref includes:
81 my $dbh = C4
::Context
->dbh;
83 my $sth = $dbh->prepare_cached("SELECT matcher_id, code, description FROM marc_matchers ORDER BY matcher_id");
86 while (my $row = $sth->fetchrow_hashref) {
94 my $matcher_id = C4::Matcher::GetMatcherId($code);
96 Returns the matcher_id of a code.
102 my $dbh = C4
::Context
->dbh;
104 my $matcher_id = $dbh->selectrow_array("SELECT matcher_id FROM marc_matchers WHERE code = ?", undef, $code);
112 my $matcher = C4::Matcher->new($record_type, $threshold);
114 Creates a new Matcher. C<$record_type> indicates which search
115 database to use, e.g., 'biblio' or 'authority' and defaults to
116 'biblio', while C<$threshold> is the minimum score required for a match
117 and defaults to 1000.
125 $self->{'id'} = undef;
128 $self->{'record_type'} = shift;
130 $self->{'record_type'} = 'biblio';
134 $self->{'threshold'} = shift;
136 $self->{'threshold'} = 1000;
139 $self->{'code'} = '';
140 $self->{'description'} = '';
142 $self->{'matchpoints'} = [];
143 $self->{'required_checks'} = [];
151 my $matcher = C4::Matcher->fetch($id);
153 Creates a matcher object from the version stored
154 in the database. If a matcher with the given
155 id does not exist, returns undef.
162 my $dbh = C4
::Context
->dbh();
164 my $sth = $dbh->prepare_cached("SELECT * FROM marc_matchers WHERE matcher_id = ?");
166 my $row = $sth->fetchrow_hashref;
168 return undef unless defined $row;
171 $self->{'id'} = $row->{'matcher_id'};
172 $self->{'record_type'} = $row->{'record_type'};
173 $self->{'code'} = $row->{'code'};
174 $self->{'description'} = $row->{'description'};
175 $self->{'threshold'} = int($row->{'threshold'});
179 $self->{'matchpoints'} = [];
180 $sth = $dbh->prepare_cached("SELECT * FROM matcher_matchpoints WHERE matcher_id = ? ORDER BY matchpoint_id");
181 $sth->execute($self->{'id'});
182 while (my $row = $sth->fetchrow_hashref) {
183 my $matchpoint = $self->_fetch_matchpoint($row->{'matchpoint_id'});
184 push @
{ $self->{'matchpoints'} }, $matchpoint;
188 $self->{'required_checks'} = [];
189 $sth = $dbh->prepare_cached("SELECT * FROM matchchecks WHERE matcher_id = ? ORDER BY matchcheck_id");
190 $sth->execute($self->{'id'});
191 while (my $row = $sth->fetchrow_hashref) {
192 my $source_matchpoint = $self->_fetch_matchpoint($row->{'source_matchpoint_id'});
193 my $target_matchpoint = $self->_fetch_matchpoint($row->{'target_matchpoint_id'});
195 $matchcheck->{'source_matchpoint'} = $source_matchpoint;
196 $matchcheck->{'target_matchpoint'} = $target_matchpoint;
197 push @
{ $self->{'required_checks'} }, $matchcheck;
203 sub _fetch_matchpoint
{
205 my $matchpoint_id = shift;
207 my $dbh = C4
::Context
->dbh;
208 my $sth = $dbh->prepare_cached("SELECT * FROM matchpoints WHERE matchpoint_id = ?");
209 $sth->execute($matchpoint_id);
210 my $row = $sth->fetchrow_hashref;
212 $matchpoint->{'index'} = $row->{'search_index'};
213 $matchpoint->{'score'} = int($row->{'score'});
216 $matchpoint->{'components'} = [];
217 $sth = $dbh->prepare_cached("SELECT * FROM matchpoint_components WHERE matchpoint_id = ? ORDER BY sequence");
218 $sth->execute($matchpoint_id);
219 while ($row = $sth->fetchrow_hashref) {
221 $component->{'tag'} = $row->{'tag'};
222 $component->{'subfields'} = { map { $_ => 1 } split(//, $row->{'subfields'}) };
223 $component->{'offset'} = int($row->{'offset'});
224 $component->{'length'} = int($row->{'length'});
225 $component->{'norms'} = [];
226 my $sth2 = $dbh->prepare_cached("SELECT *
227 FROM matchpoint_component_norms
228 WHERE matchpoint_component_id = ? ORDER BY sequence");
229 $sth2->execute($row->{'matchpoint_component_id'});
230 while (my $row2 = $sth2->fetchrow_hashref) {
231 push @
{ $component->{'norms'} }, $row2->{'norm_routine'};
233 push @
{ $matchpoint->{'components'} }, $component;
240 my $id = $matcher->store();
242 Stores matcher in database. The return value is the ID
243 of the marc_matchers row. If the matcher was
244 previously retrieved from the database via the fetch()
245 method, the DB representation of the matcher
253 if (defined $self->{'id'}) {
255 $self->_del_matcher_components();
256 $self->_update_marc_matchers();
259 $self->_new_marc_matchers();
261 $self->_store_matcher_components();
262 return $self->{'id'};
265 sub _del_matcher_components
{
268 my $dbh = C4
::Context
->dbh();
269 my $sth = $dbh->prepare_cached("DELETE FROM matchpoints WHERE matcher_id = ?");
270 $sth->execute($self->{'id'});
271 $sth = $dbh->prepare_cached("DELETE FROM matchchecks WHERE matcher_id = ?");
272 $sth->execute($self->{'id'});
273 # foreign key delete cascades take care of deleting relevant rows
274 # from matcher_matchpoints, matchpoint_components, and
275 # matchpoint_component_norms
278 sub _update_marc_matchers
{
281 my $dbh = C4
::Context
->dbh();
282 my $sth = $dbh->prepare_cached("UPDATE marc_matchers
287 WHERE matcher_id = ?");
288 $sth->execute($self->{'code'}, $self->{'description'}, $self->{'record_type'}, $self->{'threshold'}, $self->{'id'});
291 sub _new_marc_matchers
{
294 my $dbh = C4
::Context
->dbh();
295 my $sth = $dbh->prepare_cached("INSERT INTO marc_matchers
296 (code, description, record_type, threshold)
297 VALUES (?, ?, ?, ?)");
298 $sth->execute($self->{'code'}, $self->{'description'}, $self->{'record_type'}, $self->{'threshold'});
299 $self->{'id'} = $dbh->{'mysql_insertid'};
302 sub _store_matcher_components
{
305 my $dbh = C4
::Context
->dbh();
307 my $matcher_id = $self->{'id'};
308 foreach my $matchpoint (@
{ $self->{'matchpoints'}}) {
309 my $matchpoint_id = $self->_store_matchpoint($matchpoint);
310 $sth = $dbh->prepare_cached("INSERT INTO matcher_matchpoints (matcher_id, matchpoint_id)
312 $sth->execute($matcher_id, $matchpoint_id);
314 foreach my $matchcheck (@
{ $self->{'required_checks'} }) {
315 my $source_matchpoint_id = $self->_store_matchpoint($matchcheck->{'source_matchpoint'});
316 my $target_matchpoint_id = $self->_store_matchpoint($matchcheck->{'target_matchpoint'});
317 $sth = $dbh->prepare_cached("INSERT INTO matchchecks
318 (matcher_id, source_matchpoint_id, target_matchpoint_id)
320 $sth->execute($matcher_id, $source_matchpoint_id, $target_matchpoint_id);
325 sub _store_matchpoint
{
327 my $matchpoint = shift;
329 my $dbh = C4
::Context
->dbh();
331 my $matcher_id = $self->{'id'};
332 $sth = $dbh->prepare_cached("INSERT INTO matchpoints (matcher_id, search_index, score)
334 $sth->execute($matcher_id, $matchpoint->{'index'}, $matchpoint->{'score'});
335 my $matchpoint_id = $dbh->{'mysql_insertid'};
337 foreach my $component (@
{ $matchpoint->{'components'} }) {
339 $sth = $dbh->prepare_cached("INSERT INTO matchpoint_components
340 (matchpoint_id, sequence, tag, subfields, offset, length)
341 VALUES (?, ?, ?, ?, ?, ?)");
342 $sth->bind_param(1, $matchpoint_id);
343 $sth->bind_param(2, $seqnum);
344 $sth->bind_param(3, $component->{'tag'});
345 $sth->bind_param(4, join "", sort keys %{ $component->{'subfields'} });
346 $sth->bind_param(5, $component->{'offset'});
347 $sth->bind_param(6, $component->{'length'});
349 my $matchpoint_component_id = $dbh->{'mysql_insertid'};
351 foreach my $norm (@
{ $component->{'norms'} }) {
353 $sth = $dbh->prepare_cached("INSERT INTO matchpoint_component_norms
354 (matchpoint_component_id, sequence, norm_routine)
356 $sth->execute($matchpoint_component_id, $normseq, $norm);
359 return $matchpoint_id;
365 C4::Matcher->delete($id);
367 Deletes the matcher of the specified ID
374 my $matcher_id = shift;
376 my $dbh = C4
::Context
->dbh;
377 my $sth = $dbh->prepare("DELETE FROM marc_matchers WHERE matcher_id = ?");
378 $sth->execute($matcher_id); # relying on cascading deletes to clean up everything
383 $matcher->record_type('biblio');
384 my $record_type = $matcher->record_type();
392 @_ ?
$self->{'record_type'} = shift : $self->{'record_type'};
397 $matcher->threshold(1000);
398 my $threshold = $matcher->threshold();
406 @_ ?
$self->{'threshold'} = shift : $self->{'threshold'};
412 my $id = $matcher->_id();
414 Accessor method. Note that using this method
415 to set the DB ID of the matcher should not be
416 done outside of the editing CGI.
422 @_ ?
$self->{'id'} = shift : $self->{'id'};
427 $matcher->code('ISBN');
428 my $code = $matcher->code();
436 @_ ?
$self->{'code'} = shift : $self->{'code'};
441 $matcher->description('match on ISBN');
442 my $description = $matcher->description();
450 @_ ?
$self->{'description'} = shift : $self->{'description'};
453 =head2 add_matchpoint
455 $matcher->add_matchpoint($index, $score, $matchcomponents);
457 Adds a matchpoint that may include multiple components. The $index
458 parameter identifies the index that will be searched, while $score
459 is the weight that will be added if a match is found.
461 $matchcomponents should be a reference to an array of matchpoint
462 compoents, each of which should be a hash containing the following
470 The normalization_rules value should in turn be a reference to an
471 array, each element of which should be a reference to a
472 normalization subroutine (under C4::Normalize) to be applied
473 to the source string.
479 my ($index, $score, $matchcomponents) = @_;
482 $matchpoint->{'index'} = $index;
483 $matchpoint->{'score'} = $score;
484 $matchpoint->{'components'} = [];
485 foreach my $input_component (@
{ $matchcomponents }) {
486 push @
{ $matchpoint->{'components'} }, _parse_match_component
($input_component);
488 push @
{ $self->{'matchpoints'} }, $matchpoint;
491 =head2 add_simple_matchpoint
493 $matcher->add_simple_matchpoint($index, $score, $source_tag,
494 $source_subfields, $source_offset,
495 $source_length, $source_normalizer);
498 Adds a simple matchpoint rule -- after composing a key based on the source tag and subfields,
499 normalized per the normalization fuction, search the index. All records retrieved
500 will receive the assigned score.
504 sub add_simple_matchpoint
{
506 my ($index, $score, $source_tag, $source_subfields, $source_offset, $source_length, $source_normalizer) = @_;
508 $self->add_matchpoint($index, $score, [
509 { tag
=> $source_tag, subfields
=> $source_subfields,
510 offset
=> $source_offset, 'length' => $source_length,
511 norms
=> [ $source_normalizer ]
516 =head2 add_required_check
518 $match->add_required_check($source_matchpoint, $target_matchpoint);
520 Adds a required check definition. A required check means that in
521 order for a match to be considered valid, the key derived from the
522 source (incoming) record must match the key derived from the target
523 (already in DB) record.
525 Unlike a regular matchpoint, only the first repeat of each tag
526 in the source and target match criteria are considered.
528 A typical example of a required check would be verifying that the
529 titles and publication dates match.
531 $source_matchpoint and $target_matchpoint are each a reference to
532 an array of hashes, where each hash follows the same definition
533 as the matchpoint component specification in add_matchpoint, i.e.,
541 The normalization_rules value should in turn be a reference to an
542 array, each element of which should be a reference to a
543 normalization subroutine (under C4::Normalize) to be applied
544 to the source string.
548 sub add_required_check
{
550 my ($source_matchpoint, $target_matchpoint) = @_;
553 $matchcheck->{'source_matchpoint'}->{'index'} = '';
554 $matchcheck->{'source_matchpoint'}->{'score'} = 0;
555 $matchcheck->{'source_matchpoint'}->{'components'} = [];
556 $matchcheck->{'target_matchpoint'}->{'index'} = '';
557 $matchcheck->{'target_matchpoint'}->{'score'} = 0;
558 $matchcheck->{'target_matchpoint'}->{'components'} = [];
559 foreach my $input_component (@
{ $source_matchpoint }) {
560 push @
{ $matchcheck->{'source_matchpoint'}->{'components'} }, _parse_match_component
($input_component);
562 foreach my $input_component (@
{ $target_matchpoint }) {
563 push @
{ $matchcheck->{'target_matchpoint'}->{'components'} }, _parse_match_component
($input_component);
565 push @
{ $self->{'required_checks'} }, $matchcheck;
568 =head2 add_simple_required_check
570 $matcher->add_simple_required_check($source_tag, $source_subfields,
571 $source_offset, $source_length, $source_normalizer,
572 $target_tag, $target_subfields, $target_offset,
573 $target_length, $target_normalizer);
575 Adds a required check, which requires that the normalized keys made from the source and targets
576 must match for a match to be considered valid.
580 sub add_simple_required_check
{
582 my ($source_tag, $source_subfields, $source_offset, $source_length, $source_normalizer,
583 $target_tag, $target_subfields, $target_offset, $target_length, $target_normalizer) = @_;
585 $self->add_required_check(
586 [ { tag
=> $source_tag, subfields
=> $source_subfields, offset
=> $source_offset, 'length' => $source_length,
587 norms
=> [ $source_normalizer ] } ],
588 [ { tag
=> $target_tag, subfields
=> $target_subfields, offset
=> $target_offset, 'length' => $target_length,
589 norms
=> [ $target_normalizer ] } ]
595 my @matches = $matcher->get_matches($marc_record, $max_matches);
596 foreach $match (@matches) {
597 # matches already sorted in order of
599 print "record ID: $match->{'record_id'};
600 print "score: $match->{'score'};
603 Identifies all of the records matching the given MARC record. For a record already
604 in the database to be considered a match, it must meet the following criteria:
608 =item 1. Total score from its matching field must exceed the supplied threshold.
610 =item 2. It must pass all required checks.
614 Only the top $max_matches matches are returned. The returned array is sorted
615 in order of decreasing score, i.e., the best match is first.
621 my ($source_record, $max_matches) = @_;
626 $QParser = C4
::Context
->queryparser if (C4
::Context
->preference('UseQueryParser'));
627 foreach my $matchpoint ( @
{ $self->{'matchpoints'} } ) {
628 my @source_keys = _get_match_keys
( $source_record, $matchpoint );
630 next if scalar(@source_keys) == 0;
632 # FIXME - because of a bug in QueryParser, an expression ofthe
633 # format 'isbn:"isbn1" || isbn:"isbn2" || isbn"isbn3"...'
634 # does not get parsed correctly, so we will not
635 # do AggressiveMatchOnISBN if UseQueryParser is on
636 @source_keys = C4
::Koha
::GetVariationsOfISBNs
(@source_keys)
637 if ( $matchpoint->{index} =~ /^isbn$/i
638 && C4
::Context
->preference('AggressiveMatchOnISBN') )
639 && !C4
::Context
->preference('UseQueryParser');
646 if ( $self->{'record_type'} eq 'biblio' ) {
649 $query = join( " || ",
650 map { "$matchpoint->{'index'}:$_" } @source_keys );
653 my $phr = C4
::Context
->preference('AggressiveMatchOnISBN') ?
',phr' : q{};
654 $query = join( " or ",
655 map { "$matchpoint->{'index'}$phr=\"$_\"" } @source_keys );
656 #NOTE: double-quote the values so you don't get a "Embedded truncation not supported" error when a term has a ? in it.
659 my $searcher = Koha
::SearchEngine
::Search
->new({index => $Koha::SearchEngine
::BIBLIOS_INDEX
});
660 ( $error, $searchresults, $total_hits ) =
661 $searcher->simple_search_compat( $query, 0, $max_matches );
663 elsif ( $self->{'record_type'} eq 'authority' ) {
670 foreach my $key (@source_keys) {
671 push @marclist, $matchpoint->{'index'};
673 push @operator, 'exact';
676 require C4
::AuthoritiesMarc
;
677 ( $authresults, $total_hits ) =
678 C4
::AuthoritiesMarc
::SearchAuthorities
(
679 \
@marclist, \
@and_or, \
@excluding, \
@operator,
680 \
@value, 0, 20, undef,
683 foreach my $result (@
$authresults) {
684 push @
$searchresults, $result->{'authid'};
688 if ( defined $error ) {
689 warn "search failed ($query) $error";
692 foreach my $matched ( @
{$searchresults} ) {
693 $matches{$matched} += $matchpoint->{'score'};
698 # get rid of any that don't meet the threshold
699 %matches = map { ($matches{$_} >= $self->{'threshold'}) ?
($_ => $matches{$_}) : () } keys %matches;
701 # get rid of any that don't meet the required checks
702 %matches = map { _passes_required_checks
($source_record, $_, $self->{'required_checks'}) ?
($_ => $matches{$_}) : () }
703 keys %matches unless ($self->{'record_type'} eq 'auth');
706 if ($self->{'record_type'} eq 'biblio') {
708 foreach my $marcblob (keys %matches) {
709 my $target_record = C4
::Search
::new_record_from_zebra
('biblioserver',$marcblob);
711 my $result = C4
::Biblio
::TransformMarcToKoha
($target_record, '');
712 $record_number = $result->{'biblionumber'};
713 push @results, { 'record_id' => $record_number, 'score' => $matches{$marcblob} };
715 } elsif ($self->{'record_type'} eq 'authority') {
716 require C4
::AuthoritiesMarc
;
717 foreach my $authid (keys %matches) {
718 push @results, { 'record_id' => $authid, 'score' => $matches{$authid} };
721 @results = sort { $b->{'score'} cmp $a->{'score'} } @results;
722 if (scalar(@results) > $max_matches) {
723 @results = @results[0..$max_matches-1];
731 $description = $matcher->dump();
733 Returns a reference to a structure containing all of the information
734 in the matcher object. This is mainly a convenience method to
735 aid setting up a HTML editing form.
744 $result->{'matcher_id'} = $self->{'id'};
745 $result->{'code'} = $self->{'code'};
746 $result->{'description'} = $self->{'description'};
747 $result->{'record_type'} = $self->{'record_type'};
749 $result->{'matchpoints'} = [];
750 foreach my $matchpoint (@
{ $self->{'matchpoints'} }) {
751 push @
{ $result->{'matchpoints'} }, $matchpoint;
753 $result->{'matchchecks'} = [];
754 foreach my $matchcheck (@
{ $self->{'required_checks'} }) {
755 push @
{ $result->{'matchchecks'} }, $matchcheck;
761 sub _passes_required_checks
{
762 my ($source_record, $target_blob, $matchchecks) = @_;
763 my $target_record = MARC
::Record
->new_from_usmarc($target_blob); # FIXME -- need to avoid parsing record twice
765 # no checks supplied == automatic pass
766 return 1 if $#{ $matchchecks } == -1;
768 foreach my $matchcheck (@
{ $matchchecks }) {
769 my $source_key = join "", _get_match_keys
($source_record, $matchcheck->{'source_matchpoint'});
770 my $target_key = join "", _get_match_keys
($target_record, $matchcheck->{'target_matchpoint'});
771 return 0 unless $source_key eq $target_key;
776 sub _get_match_keys
{
777 my $source_record = shift;
778 my $matchpoint = shift;
779 my $check_only_first_repeat = @_ ?
shift : 0;
781 # If there is more than one component to the matchpoint (e.g.,
782 # matchpoint includes both 003 and 001), any repeats
783 # of the first component's tag are identified; repeats
784 # of the subsequent components' tags are appended to
785 # each parallel key dervied from the first component,
786 # up to the number of repeats of the first component's tag.
788 # For example, if the record has one 003 and two 001s, only
789 # one key is retrieved because there is only one 003. The key
790 # will consist of the contents of the first 003 and first 001.
792 # If there are two 003s and two 001s, there will be two keys:
793 # first 003 + first 001
794 # second 003 + second 001
797 for (my $i = 0; $i <= $#{ $matchpoint->{'components'} }; $i++) {
798 my $component = $matchpoint->{'components'}->[$i];
800 FIELD
: foreach my $field ($source_record->field($component->{'tag'})) {
802 last FIELD
if $j > 0 and $check_only_first_repeat;
803 last FIELD
if $i > 0 and $j > $#keys;
806 if ($field->is_control_field()) {
807 $string=$field->data();
809 foreach my $subfield ($field->subfields()) {
810 if (exists $component->{'subfields'}->{$subfield->[0]}) {
811 $string .= " " . $subfield->[1]; #FIXME: It would be better to create an array and join with a space later...
815 if ($component->{'length'}>0) {
816 $string= substr($string, $component->{'offset'}, $component->{'length'});
817 # FIXME normalize, substr
818 } elsif ($component->{'offset'}) {
819 $string= substr($string, $component->{'offset'});
821 $key = _normalize
($string);
823 push @keys, $key if $key;
825 $keys[$j] .= " $key" if $key;
833 sub _parse_match_component
{
834 my $input_component = shift;
837 $component->{'tag'} = $input_component->{'tag'};
838 $component->{'subfields'} = { map { $_ => 1 } split(//, $input_component->{'subfields'}) };
839 $component->{'offset'} = exists($input_component->{'offset'}) ?
$input_component->{'offset'} : -1;
840 $component->{'length'} = $input_component->{'length'} ?
$input_component->{'length'} : 0;
841 $component->{'norms'} = $input_component->{'norms'} ?
$input_component->{'norms'} : [];
846 # FIXME - default normalizer
848 my $value = uc shift;
849 $value =~ s/[.;:,\]\[\)\(\/'"]//g
;
851 #$value =~ s/^\s+$//;
854 #$value =~ s/[.;,\]\[\)\(\/"']//g;
863 Koha Development Team <http://koha-community.org/>
865 Galen Charlton <galen.charlton@liblime.com>