1 package BSE::Index::BSE;
3 use base 'BSE::Index::Base';
5 use Constants qw($DATADIR $MAXPHRASE);
8 my ($class, %opts) = @_;
10 my $self = bless \%opts, $class;
12 $self->{dh} = BSE::DB->single;
13 $self->{dropIndex} = $self->{dh}->stmt('dropIndex')
14 or die "No dropIndex member in BSE::DB";
15 $self->{insertIndex} = $self->{dh}->stmt('insertIndex')
16 or die "No insertIndex member in BSE::DB";
19 $self->{decay_multiplier} = 0.4;
27 my $stopwords = "$DATADIR/stopwords.txt";
30 open STOP, "< $stopwords"
31 or die "Cannot open $stopwords: $!";
32 chomp(my @stopwords = <STOP>);
33 tr/\r//d for @stopwords; # just in case
35 @stopwords{@stopwords} = (1) x @stopwords;
37 $self->{weights} = {};
43 my ($self, $article, $section, $indexas, $fields) = @_;
45 $self->{weights}{$indexas} ||= {};
46 for my $field (sort { $self->{scores}{$b} <=> $self->{scores}{$a} }
48 my $text = $fields->{$field};
49 my $score = $self->{scores}{$field};
50 my %seen; # $seen{phrase} non-zero if seen for this field
53 for my $para (split /\n/, $text) {
54 my @words = split /\W+/, $para;
57 for my $word (@words) {
58 if ($self->{stopwords}{lc $word}) {
59 $self->process($indexas, $section->{id}, $score, $self->{weights}{$indexas}, \%seen,
67 $self->process($indexas, $section->{id}, $score, $self->{weights}{$indexas}, \%seen,
74 my ($self, $id, $sectionid, $score, $weights, $seen, @words) = @_;
76 for (my $start = 0; $start < @words; ++$start) {
77 my $end = $start + $MAXPHRASE-1;
78 $end = $#words if $end > $#words;
80 for my $phrase (map { "@words[$start..$_]" } $start..$end) {
81 if (lc $phrase ne $phrase && !$seen->{lc $phrase}++) {
82 if (exists $self->{index}{lc $phrase}{$id}) {
83 $weights->{lc $phrase} *= $self->{decay_multiplier};
84 $self->{index}{lc $phrase}{$id}[1] +=
85 $score * $weights->{lc $phrase};
88 $weights->{lc $phrase} = 1.0;
89 $self->{index}{lc $phrase}{$id} = [ $sectionid, $score ];
92 if (!$seen->{$phrase}++) {
93 if (exists $self->{index}{$phrase}{$id}) {
94 $weights->{$phrase} *= $self->{decay_multiplier};
95 $self->{index}{$phrase}{$id}[1] +=
96 $score * $weights->{$phrase};
99 $weights->{$phrase} = 1.0;
100 $self->{index}{$phrase}{$id} = [ $sectionid, $score ];
110 $self->{dropIndex}->execute()
111 or die "dropIndex failed: ", $self->{dropindex}->errstr, "\n";
113 my $insertIndex = $self->{insertIndex};
114 for my $key (sort keys %{$self->{index}}) {
115 my $word = $self->{index}{$key};
116 # sort by reverse score so that if we overflow the field we
117 # get the highest scoring matches
118 my @ids = sort { $word->{$b}[1] <=> $word->{$a}[1] } keys %$word;
119 my @sections = map { $_->[0] } @$word{@ids};
120 my @scores = map { $_->[1] } @$word{@ids};
122 $insertIndex->execute($key, "@ids", "@sections", "@scores")
123 or die "Cannot insert into index: ", $insertIndex->errstr;