Catalyst-Model-Search

 view release on metacpan or  search on metacpan

lib/Catalyst/Model/Search/Plucene.pm  view on Meta::CPAN

package Catalyst::Model::Search::Plucene;

our $VERSION = '0.03';

use strict;
use warnings;
use NEXT;
use base qw/Catalyst::Model::Search/;
use Catalyst::Model::Search::Plucene::Simple;

__PACKAGE__->mk_classdata( '_plucene' );

sub new { 
    my ( $self, $c ) = @_;

    $self = $self->NEXT::new( $c );
    
    $self->config->{index}        ||= $c->config->{home} . '/plucene';
    $self->config->{analyzer}     ||= 'Plucene::Analysis::SimpleAnalyzer';
    $self->config->{return_style} ||= 'key';
    
    return $self->init();
}

sub init {
    my $self = shift;
    
    my $plucene 
        = Catalyst::Model::Search::Plucene::Simple->new( {
            dir          => $self->config->{index},
            analyzer     => $self->config->{analyzer},
            return_style => $self->config->{return_style},
        } );
                   
    $self->_plucene( $plucene );
    
    $self->optimize;
    
    return $self;
}

sub analyzer {
    my ( $self, $analyzer_class ) = @_;
    
    $self->config->{analyzer} = $analyzer_class;
    
    return $self->init();
}

sub add {
    my ( $self, $data ) = @_;
    
    $self->_plucene->add( %{ $data } );
}

sub update {
    my ( $self, $data ) = @_;
    
    foreach my $key ( keys %{ $data } ) {
        $self->remove( $key );
    }
    $self->add( $data );
}

sub remove {
    my ( $self, $key ) = @_;

    if ( $self->is_indexed( $key ) ) {
        $self->_plucene->delete_document( $key );
    }
}

sub query {
    my ( $self, $query ) = @_;
    
    my $results = $self->_plucene->search( $query );
    return (wantarray) ? $results->get_items : $results;
}

sub is_indexed {
    my ( $self, $key ) = @_;
    
    return $self->_plucene->indexed( $key );
}

sub optimize {
    my $self = shift;
    
    $self->_plucene->optimize;
}

1;
__END__

=head1 NAME

Catalyst::Model::Search::Plucene - Index and search using Plucene

=head1 SYNOPSIS

    package MyApp::M::Search;

    use strict;
    use base qw/Catalyst::Model::Search::Plucene/;
    
    __PACKAGE__->config(
        index        => MyApp->config->{home} . '/plucene',
        analyzer     => 'Plucene::Plugin::Analyzer::SnowballAnalyzer',
        return_style => 'full',
    );
    
    1;
    
    # meanwhile, in a controller...
    
    my $search = 'MyApp::M::Search';



( run in 1.590 second using v1.01-cache-2.11-cpan-39bf76dae61 )