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