18
Nov
Reindexing a single object using Django & Haystack
If you’re using Django & Haystack, and you want to reindex a single object, you would dothe following:
from haystack import site
site.get_index(YourModel).update_object(your_instance)
This is useful if you have objects that are related in some kind of hierarchy, but you store them flattened in Haystack. So, when you update one of the leaf objects, you would need to reindex the root object, and thus, the code above.
BTW, I’m pretty annoyed that haystack used the term “site”. I would have preferred it to be something more haystack-specific. Maybe “haystack_engine” or something? I can always say “from haystack import site as haystack_engine” but that style seems to lead into a world of incompatible code.
If you’re using the standard “SearchIndex“ (soon to become “RealTimeSearchIndex“), just saving the model in question will update the document in the index. If not, your code is correct.
As for “site“, it really refers to a customized registry of models available for the site it serves. It was also chosen because it was consistent with “admin.site.register(Model, ModelAdmin)“, so that most users would find it more familiar. And care was taken to namespace to the “haystack“ module to prevent collisions with other objects.
Yeah, I know that saving the model will also update the index, I should have mentioned that my model has something akin to “last_modified=DateTimeField(auto_now=True)”. So, I don’t want to call save() on the model, because it would result in updating of the last_modified time, which is incorrect.
Oh, and I’m not sure I buy your argument about “site”. You have to remember that “http://localhost:8000/admin” is actually a “site”. It includes models, views, etc. With Haystack, on the other hand, I like the symmetry with the admin interface, but I don’t think of it as it’s own “site”. It’s much more like a reusable app. I’d still prefer if it were called something like “engine”. Just because you’re modeling on the admin API doesn’t mean you can’t make some other changes here and there when they make sense.
BTW, If SearhcIndex is becoming RealTimeSearchIndex, does that mean that there’s a Non-realtime search index as well? What’s the difference? I guess I should just read the source.