Created
May 20, 2011 08:25
-
-
Save clintongormley/982552 to your computer and use it in GitHub Desktop.
Search ElasticSearch blogposts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use strict; | |
use warnings; | |
use ElasticSearch(); | |
my $es = ElasticSearch->new( | |
servers => 'localhost:9200', | |
use_index => 'es_blogs', | |
use_type => 'post' | |
); | |
setup_console(); | |
while (1) { | |
print "Enter a search term: "; | |
# Read search term from STDIN - quit if blank | |
my $keywords = <>; | |
last unless $keywords =~ /\S/; | |
my $result = $es->search( | |
query => { field => { _all => $keywords } }, | |
highlight => { | |
fields => { | |
_all => { | |
pre_tags => ['**'], | |
post_tags => ['**'], | |
} | |
} | |
} | |
); | |
my $hits = $result->{hits}; | |
my $total = $hits->{total}; | |
if ( $total == 0 ) { | |
print "No results found\n\n"; | |
} | |
else { | |
print "\n" . "Found $total results:\n"; | |
display_results( $hits->{hits} ); | |
} | |
} | |
#=================================== | |
sub display_results { | |
#=================================== | |
my $hits = shift; | |
for my $hit (@$hits) { | |
printf "Title: %s\n", $hit->{_source}{title}; | |
printf "URL: %s\n", $hit->{_source}{url}; | |
print "Snippets:\n"; | |
for my $snippet ( @{ $hit->{highlight}{_all} } ) { | |
print " - $snippet\n"; | |
} | |
print "\n"; | |
} | |
print "\n"; | |
} | |
#=================================== | |
sub setup_console { | |
#=================================== | |
# Assume a UTF8 console | |
binmode( STDOUT, ':utf8' ); | |
binmode( STDERR, ':utf8' ); | |
binmode( STDIN, ':encoding(UTF-8)' ); | |
# auto-flush STDOUT | |
$| = 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment