搜索引擎–Django 內建模板標籤中關鍵字的高亮顯示

  • 主機環境: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的搜索我們可以把搜索結果高亮顯示,可以使用下面的函數建立高亮對象:

1h=HighLighter(['<font color="red">'], ['</font>'], fragment_size=100)

然後使用add_highlight給搜索的字段添加高亮標誌後調用pyes的搜索函數。

獲得添加高亮後的搜索結果:

1if(r._meta.highlight.has_key("title")):
2    r['title']=r._meta.highlight[u"title"][0]
3if(r._meta.highlight.has_key('content')):
4    r['content']=r._meta.highlight[u'content'][0]

然後將ITEM返回給view。

view裏的對結果的處理如下:

01start = clock()
02total_hits = []#this list is used to obtain the total_hits,only total_hits[0] is used.
03results = dosearch(q,page,total_hits)
04end = clock()
05return render(request,'res_search.html', {'results' : results,
06                                            'query':q,
07                                            'count':total_hits[0],
08                                            'time':end-start,
09                                            'page':page,
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>秒
05{% if results %}
06    {% for res in results %}
07    <li><b> <a href={{ res.url }}>{% autoescape off %} {{ res.title }} {% endautoescape %} </a></b></li>
08        {{ res.url }}<br/>
09        {% autoescape off %}
10            {{ res.content }}
11        {% endautoescape %}
12    {% endfor %}
13{% else %}
14     <p>No contents found.
15{% endif %}

這樣搜索結果就會顯示富文本效果了。展示效果如下:

Screenshot from 2013-10-20 22:50:51

發佈了383 篇原創文章 · 獲贊 774 · 訪問量 271萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章