Install and setup Haystack search for Django

So Mysql is crap at doing full text search. So in one of my projects i use Haystack so i can do full text searches.

I have a running Django project up and this is how I setup haystack for my project.

 

Install and config

sudo pip install django-haystack

 

in settings.py under INSTALLED_APPS add haystack

'haystack',

 

And also in settings.py file add some haystack settings

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

 

I have a model that looks like this

from django.db import models
# Create your models here.
class Register(models.Model):
 name = models.CharField(max_length=255)
 taxed = models.CharField(max_length=100)
 kapital = models.CharField(max_length=100)
 year = models.CharField(max_length=100)
 location = models.CharField(max_length=100)

 

Then I have an search index that that matches my model

import datetime
from haystack import indexes
from search.models import Register
class RegisterIndex(indexes.SearchIndex, indexes.Indexable):
 text = indexes.CharField(document=True,model_attr='name')
 taxed = indexes.CharField(model_attr='taxed')
 kapital = indexes.CharField(model_attr='kapital')
 location = indexes.CharField(model_attr='location')
def get_model(self):
 return Register
def index_queryset(self, using=None):
 """Used when the entire index for model is updated."""
 return self.get_model().objects.all()

 

Make it work

Sync up you database sett you mysql settings in settings.py and the run this command so that django can setup your database.

python manage.py syncd

Adding a lot of DATA to your tabel

build you index

python manage.py rebuild_index
WARNING: This will irreparably remove EVERYTHING from your search index in connection 'default'.
Your choices after this are to restore from backups or rebuild via the `rebuild_index` command.
Are you sure you wish to continue? [y/N] y
Removing all documents from your index because you said so.
All documents removed.
Indexing 130 registers

 

And then when you want to update your index you run

python manage.py update_index

So the last thing is to setup some views so I can search fulltext. This is my functions and its a ajax request from my webbapp. And it returns the data

 

def ajaxsearch(request):
 if request.method == 'POST':
 search=request.POST['search']
 location=request.POST['location']
 search_answer = SearchQuerySet().filter(text=search).filter(town=location)
 return render_to_response('test.html',{'search': search_answer},context_instance=RequestContext(request))

and here is the template that prints the data

 

{% for r in search %}
 <div class='alert alert-info'><button type='button' class='close' data-dismiss='alert'>&times;</button><strong>{{ r.text }} {{ r.location }}</strong> <br> <b>{{ r.taxed }}</b>
{% endfor %}