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

来源:互联网 发布:linux查看tcp端口占用 编辑:程序博客网 时间:2024/06/05 19:57
  • 主机环境: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

原创粉丝点击