Open cs246810 opened 3 years ago
'default': { 'ENGINE': 'haystack.backends.elasticsearch5_backend.Elasticsearch5SearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'article', }, 'example': { 'ENGINE': 'haystack.backends.elasticsearch5_backend.Elasticsearch5SearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'videoad', }
drf-haystack query result always use
default
connection, The question is how to useexample
for query?This haystack doc could use connection you want.
from haystack.query import SearchQuerySet # Uses the routers' opinion. sqs = SearchQuerySet().auto_query('banana') # Forces the default. sqs = SearchQuerySet().using('default').auto_query('banana') # Forces the slave connection (presuming it was setup). sqs = SearchQuerySet().using('slave').auto_query('banana')
But I use drf-haystack.
Suppose you have a Haystack connection configured in your settings.py
file like this:
HAYSTACK_CONNECTIONS = {
# Default connection settings go here ...
'example': {
'ENGINE': "haystack.backends.solr_backend.SolrEngine",
'URL': "http://127.0.0.1:8983/solr/example",
'ADMIN_URL': "http://127.0.0.1:8983/solr/admin/cores"
}
}
In this example, we’ve defined a custom Haystack connection called example
, which is configured to use the Solr engine.
drf-haystack
To use this specific connection (like example
) with drf-haystack
in your views, you can set it directly within the get_queryset
method of your view class. By appending .using('example')
to the SearchQuerySet
, you ensure that the correct Haystack connection is used for your search queries.
Here’s how you can implement this in your view:
class BillViewSet(HaystackViewSet):
index_models = [Bill] # This will include only Bill Django model results in the SearchQuerySet()
serializer_class = BillSerializer
def get_queryset(self, index_models=[]):
# Ensure the query uses the 'example' Haystack connection
sqs = super(BillViewSet, self).get_queryset(index_models).using("example")
return sqs
Once you have set up the connection, you can inspect the SearchQuerySet
to confirm that it is correctly targeting the example
connection. You can do this by printing the sqs
object in a debugger like pdb
:
(Pdb) print(sqs)
<SearchQuerySet: query=<haystack.backends.solr_backend.SolrSearchQuery object at 0x74f8bae8dc40>, using='example'>
(Pdb) print(sqs._using)
example
Here, sqs._using
should print example
, indicating that the query is indeed using the correct connection.
HAYSTACK_CONNECTIONS
setting allows you to define multiple search connections..using('example')
in your get_queryset
method to specify which connection to use when querying.SearchQuerySet
object.This approach ensures that your view queries the correct Haystack connection, making it easier to work with multiple search engines or configurations in a single project.
drf-haystack query result always use
default
connection, The question is how to useexample
for query?This haystack doc could use connection you want.
But I use drf-haystack.