]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
search: consistently pass options and flags
[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_compressed/;
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_compressed 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_compressed)
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         $self->do_enquire($query, $opts);
80 }
81
82 sub get_subject_path {
83         my ($self, $path, $opts) = @_;
84         my $query = $self->qp->parse_query("path:".mid_compressed($path), 0);
85         $self->do_enquire($query, $opts);
86 }
87
88 # given a message ID, get followups to a message
89 sub get_followups {
90         my ($self, $mid, $opts) = @_;
91         $mid = mid_clean($mid);
92         $mid = mid_compressed($mid);
93         my $qp = $self->qp;
94         my $irt = $qp->parse_query("inreplyto:$mid", 0);
95         my $ref = $qp->parse_query("references:$mid", 0);
96         my $query = Search::Xapian::Query->new(OP_OR, $irt, $ref);
97         $self->do_enquire($query, $opts);
98 }
99
100 sub get_thread {
101         my ($self, $mid, $opts) = @_;
102         my $smsg = eval { $self->lookup_message($mid) };
103
104         return { total => 0, msgs => [] } unless $smsg;
105         my $qp = $self->qp;
106         my $qtid = $qp->parse_query('thread:'.$smsg->thread_id, 0);
107         my $qsub = $qp->parse_query('path:'.mid_compressed($smsg->path), 0);
108         my $query = Search::Xapian::Query->new(OP_OR, $qtid, $qsub);
109         $self->do_enquire($query, $opts);
110 }
111
112 # private subs below
113
114 sub do_enquire {
115         my ($self, $query, $opts) = @_;
116         my $enquire = $self->enquire;
117
118         $query = Search::Xapian::Query->new(OP_AND, $query, $mail_query);
119         $enquire->set_query($query);
120         $enquire->set_sort_by_relevance_then_value(TS, 0);
121         $opts ||= {};
122         my $offset = $opts->{offset} || 0;
123         my $limit = $opts->{limit} || 50;
124         my $mset = $enquire->get_mset($offset, $limit);
125         my @msgs = map {
126                 PublicInbox::SearchMsg->load_doc($_->get_document);
127         } $mset->items;
128
129         { total => $mset->get_matches_estimated, msgs => \@msgs }
130 }
131
132 # read-write
133 sub stemmer { Search::Xapian::Stem->new($LANG) }
134
135 # read-only
136 sub qp {
137         my ($self) = @_;
138
139         my $qp = $self->{query_parser};
140         return $qp if $qp;
141
142         # new parser
143         $qp = Search::Xapian::QueryParser->new;
144         $qp->set_default_op(OP_AND);
145         $qp->set_database($self->{xdb});
146         $qp->set_stemmer($self->stemmer);
147         $qp->set_stemming_strategy(STEM_SOME);
148         $qp->add_valuerangeprocessor($self->ts_range_processor);
149         $qp->add_valuerangeprocessor($self->date_range_processor);
150
151         while (my ($name, $prefix) = each %bool_pfx_external) {
152                 $qp->add_boolean_prefix($name, $prefix);
153         }
154
155         while (my ($name, $prefix) = each %prob_prefix) {
156                 $qp->add_prefix($name, $prefix);
157         }
158
159         $self->{query_parser} = $qp;
160 }
161
162 sub ts_range_processor {
163         $_[0]->{tsrp} ||= Search::Xapian::NumberValueRangeProcessor->new(TS);
164 }
165
166 sub date_range_processor {
167         $_[0]->{drp} ||= Search::Xapian::DateValueRangeProcessor->new(TS);
168 }
169
170 sub lookup_message {
171         my ($self, $mid) = @_;
172         $mid = mid_clean($mid);
173         $mid = mid_compressed($mid);
174
175         my $doc_id = $self->find_unique_doc_id('mid', $mid);
176         my $smsg;
177         if (defined $doc_id) {
178                 # raises on error:
179                 my $doc = $self->{xdb}->get_document($doc_id);
180                 $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
181                 $smsg->doc_id($doc_id);
182         }
183         $smsg;
184 }
185
186 sub find_unique_doc_id {
187         my ($self, $term, $value) = @_;
188
189         my ($begin, $end) = $self->find_doc_ids($term, $value);
190
191         return undef if $begin->equal($end); # not found
192
193         my $rv = $begin->get_docid;
194
195         # sanity check
196         $begin->inc;
197         $begin->equal($end) or die "Term '$term:$value' is not unique\n";
198         $rv;
199 }
200
201 # returns begin and end PostingIterator
202 sub find_doc_ids {
203         my ($self, $term, $value) = @_;
204
205         $self->find_doc_ids_for_term(xpfx($term) . $value);
206 }
207
208 # returns begin and end PostingIterator
209 sub find_doc_ids_for_term {
210         my ($self, $term) = @_;
211         my $db = $self->{xdb};
212
213         ($db->postlist_begin($term), $db->postlist_end($term));
214 }
215
216 # normalize subjects so they are suitable as pathnames for URLs
217 sub subject_path {
218         my $subj = pop;
219         $subj = subject_normalized($subj);
220         $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
221         lc($subj);
222 }
223
224 sub subject_normalized {
225         my $subj = pop;
226         $subj =~ s/\A\s+//s; # no leading space
227         $subj =~ s/\s+\z//s; # no trailing space
228         $subj =~ s/\s+/ /gs; # no redundant spaces
229         $subj =~ s/\.+\z//; # no trailing '.'
230         $subj =~ s/$REPLY_RE//igo; # remove reply prefix
231         $subj;
232 }
233
234 sub enquire {
235         my ($self) = @_;
236         $self->{enquire} ||= Search::Xapian::Enquire->new($self->{xdb});
237 }
238
239 1;