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>.
33 C4::Matcher - find MARC records matching another one
37 my @matchers = C4::Matcher::GetMatcherList();
39 my $matcher = C4::Matcher->new($record_type);
40 $matcher->threshold($threshold);
41 $matcher->code($code);
42 $matcher->description($description);
44 $matcher->add_simple_matchpoint('isbn', 1000, '020', 'a', -1, 0, '');
45 $matcher->add_simple_matchpoint('Date', 1000, '008', '', 7, 4, '');
46 $matcher->add_matchpoint('isbn', 1000, [ { tag => '020', subfields => 'a', norms => [] } ]);
48 $matcher->add_simple_required_check('245', 'a', -1, 0, '', '245', 'a', -1, 0, '');
49 $matcher->add_required_check([ { tag => '245', subfields => 'a', norms => [] } ],
50 [ { tag => '245', subfields => 'a', norms => [] } ]);
52 my @matches = $matcher->get_matches($marc_record, $max_matches);
54 foreach $match (@matches) {
56 # matches already sorted in order of
58 print "record ID: $match->{'record_id'};
59 print "score: $match->{'score'};
63 my $matcher_description = $matcher->dump();
71 my @matchers = C4::Matcher::GetMatcherList();
73 Returns an array of hashrefs list all matchers
74 present in the database. Each hashref includes:
83 my $dbh = C4::Context->dbh;
85 my $sth = $dbh->prepare_cached("SELECT matcher_id, code, description FROM marc_matchers ORDER BY matcher_id");
88 while (my $row = $sth->fetchrow_hashref) {
96 my $matcher_id = C4::Matcher::GetMatcherId($code);
98 Returns the matcher_id of a code.
104 my $dbh = C4::Context->dbh;
106 my $matcher_id = $dbh->selectrow_array("SELECT matcher_id FROM marc_matchers WHERE code = ?", undef, $code);
114 my $matcher = C4::Matcher->new($record_type, $threshold);
116 Creates a new Matcher. C<$record_type> indicates which search
117 database to use, e.g., 'biblio' or 'authority' and defaults to
118 'biblio', while C<$threshold> is the minimum score required for a match
119 and defaults to 1000.
127 $self->{'id'} = undef;
130 $self->{'record_type'} = shift;
132 $self->{'record_type'} = 'biblio';
136 $self->{'threshold'} = shift;
138 $self->{'threshold'} = 1000;
141 $self->{'code'} = '';
142 $self->{'description'} = '';
144 $self->{'matchpoints'} = [];
145 $self->{'required_checks'} = [];
153 my $matcher = C4::Matcher->fetch($id);
155 Creates a matcher object from the version stored
156 in the database. If a matcher with the given
157 id does not exist, returns undef.
164 my $dbh = C4::Context->dbh();
166 my $sth = $dbh->prepare_cached("SELECT * FROM marc_matchers WHERE matcher_id = ?");
168 my $row = $sth->fetchrow_hashref;
170 return undef unless defined $row;
173 $self->{'id'} = $row->{'matcher_id'};
174 $self->{'record_type'} = $row->{'record_type'};
175 $self->{'code'} = $row->{'code'};
176 $self->{'description'} = $row->{'description'};
177 $self->{'threshold'} = int($row->{'threshold'});
181 $self->{'matchpoints'} = [];
182 $sth = $dbh->prepare_cached("SELECT * FROM matcher_matchpoints WHERE matcher_id = ? ORDER BY matchpoint_id");
183 $sth->execute($self->{'id'});
184 while (my $row = $sth->fetchrow_hashref) {
185 my $matchpoint = $self->_fetch_matchpoint($row->{'matchpoint_id'});
186 push @{ $self->{'matchpoints'} }, $matchpoint;
190 $self->{'required_checks'} = [];
191 $sth = $dbh->prepare_cached("SELECT * FROM matchchecks WHERE matcher_id = ? ORDER BY matchcheck_id");
192 $sth->execute($self->{'id'});
193 while (my $row = $sth->fetchrow_hashref) {
194 my $source_matchpoint = $self->_fetch_matchpoint($row->{'source_matchpoint_id'});
195 my $target_matchpoint = $self->_fetch_matchpoint($row->{'target_matchpoint_id'});
197 $matchcheck->{'source_matchpoint'} = $source_matchpoint;
198 $matchcheck->{'target_matchpoint'} = $target_matchpoint;
199 push @{ $self->{'required_checks'} }, $matchcheck;
205 sub _fetch_matchpoint {
207 my $matchpoint_id = shift;
209 my $dbh = C4::Context->dbh;
210 my $sth = $dbh->prepare_cached("SELECT * FROM matchpoints WHERE matchpoint_id = ?");
211 $sth->execute($matchpoint_id);
212 my $row = $sth->fetchrow_hashref;
214 $matchpoint->{'index'} = $row->{'search_index'};
215 $matchpoint->{'score'} = int($row->{'score'});
218 $matchpoint->{'components'} = [];
219 $sth = $dbh->prepare_cached("SELECT * FROM matchpoint_components WHERE matchpoint_id = ? ORDER BY sequence");
220 $sth->execute($matchpoint_id);
221 while ($row = $sth->fetchrow_hashref) {
223 $component->{'tag'} = $row->{'tag'};
224 $component->{'subfields'} = { map { $_ => 1 } split(//, $row->{'subfields'}) };
225 $component->{'offset'} = int($row->{'offset'});
226 $component->{'length'} = int($row->{'length'});
227 $component->{'norms'} = [];
228 my $sth2 = $dbh->prepare_cached("SELECT *
229 FROM matchpoint_component_norms
230 WHERE matchpoint_component_id = ? ORDER BY sequence");
231 $sth2->execute($row->{'matchpoint_component_id'});
232 while (my $row2 = $sth2->fetchrow_hashref) {
233 push @{ $component->{'norms'} }, $row2->{'norm_routine'};
235 push @{ $matchpoint->{'components'} }, $component;
242 my $id = $matcher->store();
244 Stores matcher in database. The return value is the ID
245 of the marc_matchers row. If the matcher was
246 previously retrieved from the database via the fetch()
247 method, the DB representation of the matcher
255 if (defined $self->{'id'}) {
257 $self->_del_matcher_components();
258 $self->_update_marc_matchers();
261 $self->_new_marc_matchers();
263 $self->_store_matcher_components();
264 return $self->{'id'};
267 sub _del_matcher_components {
270 my $dbh = C4::Context->dbh();
271 my $sth = $dbh->prepare_cached("DELETE FROM matchpoints WHERE matcher_id = ?");
272 $sth->execute($self->{'id'});
273 $sth = $dbh->prepare_cached("DELETE FROM matchchecks WHERE matcher_id = ?");
274 $sth->execute($self->{'id'});
275 # foreign key delete cascades take care of deleting relevant rows
276 # from matcher_matchpoints, matchpoint_components, and
277 # matchpoint_component_norms
280 sub _update_marc_matchers {
283 my $dbh = C4::Context->dbh();
284 my $sth = $dbh->prepare_cached("UPDATE marc_matchers
289 WHERE matcher_id = ?");
290 $sth->execute($self->{'code'}, $self->{'description'}, $self->{'record_type'}, $self->{'threshold'}, $self->{'id'});
293 sub _new_marc_matchers {
296 my $dbh = C4::Context->dbh();
297 my $sth = $dbh->prepare_cached("INSERT INTO marc_matchers
298 (code, description, record_type, threshold)
299 VALUES (?, ?, ?, ?)");
300 $sth->execute($self->{'code'}, $self->{'description'}, $self->{'record_type'}, $self->{'threshold'});
301 $self->{'id'} = $dbh->{'mysql_insertid'};
304 sub _store_matcher_components {
307 my $dbh = C4::Context->dbh();
309 my $matcher_id = $self->{'id'};
310 foreach my $matchpoint (@{ $self->{'matchpoints'}}) {
311 my $matchpoint_id = $self->_store_matchpoint($matchpoint);
312 $sth = $dbh->prepare_cached("INSERT INTO matcher_matchpoints (matcher_id, matchpoint_id)
314 $sth->execute($matcher_id, $matchpoint_id);
316 foreach my $matchcheck (@{ $self->{'required_checks'} }) {
317 my $source_matchpoint_id = $self->_store_matchpoint($matchcheck->{'source_matchpoint'});
318 my $target_matchpoint_id = $self->_store_matchpoint($matchcheck->{'target_matchpoint'});
319 $sth = $dbh->prepare_cached("INSERT INTO matchchecks
320 (matcher_id, source_matchpoint_id, target_matchpoint_id)
322 $sth->execute($matcher_id, $source_matchpoint_id, $target_matchpoint_id);
327 sub _store_matchpoint {
329 my $matchpoint = shift;
331 my $dbh = C4::Context->dbh();
333 my $matcher_id = $self->{'id'};
334 $sth = $dbh->prepare_cached("INSERT INTO matchpoints (matcher_id, search_index, score)
336 $sth->execute($matcher_id, $matchpoint->{'index'}, $matchpoint->{'score'});
337 my $matchpoint_id = $dbh->{'mysql_insertid'};
339 foreach my $component (@{ $matchpoint->{'components'} }) {
341 $sth = $dbh->prepare_cached("INSERT INTO matchpoint_components
342 (matchpoint_id, sequence, tag, subfields, offset, length)
343 VALUES (?, ?, ?, ?, ?, ?)");
344 $sth->bind_param(1, $matchpoint_id);
345 $sth->bind_param(2, $seqnum);
346 $sth->bind_param(3, $component->{'tag'});
347 $sth->bind_param(4, join "", sort keys %{ $component->{'subfields'} });
348 $sth->bind_param(5, $component->{'offset'});
349 $sth->bind_param(6, $component->{'length'});
351 my $matchpoint_component_id = $dbh->{'mysql_insertid'};
353 foreach my $norm (@{ $component->{'norms'} }) {
355 $sth = $dbh->prepare_cached("INSERT INTO matchpoint_component_norms
356 (matchpoint_component_id, sequence, norm_routine)
358 $sth->execute($matchpoint_component_id, $normseq, $norm);
361 return $matchpoint_id;
367 C4::Matcher->delete($id);
369 Deletes the matcher of the specified ID
376 my $matcher_id = shift;
378 my $dbh = C4::Context->dbh;
379 my $sth = $dbh->prepare("DELETE FROM marc_matchers WHERE matcher_id = ?");
380 $sth->execute($matcher_id); # relying on cascading deletes to clean up everything
385 $matcher->record_type('biblio');
386 my $record_type = $matcher->record_type();
394 @_ ? $self->{'record_type'} = shift : $self->{'record_type'};
399 $matcher->threshold(1000);
400 my $threshold = $matcher->threshold();
408 @_ ? $self->{'threshold'} = shift : $self->{'threshold'};
414 my $id = $matcher->_id();
416 Accessor method. Note that using this method
417 to set the DB ID of the matcher should not be
418 done outside of the editing CGI.
424 @_ ? $self->{'id'} = shift : $self->{'id'};
429 $matcher->code('ISBN');
430 my $code = $matcher->code();
438 @_ ? $self->{'code'} = shift : $self->{'code'};
443 $matcher->description('match on ISBN');
444 my $description = $matcher->description();
452 @_ ? $self->{'description'} = shift : $self->{'description'};
455 =head2 add_matchpoint
457 $matcher->add_matchpoint($index, $score, $matchcomponents);
459 Adds a matchpoint that may include multiple components. The $index
460 parameter identifies the index that will be searched, while $score
461 is the weight that will be added if a match is found.
463 $matchcomponents should be a reference to an array of matchpoint
464 compoents, each of which should be a hash containing the following
472 The normalization_rules value should in turn be a reference to an
473 array, each element of which should be a reference to a
474 normalization subroutine (under C4::Normalize) to be applied
475 to the source string.
481 my ($index, $score, $matchcomponents) = @_;
484 $matchpoint->{'index'} = $index;
485 $matchpoint->{'score'} = $score;
486 $matchpoint->{'components'} = [];
487 foreach my $input_component (@{ $matchcomponents }) {
488 push @{ $matchpoint->{'components'} }, _parse_match_component($input_component);
490 push @{ $self->{'matchpoints'} }, $matchpoint;
493 =head2 add_simple_matchpoint
495 $matcher->add_simple_matchpoint($index, $score, $source_tag,
496 $source_subfields, $source_offset,
497 $source_length, $source_normalizer);
500 Adds a simple matchpoint rule -- after composing a key based on the source tag and subfields,
501 normalized per the normalization fuction, search the index. All records retrieved
502 will receive the assigned score.
506 sub add_simple_matchpoint {
508 my ($index, $score, $source_tag, $source_subfields, $source_offset, $source_length, $source_normalizer) = @_;
510 $self->add_matchpoint($index, $score, [
511 { tag => $source_tag, subfields => $source_subfields,
512 offset => $source_offset, 'length' => $source_length,
513 norms => [ $source_normalizer ]
518 =head2 add_required_check
520 $match->add_required_check($source_matchpoint, $target_matchpoint);
522 Adds a required check definition. A required check means that in
523 order for a match to be considered valid, the key derived from the
524 source (incoming) record must match the key derived from the target
525 (already in DB) record.
527 Unlike a regular matchpoint, only the first repeat of each tag
528 in the source and target match criteria are considered.
530 A typical example of a required check would be verifying that the
531 titles and publication dates match.
533 $source_matchpoint and $target_matchpoint are each a reference to
534 an array of hashes, where each hash follows the same definition
535 as the matchpoint component specification in add_matchpoint, i.e.,
543 The normalization_rules value should in turn be a reference to an
544 array, each element of which should be a reference to a
545 normalization subroutine (under C4::Normalize) to be applied
546 to the source string.
550 sub add_required_check {
552 my ($source_matchpoint, $target_matchpoint) = @_;
555 $matchcheck->{'source_matchpoint'}->{'index'} = '';
556 $matchcheck->{'source_matchpoint'}->{'score'} = 0;
557 $matchcheck->{'source_matchpoint'}->{'components'} = [];
558 $matchcheck->{'target_matchpoint'}->{'index'} = '';
559 $matchcheck->{'target_matchpoint'}->{'score'} = 0;
560 $matchcheck->{'target_matchpoint'}->{'components'} = [];
561 foreach my $input_component (@{ $source_matchpoint }) {
562 push @{ $matchcheck->{'source_matchpoint'}->{'components'} }, _parse_match_component($input_component);
564 foreach my $input_component (@{ $target_matchpoint }) {
565 push @{ $matchcheck->{'target_matchpoint'}->{'components'} }, _parse_match_component($input_component);
567 push @{ $self->{'required_checks'} }, $matchcheck;
570 =head2 add_simple_required_check
572 $matcher->add_simple_required_check($source_tag, $source_subfields,
573 $source_offset, $source_length, $source_normalizer,
574 $target_tag, $target_subfields, $target_offset,
575 $target_length, $target_normalizer);
577 Adds a required check, which requires that the normalized keys made from the source and targets
578 must match for a match to be considered valid.
582 sub add_simple_required_check {
584 my ($source_tag, $source_subfields, $source_offset, $source_length, $source_normalizer,
585 $target_tag, $target_subfields, $target_offset, $target_length, $target_normalizer) = @_;
587 $self->add_required_check(
588 [ { tag => $source_tag, subfields => $source_subfields, offset => $source_offset, 'length' => $source_length,
589 norms => [ $source_normalizer ] } ],
590 [ { tag => $target_tag, subfields => $target_subfields, offset => $target_offset, 'length' => $target_length,
591 norms => [ $target_normalizer ] } ]
597 my @matches = $matcher->get_matches($marc_record, $max_matches);
598 foreach $match (@matches) {
599 # matches already sorted in order of
601 print "record ID: $match->{'record_id'};
602 print "score: $match->{'score'};
605 Identifies all of the records matching the given MARC record. For a record already
606 in the database to be considered a match, it must meet the following criteria:
610 =item 1. Total score from its matching field must exceed the supplied threshold.
612 =item 2. It must pass all required checks.
616 Only the top $max_matches matches are returned. The returned array is sorted
617 in order of decreasing score, i.e., the best match is first.
623 my ($source_record, $max_matches) = @_;
628 $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
629 foreach my $matchpoint ( @{ $self->{'matchpoints'} } ) {
630 my @source_keys = _get_match_keys( $source_record, $matchpoint );
632 next if scalar(@source_keys) == 0;
634 # FIXME - because of a bug in QueryParser, an expression ofthe
635 # format 'isbn:"isbn1" || isbn:"isbn2" || isbn"isbn3"...'
636 # does not get parsed correctly, so we will not
637 # do AggressiveMatchOnISBN if UseQueryParser is on
638 @source_keys = C4::Koha::GetVariationsOfISBNs(@source_keys)
639 if ( $matchpoint->{index} =~ /^isbn$/i
640 && C4::Context->preference('AggressiveMatchOnISBN') )
641 && !C4::Context->preference('UseQueryParser');
648 if ( $self->{'record_type'} eq 'biblio' ) {
651 $query = join( " || ",
652 map { "$matchpoint->{'index'}:$_" } @source_keys );
655 my $phr = C4::Context->preference('AggressiveMatchOnISBN') ? ',phr' : q{};
656 $query = join( " or ",
657 map { "$matchpoint->{'index'}$phr=$_" } @source_keys );
662 ( $error, $searchresults, $total_hits ) =
663 C4::Search::SimpleSearch( $query, 0, $max_matches );
665 elsif ( $self->{'record_type'} eq 'authority' ) {
672 foreach my $key (@source_keys) {
673 push @marclist, $matchpoint->{'index'};
675 push @operator, 'exact';
678 require C4::AuthoritiesMarc;
679 ( $authresults, $total_hits ) =
680 C4::AuthoritiesMarc::SearchAuthorities(
681 \@marclist, \@and_or, \@excluding, \@operator,
682 \@value, 0, 20, undef,
685 foreach my $result (@$authresults) {
686 push @$searchresults, $result->{'authid'};
690 if ( defined $error ) {
691 warn "search failed ($query) $error";
694 foreach my $matched ( @{$searchresults} ) {
695 $matches{$matched} += $matchpoint->{'score'};
700 # get rid of any that don't meet the threshold
701 %matches = map { ($matches{$_} >= $self->{'threshold'}) ? ($_ => $matches{$_}) : () } keys %matches;
703 # get rid of any that don't meet the required checks
704 %matches = map { _passes_required_checks($source_record, $_, $self->{'required_checks'}) ? ($_ => $matches{$_}) : () }
705 keys %matches unless ($self->{'record_type'} eq 'auth');
708 if ($self->{'record_type'} eq 'biblio') {
710 foreach my $marcblob (keys %matches) {
711 my $target_record = C4::Search::new_record_from_zebra('biblioserver',$marcblob);
713 my $result = C4::Biblio::TransformMarcToKoha(C4::Context->dbh, $target_record, '');
714 $record_number = $result->{'biblionumber'};
715 push @results, { 'record_id' => $record_number, 'score' => $matches{$marcblob} };
717 } elsif ($self->{'record_type'} eq 'authority') {
718 require C4::AuthoritiesMarc;
719 foreach my $authid (keys %matches) {
720 push @results, { 'record_id' => $authid, 'score' => $matches{$authid} };
723 @results = sort { $b->{'score'} cmp $a->{'score'} } @results;
724 if (scalar(@results) > $max_matches) {
725 @results = @results[0..$max_matches-1];
733 $description = $matcher->dump();
735 Returns a reference to a structure containing all of the information
736 in the matcher object. This is mainly a convenience method to
737 aid setting up a HTML editing form.
746 $result->{'matcher_id'} = $self->{'id'};
747 $result->{'code'} = $self->{'code'};
748 $result->{'description'} = $self->{'description'};
749 $result->{'record_type'} = $self->{'record_type'};
751 $result->{'matchpoints'} = [];
752 foreach my $matchpoint (@{ $self->{'matchpoints'} }) {
753 push @{ $result->{'matchpoints'} }, $matchpoint;
755 $result->{'matchchecks'} = [];
756 foreach my $matchcheck (@{ $self->{'required_checks'} }) {
757 push @{ $result->{'matchchecks'} }, $matchcheck;
763 sub _passes_required_checks {
764 my ($source_record, $target_blob, $matchchecks) = @_;
765 my $target_record = MARC::Record->new_from_usmarc($target_blob); # FIXME -- need to avoid parsing record twice
767 # no checks supplied == automatic pass
768 return 1 if $#{ $matchchecks } == -1;
770 foreach my $matchcheck (@{ $matchchecks }) {
771 my $source_key = join "", _get_match_keys($source_record, $matchcheck->{'source_matchpoint'});
772 my $target_key = join "", _get_match_keys($target_record, $matchcheck->{'target_matchpoint'});
773 return 0 unless $source_key eq $target_key;
778 sub _get_match_keys {
779 my $source_record = shift;
780 my $matchpoint = shift;
781 my $check_only_first_repeat = @_ ? shift : 0;
783 # If there is more than one component to the matchpoint (e.g.,
784 # matchpoint includes both 003 and 001), any repeats
785 # of the first component's tag are identified; repeats
786 # of the subsequent components' tags are appended to
787 # each parallel key dervied from the first component,
788 # up to the number of repeats of the first component's tag.
790 # For example, if the record has one 003 and two 001s, only
791 # one key is retrieved because there is only one 003. The key
792 # will consist of the contents of the first 003 and first 001.
794 # If there are two 003s and two 001s, there will be two keys:
795 # first 003 + first 001
796 # second 003 + second 001
799 for (my $i = 0; $i <= $#{ $matchpoint->{'components'} }; $i++) {
800 my $component = $matchpoint->{'components'}->[$i];
802 FIELD: foreach my $field ($source_record->field($component->{'tag'})) {
804 last FIELD if $j > 0 and $check_only_first_repeat;
805 last FIELD if $i > 0 and $j > $#keys;
808 if ($field->is_control_field()) {
809 $string=$field->data();
811 foreach my $subfield ($field->subfields()) {
812 if (exists $component->{'subfields'}->{$subfield->[0]}) {
813 $string .= " " . $subfield->[1];
817 if ($component->{'length'}>0) {
818 $string= substr($string, $component->{'offset'}, $component->{'length'});
819 # FIXME normalize, substr
820 } elsif ($component->{'offset'}) {
821 $string= substr($string, $component->{'offset'});
823 $key = _normalize($string);
825 push @keys, $key if $key;
827 $keys[$j] .= " $key" if $key;
835 sub _parse_match_component {
836 my $input_component = shift;
839 $component->{'tag'} = $input_component->{'tag'};
840 $component->{'subfields'} = { map { $_ => 1 } split(//, $input_component->{'subfields'}) };
841 $component->{'offset'} = exists($input_component->{'offset'}) ? $input_component->{'offset'} : -1;
842 $component->{'length'} = $input_component->{'length'} ? $input_component->{'length'} : 0;
843 $component->{'norms'} = $input_component->{'norms'} ? $input_component->{'norms'} : [];
848 # FIXME - default normalizer
850 my $value = uc shift;
851 $value =~ s/[.;:,\]\[\)\(\/'"]//g;
853 #$value =~ s/^\s+$//;
856 #$value =~ s/[.;,\]\[\)\(\/"']//g;
865 Koha Development Team <http://koha-community.org/>
867 Galen Charlton <galen.charlton@liblime.com>