安装haystack
$ pip install django-haystack
需要安装并配置好solr,详见:猛击这里,接下来开始配置Django,首先在项目目录中新建search_sites.py文件,内容是:
import haystack
haystack.autodiscover()
编辑 settings.py文件加入haystack模块,指定Solr作为搜索引擎:
INSTALLED_APPS = (
#other apps
'haystack',
)
HAYSTACK_SITECONF = 'search_sites' #之前创建的文件名
HAYSTACK_SEARCH_ENGINE = 'solr'
HAYSTACK_SOLR_URL = 'http://127.0.0.1:8080/solr/'#solr所在服务器
HAYSTACK_SOLR_TIMEOUT = 60 * 5
HAYSTACK_INCLUDE_SPELLING = True
HAYSTACK_BATCH_SIZE = 100
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.solr_backend.SolrEngine',
'URL': 'http://127.0.0.1:8080/solr' #solr所在服务器
},
}
在
urls.py里引入haystack:
url(r'^search/', include('haystack.urls')),
现在打开这个地址/search/会提示找不到相应的模板文件,在模板文件夹中创建/search/search.html:
{% block content %}
<h2>Search</h2>
<form method="get" action=".">
<table>
{{ form.as_table }}
<tr>
<td> </td>
<td>
<input type="submit" class="btn btn-success" value="Search">
</td>
</tr>
</table>
{% if query %}
<h3>Results</h3>
{% for result in page.object_list %}
<p>
<a href="#">{{ result.object.name }}</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 }}&page={{ page.previous_page_number }}">{% endif %}« Previous{% if page.has_previous %}</a>{% endif %}
|
{% if page.has_next %}<a href="?q={{ query }}&page={{ page.next_page_number }}">{% endif %}Next »{% if page.has_next %}</a>{% endif %}
</div>
{% endif %}
{% else %}
{# Show some example queries to run, maybe query syntax, something else? #}
{% endif %}
</form>
{% endblock %}
假设我要搜索的Model是test应用中的search_test。在test目录下创建 search_indexes.py:
from haystack import indexes, site
from apps.products.models import Product
class TestIndex(indexes.SearchIndex):
text = indexes.CharField(document=True, use_template=True)
title = indexes.CharField(model_attr='name')
def get_model(self):
return Product
def index_queryset(self):
return self.get_model().objects.all()
site.register(search_test, TestIndex)
但现在还无法搜索,要生成一个与现有Model对应的schema,把它写入Solr:
python manage.py build_solr_schema > /etc/solr/conf/schema.xml
执行 python mange.py rebuild_index,成功后就可以使用Solr提供的搜索功能了.
另可以能不需要模板来实现搜索,而是写一个接口提供给客户端,在上面的基础上做如下操作:
from haystack.query import SearchQuerySet
sqs = SearchQuerySet().auto_query(query_string=q) #q 为查询条件
然后根据具体需求来对查询结果集sqs操作。
另更新solr索引只需要:
python manage.py update_index
至于update_index的一些具体参数,经验证 有的不能使用