我在 Elasticsearch 中突出显示结果时遇到问题。我的查询有效,它确实返回结果,但它们没有突出显示...所以我一直在搜索,但我找不到我做错了什么!
这是我的代码:
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);
});
}
我正在搜索数据然后将其放入表格中,工作正常。但突出显示根本不起作用。请帮帮我!
最佳答案
我遇到了同样的问题,事实证明,当您指定highlight参数时,elasticsearch不仅返回“_source”字段,还返回“highlight”字段。经进一步检查,ES docs似乎证实了这一点:
there will be another element in each search hit, called highlight, which includes the highlighted fields and the highlighted fragments
因此,要使其正常工作,您需要在代码中将“_source”替换为“highlight”:
<td>'+obj.highlight.name+'</td>
我还发现 ES 还将突出显示响应放在方括号中,因此在我的例子中,(使用 AngularJS)我按如下方式访问了该值:
// ...ng-repeat=result in results...
<p ng-bind-html="result.highlight.body[0]">{{result.highlight.body[0]}}</p>
关于javascript - Elasticsearch 中的搜索突出显示 (javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21782358/