Jesper Jesper - 6 months ago 38
Javascript Question

Search highlight in Elasticsearch (javascript)

I am having a problem with result highlighting in Elasticsearch. My query works, it does return results, but they are NOT highlighted... so I've been searching but I can't find what I'm doing wrong!

This is my code:

function search(searchInput){
emptyTable();
client.search({
index: 'movies',
size: 5,
body: {
query: {
//match: {_all: searchInput}
"term": {
"_all" : searchInput
}
},
"highlight": {
"require_field_match": true,
"fields": {
"_all": {
"pre_tags": [
"<b>"
],
"post_tags": [
"</b>"
]
}
}
}
}
}).then(function (resp) {
var hits = resp.hits.hits;
var hitcount = resp.hits.total;
if(!jQuery.isEmptyObject(hits)){
console.log(hits);
$.each(hits, function(key,obj) {
if(key%2==0){
$('#table').append('<tr><td>'+obj._source.imdbid+'</td><td>'+obj._source.name+'</td><td>'+obj._source.desc+'</td></tr>');
}else{
$('#table').append('<tr class="even"><td>'+obj._source.imdbid+'</td><td>'+obj._source.name+'</td><td>'+obj._source.desc+'</td></tr>');
}
});
}
$('#count').html("Aantal resultaten: "+hitcount);
});
}


I am searching data then putting it in a table, works fine. But the highlighting is not working at all. Please help me out!

Answer

I was having this same problem, and it turns out that when you specify the highlight parameter, elasticsearch returns not only the '_source' fields, but also 'highlight' fields. Upon further inspection, the ES docs seem to confirm this:

there will be another element in each search hit, called highlight, which includes the highlighted fields and the highlighted fragments

So, to get this working, you'd need to swap '_source' for 'highlight' in your code:

<td>'+obj.highlight.name+'</td>

I also found that ES also puts the highlight response in square brackets, so in my case, (using AngularJS) I accessed the value as follows:

// ...ng-repeat=result in results...
<p ng-bind-html="result.highlight.body[0]">{{result.highlight.body[0]}}</p>
Comments