]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
search: expand "d:" to "dt:" for precision with approxidate
[public-inbox.git] / lib / PublicInbox / Search.pm
1 # Copyright (C) 2015-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 # based on notmuch, but with no concept of folders, files or flags
4 #
5 # Read-only search interface for use by the web and NNTP interfaces
6 package PublicInbox::Search;
7 use strict;
8 use parent qw(Exporter);
9 our @EXPORT_OK = qw(retry_reopen int_val get_pct xap_terms);
10 use List::Util qw(max);
11 use POSIX qw(strftime);
12
13 # values for searching, changing the numeric value breaks
14 # compatibility with old indices (so don't change them it)
15 use constant {
16         TS => 0, # Received: in Unix time (IMAP INTERNALDATE, JMAP receivedAt)
17         YYYYMMDD => 1, # Date: header for searching in the WWW UI
18         DT => 2, # Date: YYYYMMDDHHMMSS (IMAP SENT*, JMAP sentAt)
19
20         # added for public-inbox 1.6.0+
21         BYTES => 3, # IMAP RFC822.SIZE
22         UID => 4, # IMAP UID == NNTP article number == Xapian docid
23         THREADID => 5, # RFC 8474, RFC 8621
24
25         # TODO
26         # REPLYCNT => ?, # IMAP ANSWERED
27
28         # SCHEMA_VERSION history
29         # 0 - initial
30         # 1 - subject_path is lower-cased
31         # 2 - subject_path is id_compress in the index, only
32         # 3 - message-ID is compressed if it includes '%' (hack!)
33         # 4 - change "Re: " normalization, avoid circular Reference ghosts
34         # 5 - subject_path drops trailing '.'
35         # 6 - preserve References: order in document data
36         # 7 - remove references and inreplyto terms
37         # 8 - remove redundant/unneeded document data
38         # 9 - disable Message-ID compression (SHA-1)
39         # 10 - optimize doc for NNTP overviews
40         # 11 - merge threads when vivifying ghosts
41         # 12 - change YYYYMMDD value column to numeric
42         # 13 - fix threading for empty References/In-Reply-To
43         #      (commit 83425ef12e4b65cdcecd11ddcb38175d4a91d5a0)
44         # 14 - fix ghost root vivification
45         # 15 - see public-inbox-v2-format(5)
46         #      further bumps likely unnecessary, we'll suggest in-place
47         #      "--reindex" use for further fixes and tweaks:
48         #
49         #      public-inbox v1.5.0 adds (still SCHEMA_VERSION=15):
50         #      * "lid:" and "l:" for List-Id searches
51         #
52         #      v1.6.0 adds BYTES, UID and THREADID values
53         SCHEMA_VERSION => 15,
54 };
55
56 use PublicInbox::Smsg;
57 use PublicInbox::Over;
58 our $QP_FLAGS;
59 our %X = map { $_ => 0 } qw(BoolWeight Database Enquire QueryParser Stem Query);
60 our $Xap; # 'Search::Xapian' or 'Xapian'
61 our $NVRP; # '$Xap::'.('NumberValueRangeProcessor' or 'NumberRangeProcessor')
62
63 # ENQ_DESCENDING and ENQ_ASCENDING weren't in SWIG Xapian.pm prior to 1.4.16,
64 # let's hope the ABI is stable
65 our $ENQ_DESCENDING = 0;
66 our $ENQ_ASCENDING = 1;
67
68 sub load_xapian () {
69         return 1 if defined $Xap;
70         # n.b. PI_XAPIAN is intended for development use only.  We still
71         # favor Search::Xapian since that's what's available in current
72         # Debian stable (10.x) and derived distros.
73         for my $x (($ENV{PI_XAPIAN} // 'Search::Xapian'), 'Xapian') {
74                 eval "require $x";
75                 next if $@;
76
77                 $x->import(qw(:standard));
78                 $Xap = $x;
79
80                 # `version_string' was added in Xapian 1.1
81                 my $xver = eval('v'.eval($x.'::version_string()')) //
82                                 eval('v'.eval($x.'::xapian_version_string()'));
83
84                 # NumberRangeProcessor was added in Xapian 1.3.6,
85                 # NumberValueRangeProcessor was removed for 1.5.0+,
86                 # favor the older /Value/ variant since that's what our
87                 # (currently) preferred Search::Xapian supports
88                 $NVRP = $x.'::'.($x eq 'Xapian' && $xver ge v1.5 ?
89                         'NumberRangeProcessor' : 'NumberValueRangeProcessor');
90                 $X{$_} = $Xap.'::'.$_ for (keys %X);
91
92                 *sortable_serialise = $x.'::sortable_serialise';
93                 *sortable_unserialise = $x.'::sortable_unserialise';
94                 # n.b. FLAG_PURE_NOT is expensive not suitable for a public
95                 # website as it could become a denial-of-service vector
96                 # FLAG_PHRASE also seems to cause performance problems chert
97                 # (and probably earlier Xapian DBs).  glass seems fine...
98                 # TODO: make this an option, maybe?
99                 # or make indexlevel=medium as default
100                 $QP_FLAGS = FLAG_PHRASE() | FLAG_BOOLEAN() | FLAG_LOVEHATE() |
101                                 FLAG_WILDCARD();
102                 return 1;
103         }
104         undef;
105 }
106
107 # This is English-only, everything else is non-standard and may be confused as
108 # a prefix common in patch emails
109 our $LANG = 'english';
110
111 # note: the non-X term prefix allocations are shared with
112 # Xapian omega, see xapian-applications/omega/docs/termprefixes.rst
113 my %bool_pfx_external = (
114         mid => 'Q', # Message-ID (full/exact), this is mostly uniQue
115         lid => 'G', # newsGroup (or similar entity), just inside <>
116         dfpre => 'XDFPRE',
117         dfpost => 'XDFPOST',
118         dfblob => 'XDFPRE XDFPOST',
119 );
120
121 my $non_quoted_body = 'XNQ XDFN XDFA XDFB XDFHH XDFCTX XDFPRE XDFPOST';
122 my %prob_prefix = (
123         # for mairix compatibility
124         s => 'S',
125         m => 'XM', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
126         l => 'XL', # 'lid:' (bool) is exact, 'l:' (prob) can do partial
127         f => 'A',
128         t => 'XTO',
129         tc => 'XTO XCC',
130         c => 'XCC',
131         tcf => 'XTO XCC A',
132         a => 'XTO XCC A',
133         b => $non_quoted_body . ' XQUOT',
134         bs => $non_quoted_body . ' XQUOT S',
135         n => 'XFN',
136
137         q => 'XQUOT',
138         nq => $non_quoted_body,
139         dfn => 'XDFN',
140         dfa => 'XDFA',
141         dfb => 'XDFB',
142         dfhh => 'XDFHH',
143         dfctx => 'XDFCTX',
144
145         # default:
146         '' => 'XM S A XQUOT XFN ' . $non_quoted_body,
147 );
148
149 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
150 # not documenting lid: for now, either, it is probably redundant with l:,
151 # especially since we don't offer boolean searches for To/Cc/From
152 # headers, either
153 our @HELP = (
154         's:' => 'match within Subject  e.g. s:"a quick brown fox"',
155         'd:' => <<EOF,
156 date range as YYYYMMDD  e.g. d:19931002..20101002
157 Open-ended ranges such as d:19931002.. and d:..20101002
158 are also supported
159 EOF
160         'dt:' => <<EOF,
161 date-time range as YYYYMMDDhhmmss (e.g. dt:19931002011000..19931002011200)
162 EOF
163         'b:' => 'match within message body, including text attachments',
164         'nq:' => 'match non-quoted text within message body',
165         'q:' => 'match quoted text within message body',
166         'n:' => 'match filename of attachment(s)',
167         't:' => 'match within the To header',
168         'c:' => 'match within the Cc header',
169         'f:' => 'match within the From header',
170         'a:' => 'match within the To, Cc, and From headers',
171         'tc:' => 'match within the To and Cc headers',
172         'l:' => 'match contents of the List-Id header',
173         'bs:' => 'match within the Subject and body',
174         'dfn:' => 'match filename from diff',
175         'dfa:' => 'match diff removed (-) lines',
176         'dfb:' => 'match diff added (+) lines',
177         'dfhh:' => 'match diff hunk header context (usually a function name)',
178         'dfctx:' => 'match diff context lines',
179         'dfpre:' => 'match pre-image git blob ID',
180         'dfpost:' => 'match post-image git blob ID',
181         'dfblob:' => 'match either pre or post-image git blob ID',
182 );
183 chomp @HELP;
184
185 sub xdir ($;$) {
186         my ($self, $rdonly) = @_;
187         if ($rdonly || !defined($self->{shard})) {
188                 $self->{xpfx};
189         } else { # v2 only:
190                 "$self->{xpfx}/$self->{shard}";
191         }
192 }
193
194 # returns all shards as separate Xapian::Database objects w/o combining
195 sub xdb_shards_flat ($) {
196         my ($self) = @_;
197         my $xpfx = $self->{xpfx};
198         my (@xdb, $slow_phrase);
199         load_xapian();
200         $self->{qp_flags} //= $QP_FLAGS;
201         if ($xpfx =~ m/xapian${\SCHEMA_VERSION}\z/) {
202                 @xdb = ($X{Database}->new($xpfx));
203                 $self->{qp_flags} |= FLAG_PHRASE() if !-f "$xpfx/iamchert";
204         } else {
205                 opendir(my $dh, $xpfx) or return (); # not initialized yet
206                 # We need numeric sorting so shard[0] is first for reading
207                 # Xapian metadata, if needed
208                 my $last = max(grep(/\A[0-9]+\z/, readdir($dh))) // return ();
209                 for (0..$last) {
210                         my $shard_dir = "$self->{xpfx}/$_";
211                         push @xdb, $X{Database}->new($shard_dir);
212                         $slow_phrase ||= -f "$shard_dir/iamchert";
213                 }
214                 $self->{qp_flags} |= FLAG_PHRASE() if !$slow_phrase;
215         }
216         @xdb;
217 }
218
219 # v2 Xapian docids don't conflict, so they're identical to
220 # NNTP article numbers and IMAP UIDs.
221 # https://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
222 sub mdocid {
223         my ($nshard, $mitem) = @_;
224         my $docid = $mitem->get_docid;
225         int(($docid - 1) / $nshard) + 1;
226 }
227
228 sub mset_to_artnums {
229         my ($self, $mset) = @_;
230         my $nshard = $self->{nshard};
231         [ map { mdocid($nshard, $_) } $mset->items ];
232 }
233
234 sub xdb ($) {
235         my ($self) = @_;
236         $self->{xdb} //= do {
237                 my @xdb = $self->xdb_shards_flat or return;
238                 $self->{nshard} = scalar(@xdb);
239                 my $xdb = shift @xdb;
240                 $xdb->add_database($_) for @xdb;
241                 $xdb;
242         };
243 }
244
245 sub new {
246         my ($class, $ibx) = @_;
247         ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
248         my $xap = $ibx->version > 1 ? 'xap' : 'public-inbox/xapian';
249         bless {
250                 xpfx => "$ibx->{inboxdir}/$xap" . SCHEMA_VERSION,
251                 altid => $ibx->{altid},
252         }, $class;
253 }
254
255 sub reopen {
256         my ($self) = @_;
257         if (my $xdb = $self->{xdb}) {
258                 $xdb->reopen;
259         }
260         $self; # make chaining easier
261 }
262
263 # Convert git "approxidate" ranges to something usable with our
264 # Xapian indices.  At the moment, Xapian only offers a C++-only API
265 # and neither the SWIG nor XS bindings allow us to use custom code
266 # to parse dates (and libgit2 doesn't expose git__date_parse, either,
267 # so we're running git-rev-parse(1)).
268 # This replaces things we need to send to $git->date_parse with
269 # "\0".$strftime_format.['+'|$idx]."\0" placeholders
270 sub date_parse_prepare {
271         my ($to_parse, $pfx, $range) = @_;
272         # are we inside a parenthesized statement?
273         my $end = $range =~ s/([\)\s]*)\z// ? $1 : '';
274         my @r = split(/\.\./, $range, 2);
275
276         # expand "d:20101002" => "d:20101002..20101003" and like
277         # n.b. git doesn't do YYYYMMDD w/o '-', it needs YYYY-MM-DD
278         # We upgrade "d:" to "dt:" to iff using approxidate
279         if ($pfx eq 'd') {
280                 my $fmt = "\0%Y%m%d";
281                 if (!defined($r[1])) {
282                         if ($r[0] =~ /\A([0-9]{4})([0-9]{2})([0-9]{2})\z/) {
283                                 push @$to_parse, "$1-$2-$3";
284                                 # we could've handled as-is, but we need
285                                 # to parse anyways for "d+" below
286                         } else {
287                                 push @$to_parse, $r[0];
288                                 if ($r[0] !~ /\A[0-9]{4}-[0-9]{2}-[0-9]{2}\z/) {
289                                         $pfx = 'dt';
290                                         $fmt = "\0%Y%m%d%H%M%S";
291                                 }
292                         }
293                         $r[0] = "$fmt+$#$to_parse\0";
294                         $r[1] = "$fmt+\0";
295                 } else {
296                         for my $x (@r) {
297                                 next if $x eq '' || $x =~ /\A[0-9]{8}\z/;
298                                 push @$to_parse, $x;
299                                 if ($x !~ /\A[0-9]{4}-[0-9]{2}-[0-9]{2}\z/) {
300                                         $pfx = 'dt';
301                                 }
302                                 $x = "$fmt$#$to_parse\0";
303                         }
304                         if ($pfx eq 'dt') {
305                                 for (@r) {
306                                         s/\0%Y%m%d/\0%Y%m%d%H%M%S/;
307                                         s/\A([0-9]{8})\z/${1}000000/;
308                                 }
309                         }
310                 }
311         } elsif ($pfx eq 'dt') {
312                 if (!defined($r[1])) { # git needs gaps and not /\d{14}/
313                         if ($r[0] =~ /\A([0-9]{4})([0-9]{2})([0-9]{2})
314                                         ([0-9]{2})([0-9]{2})([0-9]{2})\z/x) {
315                                 push @$to_parse, "$1-$2-$3 $4:$5:$6";
316                         } else {
317                                 push @$to_parse, $r[0];
318                         }
319                         $r[0] = "\0%Y%m%d%H%M%S$#$to_parse\0";
320                         $r[1] = "\0%Y%m%d%H%M%S+\0";
321                 } else {
322                         for my $x (@r) {
323                                 next if $x eq '' || $x =~ /\A[0-9]{14}\z/;
324                                 push @$to_parse, $x;
325                                 $x = "\0%Y%m%d%H%M%S$#$to_parse\0";
326                         }
327                 }
328         } else { # "rt", let git interpret "YYYY", deal with Y10K later :P
329                 for my $x (@r) {
330                         next if $x eq '' || $x =~ /\A[0-9]{5,}\z/;
331                         push @$to_parse, $x;
332                         $x = "\0%s$#$to_parse\0";
333                 }
334                 $r[1] //= "\0%s+\0";
335         }
336         "$pfx:".join('..', @r).$end;
337 }
338
339 sub date_parse_finalize {
340         my ($git, $to_parse) = @_;
341         # git-rev-parse can handle any number of args up to system
342         # limits (around (4096*32) bytes on Linux).
343         my @r = $git->date_parse(@$to_parse);
344         my $i;
345         $_[2] =~ s/\0(%[%YmdHMSs]+)([0-9\+]+)\0/strftime($1,
346                 gmtime($2 eq '+' ? ($r[$i]+86400) : $r[$i=$2+0]))/sge;
347 }
348
349 # n.b. argv never has NUL, though we'll need to filter it out
350 # if this $argv isn't from a command execution
351 sub query_argv_to_string {
352         my (undef, $git, $argv) = @_;
353         my $to_parse;
354         my $tmp = join(' ', map {;
355                 if (s!\b(d|rt|dt):(\S+)\z!date_parse_prepare(
356                                                 $to_parse //= [], $1, $2)!sge) {
357                         $_;
358                 } elsif (/\s/) {
359                         s/(.*?)\b(\w+:)// ? qq{$1$2"$_"} : qq{"$_"};
360                 } else {
361                         $_
362                 }
363         } @$argv);
364         date_parse_finalize($git, $to_parse, $tmp) if $to_parse;
365         $tmp
366 }
367
368 # this is for the WWW "q=" query parameter and "lei q --stdin"
369 # it can't do d:"5 days ago", but it will do d:5.days.ago
370 sub query_approxidate {
371         my (undef, $git) = @_; # $_[2] = $query_string (modified in-place)
372         my $DQ = qq<"\x{201c}\x{201d}>; # Xapian can use curly quotes
373         $_[2] =~ tr/\x00/ /; # Xapian doesn't do NUL, we use it as a placeholder
374         my ($terms, $phrase, $to_parse);
375         $_[2] =~ s{([^$DQ]*)([$DQ][^$DQ]*[$DQ])?}{
376                 ($terms, $phrase) = ($1, $2);
377                 $terms =~ s!\b(d|rt|dt):(\S+)!
378                         date_parse_prepare($to_parse //= [], $1, $2)!sge;
379                 $terms.($phrase // '');
380                 }sge;
381         date_parse_finalize($git, $to_parse, $_[2]) if $to_parse;
382 }
383
384 # read-only
385 sub mset {
386         my ($self, $query_string, $opts) = @_;
387         $opts ||= {};
388         my $qp = $self->{qp} //= $self->qparse_new;
389         my $query = $qp->parse_query($query_string, $self->{qp_flags});
390         _do_enquire($self, $query, $opts);
391 }
392
393 sub retry_reopen {
394         my ($self, $cb, @arg) = @_;
395         for my $i (1..10) {
396                 if (wantarray) {
397                         my @ret;
398                         eval { @ret = $cb->($self, @arg) };
399                         return @ret unless $@;
400                 } else {
401                         my $ret;
402                         eval { $ret = $cb->($self, @arg) };
403                         return $ret unless $@;
404                 }
405                 # Exception: The revision being read has been discarded -
406                 # you should call Xapian::Database::reopen()
407                 if (ref($@) =~ /\bDatabaseModifiedError\b/) {
408                         warn "reopen try #$i on $@\n";
409                         reopen($self);
410                 } else {
411                         # let caller decide how to spew, because ExtMsg queries
412                         # get wonky and trigger:
413                         # "something terrible happened at .../Xapian/Enquire.pm"
414                         die;
415                 }
416         }
417         die "Too many Xapian database modifications in progress\n";
418 }
419
420 sub _do_enquire {
421         my ($self, $query, $opts) = @_;
422         retry_reopen($self, \&_enquire_once, $query, $opts);
423 }
424
425 # returns true if all docs have the THREADID value
426 sub has_threadid ($) {
427         my ($self) = @_;
428         (xdb($self)->get_metadata('has_threadid') // '') eq '1';
429 }
430
431 sub _enquire_once { # retry_reopen callback
432         my ($self, $query, $opts) = @_;
433         my $xdb = xdb($self);
434         if (defined(my $eidx_key = $opts->{eidx_key})) {
435                 $query = $X{Query}->new(OP_FILTER(), $query, 'O'.$eidx_key);
436         }
437         if (defined(my $uid_range = $opts->{uid_range})) {
438                 my $range = $X{Query}->new(OP_VALUE_RANGE(), UID,
439                                         sortable_serialise($uid_range->[0]),
440                                         sortable_serialise($uid_range->[1]));
441                 $query = $X{Query}->new(OP_FILTER(), $query, $range);
442         }
443         my $enquire = $X{Enquire}->new($xdb);
444         $enquire->set_query($query);
445         $opts ||= {};
446         my $rel = $opts->{relevance} // 0;
447         if ($rel == -2) { # ORDER BY docid/UID (highest first)
448                 $enquire->set_weighting_scheme($X{BoolWeight}->new);
449                 $enquire->set_docid_order($ENQ_DESCENDING);
450         } elsif ($rel == -1) { # ORDER BY docid/UID (lowest first)
451                 $enquire->set_weighting_scheme($X{BoolWeight}->new);
452                 $enquire->set_docid_order($ENQ_ASCENDING);
453         } elsif ($rel == 0) {
454                 $enquire->set_sort_by_value_then_relevance(TS, !$opts->{asc});
455         } else { # rel > 0
456                 $enquire->set_sort_by_relevance_then_value(TS, !$opts->{asc});
457         }
458
459         # `mairix -t / --threads' or JMAP collapseThreads
460         if ($opts->{threads} && has_threadid($self)) {
461                 $enquire->set_collapse_key(THREADID);
462         }
463         $enquire->get_mset($opts->{offset} || 0, $opts->{limit} || 50);
464 }
465
466 sub mset_to_smsg {
467         my ($self, $ibx, $mset) = @_;
468         my $nshard = $self->{nshard};
469         my $i = 0;
470         my %order = map { mdocid($nshard, $_) => ++$i } $mset->items;
471         my @msgs = sort {
472                 $order{$a->{num}} <=> $order{$b->{num}}
473         } @{$ibx->over->get_all(keys %order)};
474         wantarray ? ($mset->get_matches_estimated, \@msgs) : \@msgs;
475 }
476
477 # read-write
478 sub stemmer { $X{Stem}->new($LANG) }
479
480 # read-only
481 sub qparse_new {
482         my ($self) = @_;
483
484         my $xdb = xdb($self);
485         my $qp = $X{QueryParser}->new;
486         $qp->set_default_op(OP_AND());
487         $qp->set_database($xdb);
488         $qp->set_stemmer(stemmer($self));
489         $qp->set_stemming_strategy(STEM_SOME());
490         my $cb = $qp->can('set_max_wildcard_expansion') //
491                 $qp->can('set_max_expansion'); # Xapian 1.5.0+
492         $cb->($qp, 100);
493         $cb = $qp->can('add_valuerangeprocessor') //
494                 $qp->can('add_rangeprocessor'); # Xapian 1.5.0+
495         $cb->($qp, $NVRP->new(YYYYMMDD, 'd:'));
496         $cb->($qp, $NVRP->new(DT, 'dt:'));
497
498         # for IMAP, undocumented for WWW and may be split off go away
499         $cb->($qp, $NVRP->new(BYTES, 'z:'));
500         $cb->($qp, $NVRP->new(TS, 'rt:'));
501         $cb->($qp, $NVRP->new(UID, 'uid:'));
502
503         while (my ($name, $prefix) = each %bool_pfx_external) {
504                 $qp->add_boolean_prefix($name, $_) foreach split(/ /, $prefix);
505         }
506
507         # we do not actually create AltId objects,
508         # just parse the spec to avoid the extra DB handles for now.
509         if (my $altid = $self->{altid}) {
510                 my $user_pfx = $self->{-user_pfx} = [];
511                 for (@$altid) {
512                         # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
513                         # note: Xapian supports multibyte UTF-8, /^[0-9]+$/,
514                         # and '_' with prefixes matching \w+
515                         /\Aserial:(\w+):/ or next;
516                         my $pfx = $1;
517                         push @$user_pfx, "$pfx:", <<EOF;
518 alternate serial number  e.g. $pfx:12345 (boolean)
519 EOF
520                         # gmane => XGMANE
521                         $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
522                 }
523                 chomp @$user_pfx;
524         }
525
526         while (my ($name, $prefix) = each %prob_prefix) {
527                 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
528         }
529         $qp;
530 }
531
532 sub help {
533         my ($self) = @_;
534         $self->{qp} //= $self->qparse_new; # parse altids
535         my @ret = @HELP;
536         if (my $user_pfx = $self->{-user_pfx}) {
537                 push @ret, @$user_pfx;
538         }
539         \@ret;
540 }
541
542 sub int_val ($$) {
543         my ($doc, $col) = @_;
544         my $val = $doc->get_value($col) or return; # undefined is '' in Xapian
545         sortable_unserialise($val) + 0; # PV => IV conversion
546 }
547
548 sub get_pct ($) { # mset item
549         # Capped at "99%" since "100%" takes an extra column in the
550         # thread skeleton view.  <xapian/mset.h> says the value isn't
551         # very meaningful, anyways.
552         my $n = $_[0]->get_percent;
553         $n > 99 ? 99 : $n;
554 }
555
556 sub xap_terms ($$;@) {
557         my ($pfx, $xdb_or_doc, @docid) = @_; # @docid may be empty ()
558         my %ret;
559         eval {
560                 my $end = $xdb_or_doc->termlist_end(@docid);
561                 my $cur = $xdb_or_doc->termlist_begin(@docid);
562                 for (; $cur != $end; $cur++) {
563                         $cur->skip_to($pfx);
564                         last if $cur == $end;
565                         my $tn = $cur->get_termname;
566                         if (index($tn, $pfx) == 0) {
567                                 $ret{substr($tn, length($pfx))} = undef;
568                         }
569                 }
570         };
571         \%ret;
572 }
573
574 1;