Skip to content

Instantly share code, notes, and snippets.

@clintongormley
Created November 16, 2014 17:00
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/66f998d904fcb0652eec to your computer and use it in GitHub Desktop.
Save clintongormley/66f998d904fcb0652eec to your computer and use it in GitHub Desktop.
use Search::Elasticsearch;
my $e = Search::Elasticsearch->new( trace_to => 'Stderr' );
my %blogpost = (
title => "My first blogpost",
author => 'Clint',
content => 'blah blah blah'
);
my @comments = (
{ author => 'John', comment => 'Nice blogpost' },
{ author => 'Mary', comment => 'Awesome work' }
);
$blogpost{comments} = \@comments;
# delete the index in case it exists
$e->indices->delete( index => 'website', ignore => 404 );
# now create the index with the `nested` mapping
$e->indices->create(
index => 'website',
body => {
mappings => {
blogpost => {
properties => {
title => { type => 'string' },
author => { type => 'string' },
comments => {
type => 'nested',
properties => {
author => { type => 'string' },
comment => { type => 'string' }
}
}
}
}
}
}
);
$e->index(
index => 'website',
type => 'blogpost',
id => 1,
body => \%blogpost
);
$e->indices->refresh; # otherwise you have to wait 1 second
my $results = $e->search(
index => 'website',
body => {
query => {
bool => {
must => [
{ match => { title => 'first blogpost' } },
{ nested => {
path => 'comments',
query => {
bool => {
must => [
{ match =>
{ "comments.author" => 'john' }
},
{ match => {
"comments.comment" => 'nice'
}
},
]
}
}
}
}
]
}
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment