- 主機環境:Ubuntu 13.04
- Python版本:2.7.4
- Django版本:1.5.4
- Scrapy版本:0.18.2
- ElasticSearch版本:0.90.5
原創作品,轉載請標明:http://blog.geekcome.com/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> |
這樣搜索結果就會顯示富文本效果了。展示效果如下: