Remove object from haystack index
Asked Answered
H

3

5

I delete a record using django:

 r = model.objects.get(id=1)
 r.delete()

Now I want to remove the record from the index WITHOUT re-indexing. How?

I cannot get remove_object to work and the haystack docs are too high level. I cannot just run "python manage.py update_index -- remove" because this will also re-index everything.

Honewort answered 7/3, 2014 at 5:16 Comment(0)
H
5

Ha, the answer was simple, yet hacky. Basically, the following code works, because if you time it right (no entries in the db in the last hour) it will only remove index entries for records that have been deleted. Voila.

  python manage.py update_index --remove --age=1
Honewort answered 7/3, 2014 at 7:29 Comment(1)
Actually, it'll reindex everything: github.com/django-haystack/django-haystack/blob/master/haystack/…Pixie
A
2

There are 2 options to remove single object.

  • First method:

You can remove or update single object with remove_object (Django Haystack Docs) or update_object (Django Haystack Docs) are the methods of class SearchIndex

You can provide an instance object and which connection should be used.

SearchIndex.remove_object(self, instance, using=None, **kwargs)

Remove an object from the index. Attached to the class’s post-delete hook.

SearchIndex.update_object(self, instance, using=None, **kwargs)

Update the index for a single object. Attached to the class’s post-save hook.

If using is provided, it specifies which connection should be used. >Default relies on the routers to decide which backend should be used.

Example:


from myapp.search_indexes import MyIndex

# Get the object you want to delete or update
instance = YourModel.objects.get(id=id)

# settings.HAYSTACK_CONNECTIONS / name of your index
using = "myindex_name"

# Remove object
MyIndex().remove_object(instance, using)

# Update object
MyIndex().update_object(instance, using)
  • Second method:

You can remove single object through SearchBackend.remove()

Here is some example:


from haystack import connections as haystack_connections

# Get the object you want to delete or update
instance = YourModel.objects.get(id=id)

# Get all Names/keys of your indexes / settings.HAYSTACK_CONNECTIONS
backend_names = haystack_connections.connections_info.keys()

# Get key of connection for your object
using = backend_names[0]

# Get the backend 
backend = haystack_connections[using].get_backend()

# To remove object
backend.remove(instance)
Almita answered 26/2, 2021 at 14:5 Comment(1)
This method is better than python manage.py update_index --remove --age=1.Sinful
U
0

Actually a much easier solution is to use a SignalProcessor (docs), connecting to the post_delete will remove the document automatically when you remove it from the orm.

Underling answered 22/3, 2017 at 8:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.