全文检索不同于特定字段的模糊查询,使用全文检索的效率更高,并且能够对于中文进行分词处理

需要的第三方库:

  • haystack:django的一个包,可以方便地对model里面的内容进行索引、搜索,设计为支持whoosh,solr,Xapian,Elasticsearc四种全文检索引擎后端,属于一种全文检索的框架
  • whoosh:纯Python编写的全文搜索引擎,虽然性能比不上sphinx、xapian、Elasticsearc等,但是无二进制包,程序不会莫名其妙的崩溃,对于小型的站点,whoosh已经足够使用
  • jieba:一款免费的中文分词包

操作

首先pip安装包

pip install django-haystack
pip install whoosh
pip install jieba

设置settings

添加应用:

INSTALLED_APPS = (
...
'haystack',
)

添加搜索引擎:

HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.whoosh_cn_backend.WhooshEngine',
'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
}
} #自动生成索引
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
#每一页显示多少数据
HAYSTACK_SEARCH_RESULTS_PER_PAGE = 18
 

添加url:

urlpatterns = [
...
url(r'^search/', include('haystack.urls')),
]

在应用目录下建立search_indexes.py

# coding=utf-8
from haystack import indexes
from models import GoodsInfo class GoodsInfoIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True) def get_model(self):
return GoodsInfo def index_queryset(self, using=None):
return self.get_model().objects.all()

在目录“templates/search/indexes/应用名称/”下创建“模型类名称_text.txt”文件

#goodsinfo_text.txt,这里列出了要对哪些列的内容进行检索,模型类中的某些字段
{{ object.gName }}
{{ object.gSubName }}
{{ object.gDes }}

在目录“templates/search/”下建立search.html

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
{% if query %}
<h3>搜索结果如下:</h3>
{% for result in page.object_list %}
<a href="/{{ result.object.id }}/">{{ result.object.gName }}</a><br/>
{% empty %}
<p>没找到</p>
{% endfor %} {% if page.has_previous or page.has_next %}
<div>
{% if page.has_previous %}<a href="?q={{ query }}&amp;page={{ page.previous_page_number }}">{% endif %}&laquo; 上一页{% if page.has_previous %}</a>{% endif %}
|
{% if page.has_next %}<a href="?q={{ query }}&amp;page={{ page.next_page_number }}">{% endif %}下一页 &raquo;{% if page.has_next %}</a>{% endif %}
</div>
{% endif %}
{% endif %}
</body>
</html>

建立ChineseAnalyzer.py文件

保存在haystack的安装文件夹下,路径如“/home/python/.virtualenvs/django_py2/lib/python2.7/site-packages/haystack/backends”

import jieba
from whoosh.analysis import Tokenizer, Token class ChineseTokenizer(Tokenizer):
def __call__(self, value, positions=False, chars=False,
keeporiginal=False, removestops=True,
start_pos=0, start_char=0, mode='', **kwargs):
t = Token(positions, chars, removestops=removestops, mode=mode,
**kwargs)
seglist = jieba.cut(value, cut_all=True)
for w in seglist:
t.original = t.text = w
t.boost = 1.0
if positions:
t.pos = start_pos + value.find(w)
if chars:
t.startchar = start_char + value.find(w)
t.endchar = start_char + value.find(w) + len(w)
yield t def ChineseAnalyzer():
return ChineseTokenizer()

复制whoosh_backend.py文件,改名为whoosh_cn_backend.py

from .ChineseAnalyzer import ChineseAnalyzer
查找
analyzer=StemmingAnalyzer()
改为
analyzer=ChineseAnalyzer()

生成索引

初始化索引:

python manage.py rebuild_index

在模板中创建搜索栏

<form method='get' action="/search/" target="_blank">
<input type="text" name="q">
<input type="submit" value="查询">
</form>

关于全文索引使用的固定参数一些说明:

我们打开haystack第三方包中的urls文件

haystack
----urls.py # encoding: utf-8 from __future__ import absolute_import, division, print_function, unicode_literals from django.conf.urls import url from haystack.views import SearchView urlpatterns = [
url(r'^$', SearchView(), name='haystack_search'),
]

然后进入haystack.views 文件

#这里将搜索显示的数据默认为20个
RESULTS_PER_PAGE = getattr(settings, 'HAYSTACK_SEARCH_RESULTS_PER_PAGE', 20)

#在search文件下的search
template = 'search/search.html'
extra_context = {}
query = ''
results = EmptySearchQuerySet()
request = None
form = None
results_per_page = RESULTS_PER_PAGE

更多详情请看

haystack.views.py

# encoding: utf-8

from __future__ import absolute_import, division, print_function, unicode_literals

