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