本文参考自Haystack官方文档:https://django-haystack.readthedocs.io/en/master/tutorial.html#configuration

简介

Haystack是一个django框架下的第三方库,专门用于提供搜索功能,它支持 Solr、Elasticsearch、Whoosh、Xapian 等多种搜索后端,而无需修改代码。

官方介绍:

Getting Started with Haystack
Search is a topic of ever increasing importance. Users increasing rely on search to separate signal from noise and find what they’re
looking for quickly. In addition, search can provide insight into what things are popular (many searches),
what things are difficult to find on the site and ways you can improve the site. To this end, Haystack tries to make integrating custom search as easy as possible while being flexible/powerful enough to handle more
advanced use cases. //Haystack试图尽可能简化集成自定义搜索,同时更灵活/强大,足以处理更高级的用例。 Haystack is a reusable app (that is, it relies only on its own code and focuses on providing just search) that plays nicely with both
apps you control as well as third-party apps (such as django.contrib.*) without having to modify the sources. Haystack also does pluggable backends (much like Django’s database layer), so virtually all of the code you write ought to be portable
between whichever search engine you choose.

应用

在第三方库中安装Haystack

pip install django-haystack

然后在settings中添加Haystack应用,通常是项目根目录下的settings.py

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites', # Added.
'haystack', # Then your usual apps...
'blog',
]

继续修改settings.py,添加要使用的后端和后端的其他配置。

比如说我们选用Whoosh

Requires setting PATH to the place on your filesystem where the Whoosh index should be located. Standard warnings about permissions 

and keeping it out of a place your webserver may serve documents out of apply.# 本地系统文件路径。以及将其保存在web服务器外,无法提供服务的警告权限的设置。

Example:

import os
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'),
},
}

接下来就是处理数据了。

处理数据

创建 SearchIndexes

SearchIndex objects are the way Haystack determines what data should be placed in the search index and handles the flow of data in. 
You can think of them as being similar to Django Models or Forms in that they are field-based and manipulate/store data. You generally create a unique SearchIndex for each type of Model you wish to index, though you can reuse the same SearchIndex between
different models if you take care in doing so and your field names are very standardized.

官方文档的说法,SearchIndexes对象是确定哪些数据应该放入搜索索引中,和处理数据流的位置(也许称为容器比较好)。我们可以认为他们类似于DJango中的Models或者Forms,用于操作/存储数据的基础字段。

我们通常可以为每种Models索引创建一个唯一SearchIndex,不过我们需要小心处理SearchIndex,给其命名非常标准的字段,才可以在不同模型中重复使用。

要构建一个SearchIndex,所必需的步骤是将indexes.SearchIndex& indexes.Indexable子类化,定义你想要存储数据的字段并定义一个get_model方法。

官方案例如下

import datetime
from haystack import indexes
from myapp.models import Note class NoteIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
author = indexes.CharField(model_attr='user')
pub_date = indexes.DateTimeField(model_attr='pub_date') def get_model(self):
return Note def index_queryset(self, using=None):
"""Used when the entire index for model is updated."""
return self.get_model().objects.filter(pub_date__lte=datetime.datetime.now())

这里代码定义方法很像是django中的类视图函数。

When you choose a document=True field, it should be consistently named across all of your SearchIndex classes to avoid 
confusing the backend. The convention is to name this field text. There is nothing special about the text field name used in all of the examples. It could be anything; you could call it
pink_polka_dot and it won’t matter. It’s simply a convention to call it text.

在这段代码后面,官方特意提醒:当我们选择document=True字段时,为了避免后端处理混淆,要在我们的SearchIndex类中保持其命名一致性。约定俗成的默认命名为text。

Additionally, we’re providing use_template=True on the text field. This allows us to use a data template 
(rather than error-prone concatenation) to build the document the search engine will index. You’ll need to create a new template
inside your template directory called search/indexes/myapp/note_text.txt and place the following inside: {{ object.title }}
{{ object.user.get_full_name }}
{{ object.body }}

接下来是官方额外备注:他们提供了用于text字段的参数use_template。该参数允许我们用数据模板(而非容易出错的拼接)创建搜索引擎的文档索引。我们需要在我们的模板目录中创建一个新的模板search/indexes/myapp/note_text.txt。就像上面文档中的示例。

关于index_queryset:

一个常见的主题是允许管理员添加,不会在网站上显示的未来的内容,直到到达指定时间。我们指定一个自定义的 index_queryset方法来防止这些潜在的项目被索引到。

视图设置

Add The SearchView To Your URLconf

我们要在项目的URLconf中,添加

url(r'^search/', include('haystack.urls')),

这设置了一个Haystack默认URLconf,它由一个指向SearchView实例的单独URLconf组成。

当然,我们可以通过改变传递的关键字参数来改变这个类的行为,也可以重新覆写为自定义视图函数。

search template

当然,你的视图模板(search/search.html for the default case) 也许看起来非常简单,通常像这样就足够了:

{% extends 'base.html' %}