from django.conf import settings
from django.core.paginator import InvalidPage, Paginator
from django.http import Http404
from django.shortcuts import render from haystack.forms import FacetedSearchForm, ModelSearchForm
from haystack.query import EmptySearchQuerySet RESULTS_PER_PAGE = getattr(settings, 'HAYSTACK_SEARCH_RESULTS_PER_PAGE', 20) class SearchView(object):
template = 'search/search.html'
extra_context = {}
query = ''
results = EmptySearchQuerySet()
request = None
form = None
results_per_page = RESULTS_PER_PAGE def __init__(self, template=None, load_all=True, form_class=None, searchqueryset=None, results_per_page=None):
self.load_all = load_all
self.form_class = form_class
self.searchqueryset = searchqueryset if form_class is None:
self.form_class = ModelSearchForm if not results_per_page is None:
self.results_per_page = results_per_page if template:
self.template = template def __call__(self, request):
"""
Generates the actual response to the search. Relies on internal, overridable methods to construct the response.
"""
self.request = request self.form = self.build_form()
self.query = self.get_query()
self.results = self.get_results() return self.create_response() def build_form(self, form_kwargs=None):
"""
Instantiates the form the class should use to process the search query.
"""
data = None
kwargs = {
'load_all': self.load_all,
}
if form_kwargs:
kwargs.update(form_kwargs) if len(self.request.GET):
data = self.request.GET if self.searchqueryset is not None:
kwargs['searchqueryset'] = self.searchqueryset return self.form_class(data, **kwargs) def get_query(self):
"""
Returns the query provided by the user. Returns an empty string if the query is invalid.
"""
if self.form.is_valid():
return self.form.cleaned_data['q'] return '' def get_results(self):
"""
Fetches the results via the form. Returns an empty list if there's no query to search with.
"""
return self.form.search() def build_page(self):
"""
Paginates the results appropriately. In case someone does not want to use Django's built-in pagination, it
should be a simple matter to override this method to do what they would
like.
"""
try:
page_no = int(self.request.GET.get('page', 1))
except (TypeError, ValueError):
raise Http404("Not a valid number for page.") if page_no < 1:
raise Http404("Pages should be 1 or greater.") start_offset = (page_no - 1) * self.results_per_page
self.results[start_offset:start_offset + self.results_per_page] paginator = Paginator(self.results, self.results_per_page) try:
page = paginator.page(page_no)
except InvalidPage:
raise Http404("No such page!") return (paginator, page) def extra_context(self):
"""
Allows the addition of more context variables as needed. Must return a dictionary.
"""
return {} def get_context(self):
(paginator, page) = self.build_page() context = {
'query': self.query,
'form': self.form,
'page': page,
'paginator': paginator,
'suggestion': None,
} if hasattr(self.results, 'query') and self.results.query.backend.include_spelling:
context['suggestion'] = self.form.get_suggestion() context.update(self.extra_context()) return context def create_response(self):
"""
Generates the actual HttpResponse to send back to the user.
""" context = self.get_context() return render(self.request, self.template, context) def search_view_factory(view_class=SearchView, *args, **kwargs):
def search_view(request):
return view_class(*args, **kwargs)(request)
return search_view class FacetedSearchView(SearchView):
def __init__(self, *args, **kwargs):
# Needed to switch out the default form class.
if kwargs.get('form_class') is None:
kwargs['form_class'] = FacetedSearchForm super(FacetedSearchView, self).__init__(*args, **kwargs) def build_form(self, form_kwargs=None):
if form_kwargs is None:
form_kwargs = {} # This way the form can always receive a list containing zero or more
# facet expressions:
form_kwargs['selected_facets'] = self.request.GET.getlist("selected_facets") return super(FacetedSearchView, self).build_form(form_kwargs) def extra_context(self):
extra = super(FacetedSearchView, self).extra_context()
extra['request'] = self.request
extra['facets'] = self.results.facet_counts()
return extra def basic_search(request, template='search/search.html', load_all=True, form_class=ModelSearchForm, searchqueryset=None, extra_context=None, results_per_page=None):
"""
A more traditional view that also demonstrate an alternative
way to use Haystack. Useful as an example of for basing heavily custom views off of. Also has the benefit of thread-safety, which the ``SearchView`` class may
not be. Template:: ``search/search.html``
Context::
* form
An instance of the ``form_class``. (default: ``ModelSearchForm``)
* page
The current page of search results.
* paginator
A paginator instance for the results.
* query
The query received by the form.
"""
query = ''
results = EmptySearchQuerySet() if request.GET.get('q'):
form = form_class(request.GET, searchqueryset=searchqueryset, load_all=load_all) if form.is_valid():
query = form.cleaned_data['q']
results = form.search()
else:
form = form_class(searchqueryset=searchqueryset, load_all=load_all) paginator = Paginator(results, results_per_page or RESULTS_PER_PAGE) try:
page = paginator.page(int(request.GET.get('page', 1)))
except InvalidPage:
raise Http404("No such page of results!") context = {
'form': form,
'page': page,
'paginator': paginator,
'query': query,
'suggestion': None,
} if results.query.backend.include_spelling:
context['suggestion'] = form.get_suggestion() if extra_context:
context.update(extra_context) return render(request, template, context)

