Search code examples
djangodjango-haystack

Django haystack - Create multiple indexes for the same model


Say, I have a User model with the following definition:

class User(models.Model):
    username = models.CharField(max_length=30, unique=True)
    email = models.EmailField(max_length=255)
    first_name = models.CharField(max_length=30, blank=True, default='')
    last_name = models.CharField(max_length=30, blank=True, default='')
    user_role = models.IntegerField(choices=USER_CHOICES, default=USER_ROLE)

Now, I want to create two separate Indexes for Users : AdminUserIndex and UserIndex each with different set of fields and configurations but derived from the same User model.

As per documentation and testing Haystack has One-to-One mapping with the specified model, so this directly does not seem possibe.

So, one way is to add all the configuration in the same Index and filter them as required, is there any other cleaner way where I don't have to mix the two of them ?

Thanks for your replies in advance!


Solution

  • I've been looking for an answer to this same question and I've tried following the recommendations that the errors Haystack gives me.

    Firstly, it's definitely not possible to have multiple indexes on the same connection (that's documented). However, the error message implies that I might be able to exclude an index. In your case this would be:

    HAYSTACK_CONNECTIONS = {
        'default': {
            'ENGINE': 'haystack.backends.solr_backend.SolrEngine',
            'URL': 'http://localhost:9001/solr/default',
            'EXCLUDE_INDEXES': ['path.to.AdminUserIndex'],
        },
        'admin': {
            'ENGINE': 'haystack.backends.solr_backend.SolrEngine',
            'PATH': 'http://localhost:9001/solr/default',
            'EXCLUDE_INDEXES': ['path.to.UserIndex'],
        },
    }
    

    However, Haystack calls unified_index.get_index(model) which find the same model even across the two connections so this seems like a no-go either.

    Whilst I can't definitely answer that it's not possible, I think most of the obvious avenues are excluded.

    Update

    Having read around about this, it seems like you can trick Haystack into allowing this by using a proxy model. See this issue on Haystack's github issues.