{% block content %}
<h2>Search</h2> <form method="get" action=".">
<table>
{{ form.as_table }}
<tr>
<td>&nbsp;</td>
<td>
<input type="submit" value="Search">
</td>
</tr>
</table> {% if query %}
<h3>Results</h3> {% for result in page.object_list %}
<p>
<a href="{{ result.object.get_absolute_url }}">{{ result.object.title }}</a>
</p>
{% empty %}
<p>No results found.</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; Previous{% if page.has_previous %}</a>{% endif %}
|
{% if page.has_next %}<a href="?q={{ query }}&amp;page={{ page.next_page_number }}">{% endif %}Next &raquo;{% if page.has_next %}</a>{% endif %}
</div>
{% endif %}
{% else %}
{# Show some example queries to run, maybe query syntax, something else? #}
{% endif %}
</form>
{% endblock %}
Note that the page.object_list is actually a list of SearchResult objects instead of individual models. These objects have all 
the data returned from that record within the search index as well as score. They can also directly access the model for the result
via {{ result.object }}. So the {{ result.object.title }} uses the actual Note object in the database and accesses its title field.

请注意,这里的page.object_list实际上是一个SearchResult 对象列表,而不是单个模型。这些对象可以返回从搜索索引内的记录及所有数据、得分。他们可以通过{{ result.objcet }}直接访问模型结果集。因此可以使用数据库的实际对象并访问其字段{{ result.object.title }}。

未完待续。。。

django-Haystack库的更多相关文章

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

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

  2. Django+haystack实现全文搜索出现错误 ImportError: cannot import name signals

    原因是在你的settings.py或者其他地方使用了  "import haystack" 当我们使用django-haysatck库时,表面上会有haystack库,但实际上并不 ...

  3. django haystack报错: ModuleNotFoundError: No module named 'blog.whoosh_cn_backend'

    在配置django haystack时报错: 解决方案: 将ENGINE的值 改为 这样就可以了.

  4. Django haystack+solr搜索引擎部署的坑.

    跟着<<Django by Example>> 一路做下来,到了搭建搜索引擎的步骤 默认的思路是用 obj.objects.filter(body__icontains='fr ...

  5. django haystack

    # coding=utf-8 from haystack import indexes from yw_asset.models import * class AssetIndex(indexes.S ...

  6. python第三方库系列之十八--python/django test库

    django是属于python语音的web框架,要说django測试.也能够先说说python的測试.django能够用python的方式測试,当然,django也基于python封装了一个自己的測试 ...

  7. django 一些库

    https://django-adminactions.readthedocs.io/en/latest/actions.html http://www.ziqiangxuetang.com/djan ...

  8. DJANGO变动库的一次真实手动经历

    在变更库时,由于对字段规划和约束性没考虑完全,需要手工操作数据库,以便可以重复执行. 有以下三点要注意. 1,先迎合错误输出,增删对应的表或字段. 2,必要时,修改migrations文件,以去除唯一 ...

  9. 稳定易用的 Django 分页库,完善分页功能

    作者:HelloGitHub-追梦人物 文中所涉及的示例代码,已同步更新到 HelloGitHub-Team 仓库 在 通过 Django Pagination 实现简单分页 中,我们实现了一个简单的 ...

  10. Sadmin:打造私有Django公共库实现代码复用

    我们借助于Django开发了许多的内部管理系统,例如之前介绍过的Probius.Kerrigan.Proxy等等,这些系统看起来长的都一样,但实际实现的功能确是千差万别,这些不同的系统为什么会长的一样 ...

随机推荐

  1. World Finals 2017 (水题题解)

    看大佬做2017-WF,我这种菜鸡,只能刷刷水题,勉强维持生活. 赛后补补水题. 题目pdf链接,中文的,tls翻译的,链接在这里 个人喜欢在vjudge上面刷题. E Need for Speed ...

  2. Python: PS 滤镜--表面模糊

    本文用 Python 实现 PS 滤镜中的表面模糊,具体的算法原理和效果可以参考之前的博客: http://blog.csdn.net/matrix_space/article/details/528 ...

  3. SDOI2017 Round1 Day2 题解

    T2好厉害啊……AK不了啦……不过要是SCOI考这套题就好了240保底. BZOJ4819 新生舞会 模板题,分数规划+二分图最大权匹配. 费用流跑得过,可以不用KM. UPD:分数规划用迭代跑得飞快 ...

  4. Python之Numpy详细教程

    NumPy - 简介 NumPy 是一个 Python 包. 它代表 “Numeric Python”. 它是一个由多维数组对象和用于处理数组的例程集合组成的库. Numeric,即 NumPy 的前 ...

  5. python与c#的交互模块pythonnet

    今天总结一下python与c#的交互模块pythonnet,其实微软也是有相应的解释器的,就是Ironpython,可是毕竟Ironpython还有很多东西没有从python那边继承过来,所以有时候用 ...

  6. css animation 简写和参数

  7. android项目源码

    [置顶] Android精品开源项目整理_V20140221(持续更新中..) 让我们回顾下2013年有哪些精品资源:Android精品开源项目整理_V20131115(持续更新中..) 引言:   ...

  8. 再谈使用X.PagedList.Mvc 分页(ASP.NET Core 2.1)

    在以前的博文中写过使用X.PagedList.Mvc组件来对ASP.NET MVC应用程序进行分页,可以参考此篇随笔:Asp.net MVC 使用PagedList(新的已更名 为X.PagedLis ...

  9. Bootstrap表格添加搜索栏

    在学习了表格的分页后,本文尝试在表格顶部加入搜索栏,用来筛选表格的数据,先看一下效果: 未进行搜索时,有394条记录: 在输入乘车码“1”和订单号“20150120”后,只有28条记录: 此处使用了两 ...

  10. vbs实现zip压缩

    VBS实现zip压缩 Zip "D:\test.xls", "D:\test.zip" Sub Zip(ByVal mySourceDir, ByVal myZ ...