搜索引擎–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的搜索我们可以把搜索结果高亮显示,可以使用下面的函数建立高亮对象:
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
return
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
%}
这样搜索结果就会显示富文本效果了。展示效果如下:
- 搜索引擎–Django 内建模板标签中关键字的高亮显示
- jQuery高亮显示文本中重要的关键字
- js 搜索关键字,文章中关键字高亮显示
- 高亮显示关键字
- 高亮显示关键字
- 高亮显示关键字
- 高亮显示关键字
- 关键字高亮显示
- 关键字高亮显示
- 关键字高亮显示
- 关键字高亮显示
- 关键字高亮显示
- 关键字高亮显示
- 与关键字的高亮显示相关
- winform的DataGridView关键字高亮显示
- jquery高亮显示搜索的关键字
- 利用搜索引擎引用高亮页面关键字
- 搜索引擎中关键字搜索建议的实现(内附小Demo)
- 网站架构常用的优化手段
- 绘制dinosaur恐龙 源码
- scrum敏捷开发初探
- 在代码在设置EditText
- MySQL命令详解
- 搜索引擎–Django 内建模板标签中关键字的高亮显示
- xcode5解决crash:[NSKeyedUnarchiver decodeBoolForKey:]: value for key (UIHighlighted) is not a boolean
- HDU 1163(即周赛F题)数论数根
- linux stat命令、inode内容--ctime,mtime,atime的区别
- GPFS 之特殊管理功能
- windows下安装使用pychecker
- Strut2得到原始的request对象
- theano中的pydot安装
- 【微信开发】微信的一些应用