# 全文检索框架 pip install django-haystack # 全文检索引擎 pip install whoosh # 中文分词框架 pip install jieba
heystack一些配置都是固定写好的,须要注意下html
1.安装haystack应用python
INSTALLED_APPS = ( ... 'haystack', )
2.在settings.py文件中配置搜索引擎django
# 配置搜索引擎后端 HAYSTACK_CONNECTIONS = { 'default': { # 使用whoosh引擎:提示,若是不须要使用jieba框架实现分词,就使用whoosh_backend 'ENGINE': 'haystack.backends.whoosh_cn_backend.WhooshEngine', # 索引文件路径 'PATH': os.path.join(BASE_DIR, 'whoosh_index'), # 在项目目录下建立文件夹 whoosh_index } } # 当添加、修改、删除数据时,自动生成索引 HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
search_indexes.py
文件 定义商品索引类GoodsSKUIndex()
,继承自indexes.SearchIndex
和indexes.Indexable
后端
from haystack import indexes
from .models import GoodsSKU框架
class GoodsSKUIndex(indexes.SearchIndex, indexes.Indexable):
# 定义字符类型的属性,名称固定为text
# document=True表示创建的索引数据存储到文件中
# use_template=True表示经过模板指定表中的字段,用于查询
text = indexes.CharField(document=True, use_template=True)测试
# 针对哪张表进行查询
def get_model(self):
return GoodsSKUui
# 针对哪些行进行查询
def index_queryset(self, using=None):
return self.get_model().objects.filter(isDelete=False)
搜索引擎
在templates
下面新建目录search/indexes/应用名
url
goods
应用中的GoodsSKU
模型类中的字段要创建索引文件夹:search/indexes/goods
在新建目录下,建立goodssku_text.txt
,并编辑要创建索引的字段,以下图 spa
templates/search/indexes/goods/goodssku_text_txt
python manage.py rebuild_index
/search/
get
接收关键字:q
import haystack.urls url(r'^search/', include(haystack.urls)),
全文检索结果:
templates/search
目录下的search.html
search.html
,咱们须要本身创建该html文件,并定义本身的搜索结果页面 传递的上下文包括:
settings.py
文件中设置HAYSTACK_SEARCH_RESULTS_PER_PAGE
HAYSTACK_SEARCH_RESULTS_PER_PAGE
能够控制每页显示数量HAYSTACK_SEARCH_RESULTS_PER_PAGE = 1
search.html
编写,相似商品列表页面