django-全文检索的更多相关文章

  1. django全文检索

    -------------------linux下配置操作1.在虚拟环境中依次安装包 1.pip install django-haystack haystack:django的一个包,可以方便地对m ...

  2. Django全文检索(django-haystack+whoosh+jieba)

    前言: 全文检索就是针对所有内容进行动态匹配搜索的概念,针对特定的关键词建立索引并精确匹配达到性能优化的目的 class Whoose_seach(object): analyzer = Chines ...

  3. 使用haystack实现django全文检索搜索引擎功能

    前言 django是python语言的一个web框架,功能强大.配合一些插件可为web网站很方便地添加搜索功能. 搜索引擎使用whoosh,是一个纯python实现的全文搜索引擎,小巧简单. 中文搜索 ...

  4. Django:全文检索功能可参考博客

    https://blog.csdn.net/AC_hell/article/details/52875927 https://www.zmrenwu.com/courses/django-blog-t ...

  5. Django实现组合搜索的方法示例

    目录 一.实现方法 二.基本原理 三.代码样例 方法1:纯模板语言实现 方法二:使用simpletag实现 四.其他变化 1.model定义 2.处理函数变化 3.simpletag相应改变   一. ...

  6. Django--全文检索功能

    经过两个月的时间,毕设终于算是把所有主要功能都完成了,最近这一周为了实现全文检索的功能,也算是查阅了不少资料,今天就在这里记录一下,以免以后再用到时抓瞎了~ 首先介绍一下我使用的Django全文检索逻 ...

  7. Django Haystack 全文检索与关键词高亮

    Django Haystack 简介 django-haystack 是一个专门提供搜索功能的 django 第三方应用,它支持 Solr.Elasticsearch.Whoosh.Xapian 等多 ...

  8. django框架中的全文检索Haystack

    1.什么是Haystack Haystack是django的开源全文搜索框架(全文检索不同于特定字段的模糊查询,使用全文检索的效率更高 ),该框架支持Solr,Elasticsearch,Whoosh ...

  9. Django:haystack全文检索详细教程

    参考:https://blog.csdn.net/AC_hell/article/details/52875927 一.安装第三方库及配置 1.1 安装插件 pip install whoosh dj ...

  10. django之全文检索

    全文检索 全文检索不同于特定字段的模糊查询,使用全文检索的效率更高,并且能够对于中文进行分词处理 haystack:django的一个包,可以方便地对model里面的内容进行索引.搜索,设计为支持wh ...

随机推荐

  1. 牛客第二场 C.message(计算几何+二分)

    题目传送:https://www.nowcoder.com/acm/contest/140/C 题意:有n个云层,每个云层可以表示为y=ax+b.每个飞机的航线可以表示为时间x时,坐标为(x,cx+d ...

  2. Python大法之告别脚本小子系列—各类URL采集器编写

    本文作者:i春秋签约作家——阿甫哥哥 系列文章专辑:https://bbs.ichunqiu.com/forum.php?mod=collection&action=view&ctid ...

  3. Swift5 语言参考(二) 词法结构

    词汇结构 Swift 的词法结构描述了什么样的字符序列形成了语言的有效标记.这些有效令牌构成语言的最低级构建块,用于描述后续章节中的其余语言.令牌由标识符,关键字,标点符号,文字或运算符组成. 在大多 ...

  4. Redis---事务和Wtach

    1. 概述 Redis通过 MULTI, EXEC / WATCH 等命令来实现事务. 事务提供一种将多个命令请求打包, 然后一次性.按顺序的执行多个命令的机制. 并且在事务执行期间, 服务器不会中断 ...

  5. java操作数据库的基本方法

    此次开发工具为eclipse,才有的数据库驱动是mysql-connector-java-5.1.8-bin.jar 第一步,在eclipse的工程目录中引用mysql驱动 驱动下载地址:https: ...

  6. Fiddler抓包连接失败502的解决方法

    本篇用户记录,在用Fiddler遇到过的坑,首先, 先上图,遇到的问题,提示主机连接失败.只是打开Fiddler,不会报这个问题,只有当Fiddler和火狐浏览器一起启动的时候,才会报这个错. 尝试去 ...

  7. SQLServer——SQLServer链接外部数据源

    学习链接:https://www.cnblogs.com/licin/p/6244169.html 一.新建ODBC数据源 1.打开控制面板→管理工具→ODBC数据源→系统DSN 2.添加新系统数据源 ...

  8. 11-02 Java Object类使用详解

     Object 作为超类 Object是类层次结构的根类,所有的类都直接或者间接的继承自Object类. Object类的构造方法有一个,并且是无参构造,这其实就是理解当时我们说过,子类构造方法默认访 ...

  9. SQL SERVICE中的锁

    SQL SERVICE中的几个锁 SELECT * FROM dbo.TableName WITH (NOLOCK) --不加任何锁的读,脏读SELECT * FROM dbo.TableName W ...

  10. Javac中的nullcheck

    Javac会通过调用引用对象的getClass()来判空,主要有几处: (1)JCMethodInvocation()方法中,如下实例: class A{ class B{} } public cla ...