django-elasticsearch-dsl icon indicating copy to clipboard operation
django-elasticsearch-dsl copied to clipboard

Filtering elements before indexing them

Open flaa opened this issue 5 years ago • 2 comments

Is there currently an easy way to filter elements before indexing them? If for example I had Car model and would like to index cars, but only red ones?

I could probably use ELASTICSEARCH_DSL_SIGNAL_PROCESSOR in settings to provide my own class for handling on-save signal, where I would filter cars before indexing them. But how could I populate the whole index from scratch? I think search_index command will index each and every Car

flaa avatar Jul 17 '20 15:07 flaa

This issue might help you: https://github.com/django-es/django-elasticsearch-dsl/issues/111

Basically you can override the get_queryset method from the Document class, which is called by the search_index command to populate your index.

Something like:

class CarDocument(Document):
    ...

    class Django:
        model = Car

    def get_queryset(self):
        queryset = super().get_queryset()
        return queryset.filter(color='red')

rafascar avatar Jul 17 '20 19:07 rafascar

@rafascar oh this is so simple yet perfect, thank you

flaa avatar Jul 17 '20 20:07 flaa