show slots
[angular-mojolicious.git] / couchdb-external-kinosearch.pl
1 #!/usr/bin/perl
2 use warnings;
3 use strict;
4
5 # http://wiki.apache.org/couchdb/ExternalProcesses
6 #
7 # curl 'http://localhost:5984/drzb2011/_kinosearch?q=a&include_docs=true'
8
9 use KinoSearch::Search::IndexSearcher;
10 use Mojo::JSON;
11 use Data::Dump qw(dump);
12
13 $|=1;
14
15 our $json = Mojo::JSON->new;
16
17 open(my $log, '>>', '/tmp/couchdb-external-kinosearch.log');
18
19 while(<STDIN>) {
20         warn "# $_\n";
21         my $request = $json->decode($_);
22         print $log "<<< $_\n"; 
23
24         my $response = {
25                 code => 200,
26 #               json => {},
27         };
28
29         if ( my $q = $request->{query}->{q} ) {
30
31                 my $searcher = KinoSearch::Search::IndexSearcher->new( 
32                         index => '/tmp/kinosearch.' . $request->{info}->{db_name},
33                 );
34
35                 my $hits = $searcher->hits( query => $q );
36
37                 $response->{json}->{total_hits} = $hits->total_hits;
38
39                 while ( my $hit = $hits->next ) {
40                         my $r = {
41                                 _id => $hit->{_id},
42                                 _rev => $hit->{_rev},
43                                 score => $hit->get_score,
44                         };
45                         $r->{doc} = $json->decode( $hit->{doc} ) if exists $request->{query}->{include_docs};
46                         push @{ $response->{json}->{hits} }, $r;
47                 }
48
49         } else {
50                 $response->{json}->{error} = "no query found";
51         }
52
53         my $send = $json->encode($response);
54         print $send, $/;
55         print $log ">>> $send\n";
56 }
57
58
59 __END__
60 ; insert following into /etc/couchdb/local.ini:
61
62 [log]
63 level = debug
64
65 [external]
66 kinosearch = /srv/angular-mojolicious/couchdb-external-kinosearch.pl
67
68 [httpd_db_handlers]
69 _kinosearch = {couch_httpd_external, handle_external_req, <<"kinosearch">>}
70