If you use any of the result.object.*
fields it will do a DB lookup and hit your SQL database.
Try eg. result.city
directly, that should use the data from the index and avoid the SQL DB hit.
Django haystack querying database
-
16-07-2023 - |
Pergunta
I am having this weird issue while referring to a specific field on the view, django makes a SQL query, although it a haystack index.
search_indexes.py
class StoreIndex(indexes.ModelSearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
city = indexes.CharField(model_attr='city__name', faceted=True)
region = indexes.CharField(model_attr='region__name', faceted=True)
country = indexes.CharField(model_attr='country__name')
created_at = indexes.DateTimeField(model_attr='created_at')
tags = indexes.MultiValueField(model_attr='tags__names', faceted=True)
def get_model(self):
return Store
def index_queryset(self, using=None):
"""Used when the entire index for model is updated."""
return self.get_model().objects.filter(created_at__lte=datetime.datetime.utcnow())
urls.py
queryset = SearchQuerySet().facet('tags').facet('region').facet('city')
urlpatterns = patterns('haystack.views',
url(r'^search', FacetedSearchView(form_class=FacetedSearchForm, searchqueryset=queryset),
name='haystack_search'),
)
results.html
<!-- Begin results. -->
<div id="search-results">
<ul>
{% for result in page.object_list %}
{% include 'search/_result_object.html' %}
{% empty %}
<p>No results found.</p>
{% endfor %}
</ul>
</div>
<!-- End results. -->
_result_object.html
{% with object=result.object %}
<li class="search-result">
<section>
<h3>{{ object.name }}</h3>
<p>{{ object.addressLine1 }}, {{ object.addressLine2 }}, {{ object.addressLine3 }} </p>
<strong> {{ object.city }}, {{ object.region }} </strong>
<strong class="pull-right"><a href="{% url 'store_detail' pk=object.id %}">Details</a></strong>
</section>
</li>
{% endwith %}
It queries database when accessing {{ object.city }}, {{ object.region }}
I have verified, both city and region get stored in elasticsearch as proper names.
Thanks in advance.
Solução
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow