#!/usr/bin/perl
use Search::Xapian qw/:db/;

# open index for writing
my $db = Search::Xapian::WritableDatabase->new('./testdb', DB_CREATE_OR_OVERWRITE) or die $!;

# populating the index: term with termcount 1
for (0..4) {
    my $doc = Search::Xapian::Document->new() or die $!;
    $doc->add_value(0, $_);
    $doc->add_term("test");
    $db->add_document($doc);
}

# populating the index: same term with termcount 2
for (0..4) {
    my $doc = Search::Xapian::Document->new() or die $!;
    $doc->add_value(0, $_);
    $doc->add_term("test", 2);
    $db->add_document($doc);
}

# close index
undef $db;

# reopen for search
my $db = Search::Xapian::Database->new('./testdb') or die $!;

# set query 
my $enquire = $db->enquire();
$enquire->set_query(Search::Xapian::Query->new('test'));

## comment this out to try without sorting by value
$enquire->set_sort_by_value_then_relevance(0, 1);
##

# 10 results, unpaged
print "(unpaged)\n";
search(0, 10);

# 10 results, splitted in several pages
print "(paged)\n";
search(0, 1);
search(1, 1);
search(2, 8);


# performs the search (according to an example from cpan)
sub search {
   my ($start, $num) = @_;

   my @matches = $enquire->matches($start, $num);
   foreach my $match ( @matches ) {
       my $doc = $match->get_document();
       printf "ID %d %d%%\n", $match->get_docid(), $match->get_percent();
   }
}
