pip install django-haystack
python
INSTALLED_APPS = [
...
'haystack',
...
]
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch2_backend.Elasticsearch2SearchEngine',
'URL': 'http://localhost:9200/',
'INDEX_NAME': 'haystack',
},
}
python
from haystack import indexes
from .models import Post
class PostIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
title = indexes.CharField(model_attr='title')
def get_model(self):
return Post
def index_queryset(self, using=None):
return self.get_model().objects.all()
python manage.py rebuild_index
python
from haystack.query import SearchQuerySet
def search_posts(request):
query = request.GET.get('q')
results = SearchQuerySet().filter(content=query)
return render(request, 'search_results.html', {'results': results})
html
{% for result in results %}
<h3>{{ result.object.title }}</h3>
<p>{{ result.object.content }}</p>
{% empty %}
<p>No results found.</p>
{% endfor %}