django-es / django-elasticsearch-dsl

This is a package that allows indexing of django models in elasticsearch with elasticsearch-dsl-py.
Other
1.02k stars 261 forks source link

Multi model single index possiblity #457

Closed pfk-beta closed 11 months ago

pfk-beta commented 1 year ago

Hello,

I have made few bad decisions about app and models architectures, and I don't have power to do refactoring and data migrations. So I have 4 similar, but different models in Django. And I need make them searchable, and to avoid multiple queries. I was wondering, if it possible to index them in single index, something similarly to content_types / generic foreign keys in django.

--edit-- I'm pretty sure it won't be possible, but maybe there is a chance

violuke commented 11 months ago

You might be able to keep them as 4 indexes but do a multi-index search (so it searches all 4 at once). We do this in our project.

pfk-beta commented 11 months ago

Awesome thanks. After your comment, I can see, that I can pass multi indexes to search object. I go further with django-elasticsearch-dsl-drf:

class BaseMultiDocumentViewSet(mixins.ListModelMixin,
                               GenericViewSet):

    document_uid_field = 'id'
    documents = None  # Re-define
    pagination_class = PageNumberPagination
    dictionary_proxy = DictionaryProxy
    # permission_classes = (AllowAny,)
    ignore = []

    def __init__(self, *args, **kwargs):
        self.run_checks()

        if self.documents:
            # assume all documents has the same connection
            self.client = connections.get_connection(
                self.documents[0]._get_using()
            )

            self.indicies = [document._index._name for document in self.documents]
            self.doc_types = [document._doc_type.name for document in self.documents]
            self.search = Search(
                using=self.client,
                index=self.indicies,
                doc_type=self.doc_types
            )

        super(BaseMultiDocumentViewSet, self).__init__(*args, **kwargs)