]> sipb.mit.edu Git - ikiwiki.git/blob - doc/todo/different_search_engine.mdwn
Merge branch 'master' of ssh://git.ikiwiki.info/srv/git/ikiwiki.info
[ikiwiki.git] / doc / todo / different_search_engine.mdwn
1 After using it for a while, my feeling is that [[hyperestraier]], as used in
2 the [[plugins/search]] plugin, is not robust enough for ikiwiki. It doesn't
3 upgrade well, and it has a habit of sig-11 on certain input from time to
4 time.
5
6 So some other engine should be found and used instead. 
7
8 Enrico had one that he was using for debtags stuff that looked pretty good.
9 That was [Xapian](http://www.xapian.org/), which has perl bindings in
10 libsearch-xapian-perl. The nice thing about xapian is that it does a ranked
11 search so it understands what words are most important in a search. (So
12 does Lucene..) Another nice thing is it supports "more documents like this
13 one" kind of search. --[[Joey]]
14
15 ## xapian
16
17 I've invesitgated xapian briefly. I think a custom xapian indexer and use
18 of the omega for cgi searches could work well for ikiwiki. --[[Joey]]
19
20 ### indexer
21
22 A custom indexer is needed because omindex isn't good enough for ikiwiki's
23 needs for incremental rendering. (And because, since ikiwiki has page info
24 in memory, it's silly to write it to disk and have omindex read it back.)
25
26 The indexer would run as a ikiwiki hook. It needs to be passed the page
27 name, and the content. Which hook to use is an open question.
28 Possibilities:
29
30 * `filter` - Since this runs before preprocess, only the actual text
31   written on the page would be indexed. Not text generated by directives,
32   pulled in by inlining, etc. There's something to be said for that. And
33   something to be said against it. It would also get markdown formatted
34   content, mostly, though it would still need to strip html.
35 * `sanitize` - Would get the htmlized content, so would need to strip html.
36   Preprocessor directive output would be indexed.
37 * `format` - Would get the entire html page, including the page template.
38   Probably not a good choice as indexing the same template for each page
39   is unnecessary.
40
41 Currently, a filter hook seems the best option.
42
43 The hook would remove any html from the content, and index it.
44 It would need to add the same document data that omindex would, as well as
45 adding the same special terms (see
46 http://xapian.org/docs/omega/overview.html "Boolean terms").
47
48 (Note that the U term is a bit tricky because I'll have to replicate
49 ominxes's hash_string() to hash terms > 240 chars.)
50
51 The indexer (and deleter) will need a way to figure out the ids in xapian
52 of the documents to delete. One way is storing the id of each page in the
53 ikiwiki index.
54
55 The other way would be adding a special term to the xapian db that can be
56 used with replace_document_by_term/delete_document_by_term. omindex uses
57 U<url> as a term, and I guess I could just use that, and then map page
58 names to urls when deleting a page  ... only real problem being the
59 hashing; a collision would be bad.
60
61 At the moment, storing xapian ids in the ikiwiki index file seems like the
62 best approach.
63
64 The hook should try to avoid re-indexing pages that have not changed since
65 they were last indexed. One problem is that, if a page with an inline is
66 built, every inlined item will get each hook run. And so a naive hook would
67 index each of those items, even though none of them have necessarily
68 changed. Date stamps are one possibility. Another would be to avoid having
69 the hook not do any indexing when `%preprocessing` is set (Ikiwiki.pm would
70 need to expose that variable.) Another approach would be to use a
71 needsbuild hook and only index the pages that are being built.
72
73 #### cgi
74
75 The cgi hook would exec omega to handle the searching, much as is done
76 with estseek in the current search plugin.
77
78 It would first set `OMEGA_CONFIG_FILE=.ikiwiki/omega.conf` ; that omega.conf
79 would set `database_dir=.ikiwiki/xapian` and probably also set a custom
80 `template_dir`, which would have modified templates branded for ikiwiki. So
81 the actual xapian db would be in `.ikiwiki/xapian/default/`.
82
83 ## lucene
84
85 >> I've done a bit of prototyping on this. The current hip search library is [Lucene](http://lucene.apache.org/java/docs/). There's a Perl port called [Plucene](http://search.cpan.org/~tmtm/Plucene-1.25/). Given that it's already packaged, as `libplucene-perl`, I assumed it would be a good starting point. I've written a **very rough** patch against `IkiWiki/Plugin/search.pm` to handle the indexing side (there's no facility to view the results yet, although I have a command-line interface working). That's below, and should apply to SVN trunk.
86
87 >> Of course, there are problems. ;-)
88
89 >> * Plucene throws up a warning when running under Taint mode. There's a patch on the mailing list, but I haven't tried applying it yet. So for now you'll have to build IkiWiki with `NOTAINT=1 make install`.
90 >> * If I kill `ikiwiki` while it's indexing, I can screw up Plucene's locks. I suspect that this will be an easy fix.
91
92 >> There is a [C++ port of Lucene](http://sourceforge.net/projects/clucene/) which is packaged as `libclucene0`. The Perl interface to this is called [Lucene](http://search.cpan.org/~tbusch/Lucene-0.09/lib/Lucene.pm). This is supposed to be significantly faster, and presumably won't have the taint bug. The API is virtually the same, so it will be easy to switch over. I'd use this now, were it not for the lack of package. (I assume you won't want to make core functionality depend on installing a module from CPAN). I've never built a Debian package before, so I can either learn then try building this, or somebody else could do the honours. ;-)
93
94 >> If this seems a sensible approach, I'll write the CGI interface, and clean up the plugin. -- Ben
95
96 >>> The weird thing about lucene is that these are all reimplmentations of
97 >>> it. Thank you java.. The C++ version seems like a better choice to me
98 >>> (packages are trivial). --[[Joey]]
99
100 > Might I suggest renaming the "search" plugin to "hyperestraier", and then creating new search plugins for different engines?  No reason to pick a single replacement. --[[JoshTriplett]]
101
102 <pre>
103 Index: IkiWiki/Plugin/search.pm
104 ===================================================================
105 --- IkiWiki/Plugin/search.pm    (revision 2755)
106 +++ IkiWiki/Plugin/search.pm    (working copy)
107 @@ -1,33 +1,55 @@
108  #!/usr/bin/perl
109 -# hyperestraier search engine plugin
110  package IkiWiki::Plugin::search;
111  
112  use warnings;
113  use strict;
114  use IkiWiki;
115  
116 +use Plucene::Analysis::SimpleAnalyzer;
117 +use Plucene::Document;
118 +use Plucene::Document::Field;
119 +use Plucene::Index::Reader;
120 +use Plucene::Index::Writer;
121 +use Plucene::QueryParser;
122 +use Plucene::Search::HitCollector;
123 +use Plucene::Search::IndexSearcher;
124 +
125 +#TODO: Run the Plucene optimiser after a rebuild
126 +#TODO: CGI query interface
127 +
128 +my $PLUCENE_DIR;
129 +# $config{wikistatedir} may not be defined at this point, so we delay setting $PLUCENE_DIR
130 +# until a subroutine actually needs it.
131 +sub init () {
132 +  error("Plucene: Statedir <$config{wikistatedir}> does not exist!") 
133 +    unless -e $config{wikistatedir};
134 +  $PLUCENE_DIR = $config{wikistatedir}.'/plucene';  
135 +}
136 +
137  sub import { #{{{
138 -       hook(type => "getopt", id => "hyperestraier",
139 -               call => \&amp;getopt);
140 -       hook(type => "checkconfig", id => "hyperestraier",
141 +       hook(type => "checkconfig", id => "plucene",
142                 call => \&amp;checkconfig);
143 -       hook(type => "pagetemplate", id => "hyperestraier",
144 -               call => \&amp;pagetemplate);
145 -       hook(type => "delete", id => "hyperestraier",
146 +       hook(type => "delete", id => "plucene",
147                 call => \&amp;delete);
148 -       hook(type => "change", id => "hyperestraier",
149 +       hook(type => "change", id => "plucene",
150                 call => \&amp;change);
151 -       hook(type => "cgi", id => "hyperestraier",
152 -               call => \&amp;cgi);
153  } # }}}
154  
155 -sub getopt () { #{{{
156 -        eval q{use Getopt::Long};
157 -       error($@) if $@;
158 -        Getopt::Long::Configure('pass_through');
159 -        GetOptions("estseek=s" => \$config{estseek});
160 -} #}}}
161  
162 +sub writer {
163 +  init();
164 +  return Plucene::Index::Writer->new(
165 +      $PLUCENE_DIR, Plucene::Analysis::SimpleAnalyzer->new(), 
166 +      (-e "$PLUCENE_DIR/segments" ? 0 : 1));
167 +}
168 +
169 +#TODO: Better name for this function.
170 +sub src2rendered_abs (@) {
171 +  return map { Encode::encode_utf8($config{destdir}."/$_") } 
172 +    map { @{$renderedfiles{pagename($_)}} } 
173 +    grep { defined pagetype($_) } @_;
174 +}
175 +
176  sub checkconfig () { #{{{
177         foreach my $required (qw(url cgiurl)) {
178                 if (! length $config{$required}) {
179 @@ -36,112 +58,55 @@
180         }
181  } #}}}
182  
183 -my $form;
184 -sub pagetemplate (@) { #{{{
185 -       my %params=@_;
186 -       my $page=$params{page};
187 -       my $template=$params{template};
188 +#my $form;
189 +#sub pagetemplate (@) { #{{{
190 +#      my %params=@_;
191 +#      my $page=$params{page};
192 +#      my $template=$params{template};
193 +#
194 +#      # Add search box to page header.
195 +#      if ($template->query(name => "searchform")) {
196 +#              if (! defined $form) {
197 +#                      my $searchform = template("searchform.tmpl", blind_cache => 1);
198 +#                      $searchform->param(searchaction => $config{cgiurl});
199 +#                      $form=$searchform->output;
200 +#              }
201 +#
202 +#              $template->param(searchform => $form);
203 +#      }
204 +#} #}}}
205  
206 -       # Add search box to page header.
207 -       if ($template->query(name => "searchform")) {
208 -               if (! defined $form) {
209 -                       my $searchform = template("searchform.tmpl", blind_cache => 1);
210 -                       $searchform->param(searchaction => $config{cgiurl});
211 -                       $form=$searchform->output;
212 -               }
213 -
214 -               $template->param(searchform => $form);
215 -       }
216 -} #}}}
217 -
218  sub delete (@) { #{{{
219 -       debug(gettext("cleaning hyperestraier search index"));
220 -       estcmd("purge -cl");
221 -       estcfg();
222 +       debug("Plucene: purging: ".join(',',@_));
223 +       init();
224 +  my $reader = Plucene::Index::Reader->open($PLUCENE_DIR);
225 +  my @files = src2rendered_abs(@_);
226 +  for (@files) {
227 +    $reader->delete_term( Plucene::Index::Term->new({ field => "id", text => $_ }));
228 +  }
229 +  $reader->close;
230  } #}}}
231  
232  sub change (@) { #{{{
233 -       debug(gettext("updating hyperestraier search index"));
234 -       estcmd("gather -cm -bc -cl -sd",
235 -               map {
236 -                       Encode::encode_utf8($config{destdir}."/".$_)
237 -                               foreach @{$renderedfiles{pagename($_)}};
238 -               } @_
239 -       );
240 -       estcfg();
241 +       debug("Plucene: updating search index");
242 +  init();
243 +  #TODO: Do we want to index source or rendered files?
244 +  #TODO: Store author, tags, etc. in distinct fields; may need new API hook.
245 +  my @files = src2rendered_abs(@_);
246 +  my $writer = writer();    
247 +   
248 +  for my $file (@files) {
249 +    my $doc = Plucene::Document->new;
250 +    $doc->add(Plucene::Document::Field->Keyword(id => $file));
251 +    my $data;
252 +    eval { $data = readfile($file) };
253 +    if ($@) {
254 +      debug("Plucene: can't read <$file> - $@");
255 +      next;
256 +    }
257 +    debug("Plucene: indexing <$file> (".length($data).")");
258 +    $doc->add(Plucene::Document::Field->UnStored('text' => $data));
259 +    $writer->add_document($doc);
260 +  }
261  } #}}}
262 -
263 -sub cgi ($) { #{{{
264 -       my $cgi=shift;
265 -
266 -       if (defined $cgi->param('phrase') || defined $cgi->param("navi")) {
267 -               # only works for GET requests
268 -               chdir("$config{wikistatedir}/hyperestraier") || error("chdir: $!");
269 -               exec("./".IkiWiki::basename($config{cgiurl})) || error("estseek.cgi failed");
270 -       }
271 -} #}}}
272 -
273 -my $configured=0;
274 -sub estcfg () { #{{{
275 -       return if $configured;
276 -       $configured=1;
277 -
278 -       my $estdir="$config{wikistatedir}/hyperestraier";
279 -       my $cgi=IkiWiki::basename($config{cgiurl});
280 -       $cgi=~s/\..*$//;
281 -
282 -       my $newfile="$estdir/$cgi.tmpl.new";
283 -       my $cleanup = sub { unlink($newfile) };
284 -       open(TEMPLATE, ">:utf8", $newfile) || error("open $newfile: $!", $cleanup);
285 -       print TEMPLATE IkiWiki::misctemplate("search", 
286 -               "<!--ESTFORM-->\n\n<!--ESTRESULT-->\n\n<!--ESTINFO-->\n\n",
287 -               baseurl => IkiWiki::dirname($config{cgiurl})."/") ||
288 -                       error("write $newfile: $!", $cleanup);
289 -       close TEMPLATE || error("save $newfile: $!", $cleanup);
290 -       rename($newfile, "$estdir/$cgi.tmpl") ||
291 -               error("rename $newfile: $!", $cleanup);
292 -
293 -       $newfile="$estdir/$cgi.conf";
294 -       open(TEMPLATE, ">$newfile") || error("open $newfile: $!", $cleanup);
295 -       my $template=template("estseek.conf");
296 -       eval q{use Cwd 'abs_path'};
297 -       $template->param(
298 -               index => $estdir,
299 -               tmplfile => "$estdir/$cgi.tmpl",
300 -               destdir => abs_path($config{destdir}),
301 -               url => $config{url},
302 -       );
303 -       print TEMPLATE $template->output || error("write $newfile: $!", $cleanup);
304 -       close TEMPLATE || error("save $newfile: $!", $cleanup);
305 -       rename($newfile, "$estdir/$cgi.conf") ||
306 -               error("rename $newfile: $!", $cleanup);
307 -
308 -       $cgi="$estdir/".IkiWiki::basename($config{cgiurl});
309 -       unlink($cgi);
310 -       my $estseek = defined $config{estseek} ? $config{estseek} : '/usr/lib/estraier/estseek.cgi';
311 -       symlink($estseek, $cgi) || error("symlink $estseek $cgi: $!");
312 -} # }}}
313 -
314 -sub estcmd ($;@) { #{{{
315 -       my @params=split(' ', shift);
316 -       push @params, "-cl", "$config{wikistatedir}/hyperestraier";
317 -       if (@_) {
318 -               push @params, "-";
319 -       }
320 -
321 -       my $pid=open(CHILD, "|-");
322 -       if ($pid) {
323 -               # parent
324 -               foreach (@_) {
325 -                       print CHILD "$_\n";
326 -               }
327 -               close(CHILD) || print STDERR "estcmd @params exited nonzero: $?\n";
328 -       }
329 -       else {
330 -               # child
331 -               open(STDOUT, "/dev/null"); # shut it up (closing won't work)
332 -               exec("estcmd", @params) || error("can't run estcmd");
333 -       }
334 -} #}}}
335 -
336 -1
337 +1;
338 </pre>
339
340