- 主机环境:Ubuntu 13.04
- Python版本:2.7.4
- Django版本:1.5.4
- Scrapy版本:0.18.2
- ElasticSearch版本:0.90.5
原创作品,转载请标明:http://blog.yanming8.cn/archives/141
基于ElasticSearch的搜索我们可以把搜索结果高亮显示,可以使用下面的函数建立高亮对象:
1 | h = HighLighter([ '<font color="red">' ], [ '</font>' ], fragment_size = 100 ) |
然后使用add_highlight给搜索的字段添加高亮标志后调用pyes的搜索函数。
获得添加高亮后的搜索结果:
1 | if (r._meta.highlight.has_key( "title" )): |
2 |
r[ 'title' ] = r._meta.highlight[u "title" ][ 0 ] |
3 | if (r._meta.highlight.has_key( 'content' )): |
4 |
r[ 'content' ] = r._meta.highlight[u 'content' ][ 0 ] |
然后将ITEM返回给view。
view里的对结果的处理如下:
03 | results = dosearch(q,page,total_hits) |
05 | return render(request, 'res_search.html' , { 'results' : results, |
07 |
'count' :total_hits[ 0 ], |
10 |
'total_page' :total_hits[ 0 ] / PAGE_SIZE, |
11 |
'nextpage' : int (page) + 1 }) |
如果只是这样把搜索的结果返回给HTML页面的话,搜索结果的显示会是直接由<font color=”red”>Key Word</font>包围的,这是因为系统自动把HTML转译了,而不是解释这些标签。需要关闭autoescape选项。
01 | <p>查询的内容: <font color= "red" >{{ query }}</font><br> |
02 | 发现<font color= "red" >{{ count }}</font>条符合条件的内容, |
03 | 第<font color= "red" >{{ page }}</font>页,共<font color= "red" >{{ total_page }}</font>页, |
04 | 用时<font color= "red" >{{ time }}</font>秒 |
06 |
{% for res in results %} |
07 |
<li><b> <a href={{ res.url }}>{% autoescape off %} {{ res.title }} {% endautoescape %} </a></b></li> |
这样搜索结果就会显示富文本效果了。展示效果如下: