]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
search: do not index references and inreplyto terms
[public-inbox.git] / lib / PublicInbox / Search.pm
1 # Copyright (C) 2015, all contributors <meta@public-inbox.org>
2 # License: AGPLv3 or later (https://www.gnu.org/licenses/agpl-3.0.txt)
3 # based on notmuch, but with no concept of folders, files or flags
4 package PublicInbox::Search;
5 use strict;
6 use warnings;
7 use PublicInbox::SearchMsg;
8 use Search::Xapian qw/:standard/;
9 use Email::MIME;
10 use PublicInbox::MID qw/mid_clean mid_compress/;
11
12 # This is English-only, everything else is non-standard and may be confused as
13 # a prefix common in patch emails
14 our $REPLY_RE = qr/^re:\s+/i;
15 our $LANG = 'english';
16
17 use constant {
18         TS => 0,
19         # SCHEMA_VERSION history
20         # 0 - initial
21         # 1 - subject_path is lower-cased
22         # 2 - subject_path is mid_compress in the index, only
23         # 3 - message-ID is compressed if it includes '%' (hack!)
24         # 4 - change "Re: " normalization, avoid circular Reference ghosts
25         # 5 - subject_path drops trailing '.'
26         # 6 - preserve References: order in document data
27         # 7 - remove references and inreplyto terms
28         SCHEMA_VERSION => 7,
29         QP_FLAGS => FLAG_PHRASE|FLAG_BOOLEAN|FLAG_LOVEHATE|FLAG_WILDCARD,
30 };
31
32 # setup prefixes
33 my %bool_pfx_internal = (
34         type => 'T', # "mail" or "ghost"
35         mid => 'Q', # uniQue id (Message-ID or mid_compress)
36 );
37
38 my %bool_pfx_external = (
39         path => 'XPATH',
40         thread => 'G', # newsGroup (or similar entity - e.g. a web forum name)
41 );
42
43 my %prob_prefix = (
44         subject => 'S',
45 );
46
47 my %all_pfx = (%bool_pfx_internal, %bool_pfx_external, %prob_prefix);
48
49 sub xpfx { $all_pfx{$_[0]} }
50
51 our %PFX2TERM_RMAP;
52 my %meta_pfx = (mid => 1, thread => 1, path => 1);
53 while (my ($k, $v) = each %all_pfx) {
54         $PFX2TERM_RMAP{$v} = $k if $meta_pfx{$k};
55 }
56
57 my $mail_query = Search::Xapian::Query->new(xpfx('type') . 'mail');
58
59 sub xdir {
60         my (undef, $git_dir) = @_;
61         "$git_dir/public-inbox/xapian" . SCHEMA_VERSION;
62 }
63
64 sub new {
65         my ($class, $git_dir) = @_;
66         my $dir = $class->xdir($git_dir);
67         my $db = Search::Xapian::Database->new($dir);
68         bless { xdb => $db, git_dir => $git_dir }, $class;
69 }
70
71 sub reopen { $_[0]->{xdb}->reopen }
72
73 # read-only
74 sub query {
75         my ($self, $query_string, $opts) = @_;
76         my $query = $self->qp->parse_query($query_string, QP_FLAGS);
77
78         $opts ||= {};
79         $opts->{relevance} = 1;
80         $self->do_enquire($query, $opts);
81 }
82
83 sub get_subject_path {
84         my ($self, $path, $opts) = @_;
85         my $query = $self->qp->parse_query("path:".mid_compress($path), 0);
86         $self->do_enquire($query, $opts);
87 }
88
89 sub get_thread {
90         my ($self, $mid, $opts) = @_;
91         my $smsg = eval { $self->lookup_message($mid) };
92
93         return { total => 0, msgs => [] } unless $smsg;
94         my $qp = $self->qp;
95         my $qtid = $qp->parse_query('thread:'.$smsg->thread_id, 0);
96         my $qsub = $qp->parse_query('path:'.mid_compress($smsg->path), 0);
97         my $query = Search::Xapian::Query->new(OP_OR, $qtid, $qsub);
98         $self->do_enquire($query, $opts);
99 }
100
101 # private subs below
102
103 sub do_enquire {
104         my ($self, $query, $opts) = @_;
105         my $enquire = $self->enquire;
106
107         $query = Search::Xapian::Query->new(OP_AND, $query, $mail_query);
108         $enquire->set_query($query);
109         if ($opts->{relevance}) {
110                 $enquire->set_sort_by_relevance_then_value(TS, 0);
111         } else {
112                 $enquire->set_sort_by_value(TS, 0);
113         }
114         $opts ||= {};
115         my $offset = $opts->{offset} || 0;
116         my $limit = $opts->{limit} || 50;
117         my $mset = $enquire->get_mset($offset, $limit);
118         my @msgs = map {
119                 PublicInbox::SearchMsg->load_doc($_->get_document);
120         } $mset->items;
121
122         { total => $mset->get_matches_estimated, msgs => \@msgs }
123 }
124
125 # read-write
126 sub stemmer { Search::Xapian::Stem->new($LANG) }
127
128 # read-only
129 sub qp {
130         my ($self) = @_;
131
132         my $qp = $self->{query_parser};
133         return $qp if $qp;
134
135         # new parser
136         $qp = Search::Xapian::QueryParser->new;
137         $qp->set_default_op(OP_AND);
138         $qp->set_database($self->{xdb});
139         $qp->set_stemmer($self->stemmer);
140         $qp->set_stemming_strategy(STEM_SOME);
141         $qp->add_valuerangeprocessor($self->ts_range_processor);
142         $qp->add_valuerangeprocessor($self->date_range_processor);
143
144         while (my ($name, $prefix) = each %bool_pfx_external) {
145                 $qp->add_boolean_prefix($name, $prefix);
146         }
147
148         while (my ($name, $prefix) = each %prob_prefix) {
149                 $qp->add_prefix($name, $prefix);
150         }
151
152         $self->{query_parser} = $qp;
153 }
154
155 sub ts_range_processor {
156         $_[0]->{tsrp} ||= Search::Xapian::NumberValueRangeProcessor->new(TS);
157 }
158
159 sub date_range_processor {
160         $_[0]->{drp} ||= Search::Xapian::DateValueRangeProcessor->new(TS);
161 }
162
163 sub lookup_message {
164         my ($self, $mid) = @_;
165         $mid = mid_clean($mid);
166         $mid = mid_compress($mid);
167
168         my $doc_id = $self->find_unique_doc_id('mid', $mid);
169         my $smsg;
170         if (defined $doc_id) {
171                 # raises on error:
172                 my $doc = $self->{xdb}->get_document($doc_id);
173                 $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
174                 $smsg->doc_id($doc_id);
175         }
176         $smsg;
177 }
178
179 sub find_unique_doc_id {
180         my ($self, $term, $value) = @_;
181
182         my ($begin, $end) = $self->find_doc_ids($term, $value);
183
184         return undef if $begin->equal($end); # not found
185
186         my $rv = $begin->get_docid;
187
188         # sanity check
189         $begin->inc;
190         $begin->equal($end) or die "Term '$term:$value' is not unique\n";
191         $rv;
192 }
193
194 # returns begin and end PostingIterator
195 sub find_doc_ids {
196         my ($self, $term, $value) = @_;
197
198         $self->find_doc_ids_for_term(xpfx($term) . $value);
199 }
200
201 # returns begin and end PostingIterator
202 sub find_doc_ids_for_term {
203         my ($self, $term) = @_;
204         my $db = $self->{xdb};
205
206         ($db->postlist_begin($term), $db->postlist_end($term));
207 }
208
209 # normalize subjects so they are suitable as pathnames for URLs
210 sub subject_path {
211         my $subj = pop;
212         $subj = subject_normalized($subj);
213         $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
214         lc($subj);
215 }
216
217 sub subject_normalized {
218         my $subj = pop;
219         $subj =~ s/\A\s+//s; # no leading space
220         $subj =~ s/\s+\z//s; # no trailing space
221         $subj =~ s/\s+/ /gs; # no redundant spaces
222         $subj =~ s/\.+\z//; # no trailing '.'
223         $subj =~ s/$REPLY_RE//igo; # remove reply prefix
224         $subj;
225 }
226
227 # for doc data
228 sub subject_summary {
229         my $subj = pop;
230         my $max = 68;
231         if (length($subj) > $max) {
232                 my @subj = split(/\s+/, $subj);
233                 $subj = '';
234                 my $l;
235
236                 while ($l = shift @subj) {
237                         my $new = $subj . $l . ' ';
238                         last if length($new) >= $max;
239                         $subj = $new;
240                 }
241                 if ($subj ne '') {
242                         my $r = scalar @subj ? ' ...' : '';
243                         $subj =~ s/ \z/$r/s;
244                 } else {
245                         # subject has one REALLY long word, and NOT spam? wtf
246                         @subj = ($l =~ /\A(.{1,72})/);
247                         $subj = $subj[0] . ' ...';
248                 }
249         }
250         $subj;
251 }
252
253 sub enquire {
254         my ($self) = @_;
255         $self->{enquire} ||= Search::Xapian::Enquire->new($self->{xdb});
256 }
257
258 1;