]> sipb.mit.edu Git - ikiwiki.git/blob - doc/todo/different_search_engine.mdwn
Added link to plugins/contrib/created_in_future
[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, and also
37   probably strip preprocessor directives too.
38 * `sanitize` - Would get the htmlized content, so would need to strip html.
39   Preprocessor directive output would be indexed. Doesn't get a destpage
40   parameter, making optimisation hard.
41 * `format` - Would get the entire html page, including the page template.
42   Probably not a good choice as indexing the same template for each page
43   is unnecessary.
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.
47
48 The indexer (and deleter) will need a way to figure out the ids in xapian
49 of the documents to delete. One way is storing the id of each page in the
50 ikiwiki index.
51
52 The other way would be adding a special term to the xapian db that can be
53 used with replace_document_by_term/delete_document_by_term. 
54 Hmm, let's use a term named "P<pagename>".
55
56 The hook should try to avoid re-indexing pages that have not changed since
57 they were last indexed. One problem is that, if a page with an inline is
58 built, every inlined item will get each hook run. And so a naive hook would
59 index each of those items, even though none of them have necessarily
60 changed. Date stamps are one possibility. Another would be to avoid having
61 the hook not do any indexing when `%preprocessing` is set (Ikiwiki.pm would
62 need to expose that variable.) Another approach would be to use a
63 needsbuild hook and only index the pages that are being built.
64
65 #### cgi
66
67 The cgi hook would exec omega to handle the searching, much as is done
68 with estseek in the current search plugin.
69
70 It would first set `OMEGA_CONFIG_FILE=.ikiwiki/omega.conf` ; that omega.conf
71 would set `database_dir=.ikiwiki/xapian` and probably also set a custom
72 `template_dir`, which would have modified templates branded for ikiwiki. So
73 the actual xapian db would be in `.ikiwiki/xapian/default/`.
74
75 ## lucene
76
77 >> 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.
78
79 >> Of course, there are problems. ;-)
80
81 >> * 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`.
82 >> * If I kill `ikiwiki` while it's indexing, I can screw up Plucene's locks. I suspect that this will be an easy fix.
83
84 >> 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. ;-)
85
86 >> If this seems a sensible approach, I'll write the CGI interface, and clean up the plugin. -- Ben
87
88 >>> The weird thing about lucene is that these are all reimplmentations of
89 >>> it. Thank you java.. The C++ version seems like a better choice to me
90 >>> (packages are trivial). --[[Joey]]
91
92 > 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]]
93
94 <pre>
95 Index: IkiWiki/Plugin/search.pm
96 ===================================================================
97 --- IkiWiki/Plugin/search.pm    (revision 2755)
98 +++ IkiWiki/Plugin/search.pm    (working copy)
99 @@ -1,33 +1,55 @@
100  #!/usr/bin/perl
101 -# hyperestraier search engine plugin
102  package IkiWiki::Plugin::search;
103  
104  use warnings;
105  use strict;
106  use IkiWiki;
107  
108 +use Plucene::Analysis::SimpleAnalyzer;
109 +use Plucene::Document;
110 +use Plucene::Document::Field;
111 +use Plucene::Index::Reader;
112 +use Plucene::Index::Writer;
113 +use Plucene::QueryParser;
114 +use Plucene::Search::HitCollector;
115 +use Plucene::Search::IndexSearcher;
116 +
117 +#TODO: Run the Plucene optimiser after a rebuild
118 +#TODO: CGI query interface
119 +
120 +my $PLUCENE_DIR;
121 +# $config{wikistatedir} may not be defined at this point, so we delay setting $PLUCENE_DIR
122 +# until a subroutine actually needs it.
123 +sub init () {
124 +  error("Plucene: Statedir <$config{wikistatedir}> does not exist!") 
125 +    unless -e $config{wikistatedir};
126 +  $PLUCENE_DIR = $config{wikistatedir}.'/plucene';  
127 +}
128 +
129  sub import {
130 -       hook(type => "getopt", id => "hyperestraier",
131 -               call => \&amp;getopt);
132 -       hook(type => "checkconfig", id => "hyperestraier",
133 +       hook(type => "checkconfig", id => "plucene",
134                 call => \&amp;checkconfig);
135 -       hook(type => "pagetemplate", id => "hyperestraier",
136 -               call => \&amp;pagetemplate);
137 -       hook(type => "delete", id => "hyperestraier",
138 +       hook(type => "delete", id => "plucene",
139                 call => \&amp;delete);
140 -       hook(type => "change", id => "hyperestraier",
141 +       hook(type => "change", id => "plucene",
142                 call => \&amp;change);
143 -       hook(type => "cgi", id => "hyperestraier",
144 -               call => \&amp;cgi);
145  }
146  
147 -sub getopt () {
148 -        eval q{use Getopt::Long};
149 -       error($@) if $@;
150 -        Getopt::Long::Configure('pass_through');
151 -        GetOptions("estseek=s" => \$config{estseek});
152 -}
153  
154 +sub writer {
155 +  init();
156 +  return Plucene::Index::Writer->new(
157 +      $PLUCENE_DIR, Plucene::Analysis::SimpleAnalyzer->new(), 
158 +      (-e "$PLUCENE_DIR/segments" ? 0 : 1));
159 +}
160 +
161 +#TODO: Better name for this function.
162 +sub src2rendered_abs (@) {
163 +  return map { Encode::encode_utf8($config{destdir}."/$_") } 
164 +    map { @{$renderedfiles{pagename($_)}} } 
165 +    grep { defined pagetype($_) } @_;
166 +}
167 +
168  sub checkconfig () {
169         foreach my $required (qw(url cgiurl)) {
170                 if (! length $config{$required}) {
171 @@ -36,112 +58,55 @@
172         }
173  }
174  
175 -my $form;
176 -sub pagetemplate (@) {
177 -       my %params=@_;
178 -       my $page=$params{page};
179 -       my $template=$params{template};
180 +#my $form;
181 +#sub pagetemplate (@) {
182 +#      my %params=@_;
183 +#      my $page=$params{page};
184 +#      my $template=$params{template};
185 +#
186 +#      # Add search box to page header.
187 +#      if ($template->query(name => "searchform")) {
188 +#              if (! defined $form) {
189 +#                      my $searchform = template("searchform.tmpl", blind_cache => 1);
190 +#                      $searchform->param(searchaction => $config{cgiurl});
191 +#                      $form=$searchform->output;
192 +#              }
193 +#
194 +#              $template->param(searchform => $form);
195 +#      }
196 +#}
197  
198 -       # Add search box to page header.
199 -       if ($template->query(name => "searchform")) {
200 -               if (! defined $form) {
201 -                       my $searchform = template("searchform.tmpl", blind_cache => 1);
202 -                       $searchform->param(searchaction => $config{cgiurl});
203 -                       $form=$searchform->output;
204 -               }
205 -
206 -               $template->param(searchform => $form);
207 -       }
208 -}
209 -
210  sub delete (@) {
211 -       debug(gettext("cleaning hyperestraier search index"));
212 -       estcmd("purge -cl");
213 -       estcfg();
214 +       debug("Plucene: purging: ".join(',',@_));
215 +       init();
216 +  my $reader = Plucene::Index::Reader->open($PLUCENE_DIR);
217 +  my @files = src2rendered_abs(@_);
218 +  for (@files) {
219 +    $reader->delete_term( Plucene::Index::Term->new({ field => "id", text => $_ }));
220 +  }
221 +  $reader->close;
222  }
223  
224  sub change (@) {
225 -       debug(gettext("updating hyperestraier search index"));
226 -       estcmd("gather -cm -bc -cl -sd",
227 -               map {
228 -                       Encode::encode_utf8($config{destdir}."/".$_)
229 -                               foreach @{$renderedfiles{pagename($_)}};
230 -               } @_
231 -       );
232 -       estcfg();
233 +       debug("Plucene: updating search index");
234 +  init();
235 +  #TODO: Do we want to index source or rendered files?
236 +  #TODO: Store author, tags, etc. in distinct fields; may need new API hook.
237 +  my @files = src2rendered_abs(@_);
238 +  my $writer = writer();    
239 +   
240 +  for my $file (@files) {
241 +    my $doc = Plucene::Document->new;
242 +    $doc->add(Plucene::Document::Field->Keyword(id => $file));
243 +    my $data;
244 +    eval { $data = readfile($file) };
245 +    if ($@) {
246 +      debug("Plucene: can't read <$file> - $@");
247 +      next;
248 +    }
249 +    debug("Plucene: indexing <$file> (".length($data).")");
250 +    $doc->add(Plucene::Document::Field->UnStored('text' => $data));
251 +    $writer->add_document($doc);
252 +  }
253  }
254 -
255 -sub cgi ($) {
256 -       my $cgi=shift;
257 -
258 -       if (defined $cgi->param('phrase') || defined $cgi->param("navi")) {
259 -               # only works for GET requests
260 -               chdir("$config{wikistatedir}/hyperestraier") || error("chdir: $!");
261 -               exec("./".IkiWiki::basename($config{cgiurl})) || error("estseek.cgi failed");
262 -       }
263 -}
264 -
265 -my $configured=0;
266 -sub estcfg () {
267 -       return if $configured;
268 -       $configured=1;
269 -
270 -       my $estdir="$config{wikistatedir}/hyperestraier";
271 -       my $cgi=IkiWiki::basename($config{cgiurl});
272 -       $cgi=~s/\..*$//;
273 -
274 -       my $newfile="$estdir/$cgi.tmpl.new";
275 -       my $cleanup = sub { unlink($newfile) };
276 -       open(TEMPLATE, ">:utf8", $newfile) || error("open $newfile: $!", $cleanup);
277 -       print TEMPLATE IkiWiki::misctemplate("search", 
278 -               "<!--ESTFORM-->\n\n<!--ESTRESULT-->\n\n<!--ESTINFO-->\n\n",
279 -               baseurl => IkiWiki::dirname($config{cgiurl})."/") ||
280 -                       error("write $newfile: $!", $cleanup);
281 -       close TEMPLATE || error("save $newfile: $!", $cleanup);
282 -       rename($newfile, "$estdir/$cgi.tmpl") ||
283 -               error("rename $newfile: $!", $cleanup);
284 -
285 -       $newfile="$estdir/$cgi.conf";
286 -       open(TEMPLATE, ">$newfile") || error("open $newfile: $!", $cleanup);
287 -       my $template=template("estseek.conf");
288 -       eval q{use Cwd 'abs_path'};
289 -       $template->param(
290 -               index => $estdir,
291 -               tmplfile => "$estdir/$cgi.tmpl",
292 -               destdir => abs_path($config{destdir}),
293 -               url => $config{url},
294 -       );
295 -       print TEMPLATE $template->output || error("write $newfile: $!", $cleanup);
296 -       close TEMPLATE || error("save $newfile: $!", $cleanup);
297 -       rename($newfile, "$estdir/$cgi.conf") ||
298 -               error("rename $newfile: $!", $cleanup);
299 -
300 -       $cgi="$estdir/".IkiWiki::basename($config{cgiurl});
301 -       unlink($cgi);
302 -       my $estseek = defined $config{estseek} ? $config{estseek} : '/usr/lib/estraier/estseek.cgi';
303 -       symlink($estseek, $cgi) || error("symlink $estseek $cgi: $!");
304 -}
305 -
306 -sub estcmd ($;@) {
307 -       my @params=split(' ', shift);
308 -       push @params, "-cl", "$config{wikistatedir}/hyperestraier";
309 -       if (@_) {
310 -               push @params, "-";
311 -       }
312 -
313 -       my $pid=open(CHILD, "|-");
314 -       if ($pid) {
315 -               # parent
316 -               foreach (@_) {
317 -                       print CHILD "$_\n";
318 -               }
319 -               close(CHILD) || print STDERR "estcmd @params exited nonzero: $?\n";
320 -       }
321 -       else {
322 -               # child
323 -               open(STDOUT, "/dev/null"); # shut it up (closing won't work)
324 -               exec("estcmd", @params) || error("can't run estcmd");
325 -       }
326 -}
327 -
328 -1
329 +1;
330 </pre>
331
332