Search code examples
pythondjangoelasticsearchdjango-haystack

Serialize Haystack SearchQuerySet


I have some Django queries dumped in files that are delayed so I pass as parameter sql_with_params to later execute in the delayed a raw query.

I have migrated all queries to haystack so I wan't to do the same with SearchQuerySet.

Is there any way to get the raw_query of an already constructed SearchQuerySet?

PD: I am using ElasticSearch


Solution

  • Sure, here's one way that unfortunately requires a bit of plumbing. You can create a custom search engine and set its query to your own query definition inheriting from ElasticsearchSearchQuery:

    from haystack.backends.elasticsearch_backend import ElasticsearchSearchEngine, ElasticsearchSearchQuery
    
    
    class ExtendedElasticsearchSearchQuery(ElasticsearchSearchQuery):
        def build_query(self):
            raw_query = super(ExtendedElasticsearchSearchQuery, self).build_query()
            # TODO: Do something with raw query
            return raw_query
    
    class ExtendedElasticsearchSearchEngine(ElasticsearchSearchEngine):
        query = ExtendedElasticsearchSearchQuery
    

    and reference that from your settings:

    HAYSTACK_CONNECTIONS = {
        'default': {
            'ENGINE': 'myapp.mymodule.ExtendedElasticsearchSearchEngine',
            'URL': 'http://localhost:9200/',
            'INDEX_NAME': 'haystack'
        },
    }