Skip to content

Instantly share code, notes, and snippets.

@toastdriven
Created March 4, 2011 08:27
Show Gist options
  • Select an option

  • Save toastdriven/854331 to your computer and use it in GitHub Desktop.

Select an option

Save toastdriven/854331 to your computer and use it in GitHub Desktop.
# At a shell...
mkdir whooshtest
cd whooshtest
virtualenv --no-site-packages .
. bin/activate
./bin/pip install -E . django
./bin/pip install -E . django-haystack
./bin/pip install -E . whoosh==1.2.6
./bin/django-admin.py startproject whooshtest
cd whooshtest
chmod 755 manage.py
# Edit settings.py, match these:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'whooshtest.db', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Later in settings.py...
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'haystack',
'appy',
)
import os
HAYSTACK_SEARCH_ENGINE = 'whoosh'
HAYSTACK_WHOOSH_PATH = os.path.join(os.path.dirname(__file__), 'the_index')
HAYSTACK_SITECONF = 'search_sites'
# At the shell
./manage.py startapp appy
# In search_sites.py
import haystack
haystack.autodiscover()
# In appy/models.py
import datetime
from django.db import models
class Grumble(models.Model):
title = models.CharField(max_length=64)
views = models.PositiveIntegerField(default=0)
created = models.DateTimeField(blank=True, null=True, default=datetime.datetime.now)
def __unicode__(self):
return self.title
# In appy/search_indexes.py
import haystack
from haystack import indexes
from models import Grumble
class GrumbleIndex(indexes.SearchIndex):
text = indexes.CharField(document=True, model_attr='title')
title = indexes.CharField(model_attr='title')
views = indexes.IntegerField(model_attr='views')
created = indexes.DateTimeField(model_attr='created')
haystack.site.register(Grumble, GrumbleIndex)
# Sync it.
./manage.py syncdb
# Drop in some fixture/model data.
# Build the index.
./manage.py rebuild_index --noinput --verbosity=2
# Explore at a Django shell.
./manage.py shell
>>> from haystack.query import SearchQuerySet
>>> SearchQuerySet().filter(views__gte=3)
[<got two results back here (out of three)>]
>>> SearchQuerySet().filter(views__lt=3)
[<got one result back here>]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment