搜索引擎–Django 内建模板标签中关键字的高亮显示

  • 主机环境: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里的对结果的处理如下:

01 start=clock()
02 total_hits=[]#this list is used to obtain the total_hits,only total_hits[0] is used.
03 results=dosearch(q,page,total_hits)
04 end=clock()
05 returnrender(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 {%ifresults %}
06 {%forres 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值