Skip to content

Instantly share code, notes, and snippets.

@benspaulding
Created December 11, 2010 22:21
Show Gist options
  • Save benspaulding/737694 to your computer and use it in GitHub Desktop.
Save benspaulding/737694 to your computer and use it in GitHub Desktop.
A custom RealTimeSearchIndex that also removes objects from the index when saved such that they should be.
from django.db.models import signals
from haystack import indexes
class RealTimeSearchIndex(indexes.RealTimeSearchIndex):
"""
A variant of the stock ``RealTimeSearchIndex`` that constantly keeps the
index fresh, including removing an object when it is saved to a state such
that it should no longer be in the index. (The latter is not done by the
stock one.)
"""
def should_update(self, instance, **kwargs):
"""
Determine if an object should be updated in the index.
Different from the stock method in that this one does not always
return true. Rather, we verify that we should actually update the
object.
"""
if instance in self.get_queryset():
return True
return False
def update_object(self, instance, **kwargs):
"""
Update the index for a single object. Attached to the class's
post-save hook.
"""
# Check to make sure we want to index this first.
if self.should_update(instance, **kwargs):
self.backend.update(self, [instance])
else:
# Otherwise, remove it.
self.remove_object(instance)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment