Skip to content

Instantly share code, notes, and snippets.

@clintongormley
Created May 20, 2011 08:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clintongormley/982552 to your computer and use it in GitHub Desktop.
Save clintongormley/982552 to your computer and use it in GitHub Desktop.
Search ElasticSearch blogposts
#!/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