Skip to content

Instantly share code, notes, and snippets.

@phillro
Created August 5, 2011 02:19
Show Gist options
  • Save phillro/1126799 to your computer and use it in GitHub Desktop.
Save phillro/1126799 to your computer and use it in GitHub Desktop.
Easy Document Searching with Jquery, jquery-templates and Elastic Search
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
</head>
<body>
<script id="searchResultTemplate" type="text/x-jquery-tmpl">
{{each(i,result) hits}}
<div class="search-result">
<div>
${result.fields.content}
</div>
</div>
{{/each}}
</script>
<input id="search_txt">
<div id="search_results"></div>
<script src="js/jquery-1.6.1.min.js"></script>
<script src="js/jquery.tmp.min.js"></script>
<script>
$(document).ready(function() {
var elasticSearchParams = {
host: 'http://public.elasticsearchhq.com',
index: 'yourindexname',
obj: 'yourobjectname'
}
$(document).bind('search', function(event, data) {
var url = elasticSearchParams.host + ':'
+ elasticSearchParams.port + '/'
+ elasticSearchParams.index + '/'
+ elasticSearchParams.obj + '/'
+ '_search';
var query = {
q: 'content:*' + data.terms + '*',
fields:'content',
size:8
}
$.ajax({
url: url,
data: query,
dataType: "jsonp",
success: function(data) {
var tmp = data;
$('#search_results').empty();
$("#searchResultTemplate").tmpl(data.hits).appendTo("#search_results");
},
})
});
//Submit on each key pressed, but put in a minimum interval with typewatch
$('#search_txt').keyup(function() {
typewatch(function () {
var lastSearchTerm = $('#search_txt').data('lastSearchTerm');
if (!lastSearchTerm) {
lastSearchTerm = '';
}
if (lastSearchTerm != $('#search_txt').val()) {
$(document).trigger('search', {terms:$('#search_txt').val()});
}
$('#search_txt').data('lastSearchTerm', $('#search_txt').val());
}, 250);
});
//Creates a minimum interval between posted searches.
var typewatch = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
}
})();
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment