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