Skip to content

Commit 07e11a3

Browse files
authored
Merge pull request #222 from Xpirix/improve_haystack_indexing
Switch to CelerySignalProcessor for asynchronous indexing in Haystack
2 parents 0666dc7 + 59b7dc1 commit 07e11a3

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

qgis-app/plugins/signals.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
from celery import shared_task
2+
from haystack import signals
3+
from haystack.exceptions import NotHandled
4+
5+
6+
@shared_task
7+
def update_search_index(action, instance_pk, app_label, model_name):
8+
"""Async task to update search index"""
9+
from django.apps import apps
10+
11+
try:
12+
model_class = apps.get_model(app_label, model_name)
13+
instance = model_class.objects.get(pk=instance_pk)
14+
15+
from haystack import connection_router, connections
16+
17+
using_backends = connection_router.for_write(instance=instance)
18+
19+
for using in using_backends:
20+
try:
21+
index = connections[using].get_unified_index().get_index(model_class)
22+
if action == "update":
23+
index.update_object(instance, using=using)
24+
elif action == "delete":
25+
index.remove_object(instance, using=using)
26+
except NotHandled:
27+
pass
28+
29+
except model_class.DoesNotExist:
30+
pass # Instance was deleted
31+
except Exception as e:
32+
# Log error but don't fail
33+
import logging
34+
35+
logging.error(f"Search index update failed: {e}")
36+
37+
38+
class CelerySignalProcessor(signals.BaseSignalProcessor):
39+
"""Signal processor that queues updates to Celery"""
40+
41+
def handle_save(self, sender, instance, **kwargs):
42+
update_search_index.delay(
43+
"update", instance.pk, instance._meta.app_label, instance._meta.model_name
44+
)
45+
46+
def handle_delete(self, sender, instance, **kwargs):
47+
update_search_index.delay(
48+
"delete", instance.pk, instance._meta.app_label, instance._meta.model_name
49+
)

qgis-app/settings.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,8 @@
198198
}
199199

200200
# Migration: see http://django-haystack.readthedocs.org/en/latest/migration_from_1_to_2.html#removal-of-realtimesearchindex
201-
HAYSTACK_SIGNAL_PROCESSOR = "haystack.signals.RealtimeSignalProcessor"
201+
# Use CelerySignalProcessor for async indexing via Celery
202+
HAYSTACK_SIGNAL_PROCESSOR = "plugins.signals.CelerySignalProcessor"
202203

203204
# Added by Tim for database based caching
204205
# See http://docs.djangoproject.com/en/dev/topics/cache/

0 commit comments

Comments
 (0)