Search code examples
djangoelasticsearchdjango-haystack

Unable to search part of a term with Django Haystack and Elasticsearch


I have a project based on

Django==1.9.2
django-haystack==2.4.1
elasticsearch==2.2.0

A very simple search view:

def search_view(request):
    query = request.GET.get('q', '')
    sqs = SearchQuerySet().filter(content=query)
    params = {
        'results': sqs,
        'query': query,
    }
    return render_to_response('results.html', params,
        context_instance=RequestContext(request))

My search index is as simple as:

class CategoryIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    name = indexes.CharField(model_attr='name')

    def get_model(self):
        return Category

    def index_queryset(self, using=None):
        return self.get_model().objects.filter(published=True)

The category_text.txt file is just:

{{ object.name }}

In my database I have a few items:

  • Acqua
  • Acquario
  • Aceto
  • Accento

When I search with my view, I have strange behaviours.

  1. Searching with query "ac" I receive no results! I was expecting to have all my items. I have tryed to change the query using .filter(content__contains=query) (I know it is the default!) but nothing changed.

  2. Searching with query "acqua" I receive 1 result (correct) with the result object, but when I try to print it, the result.object field is None (the other fields contain the correct information).

What am I doing wrong? Thank you.

UPDATE

I have found a solution to my problem number 2. Latest Haystack version from PyPi is not Django 1.9.x compatible. I have just added -e git+https://github.com/django-haystack/django-haystack.git#egg=django-haystack to my requirements.txt file and the issue is fixed. More info about that on GitHub: https://github.com/django-haystack/django-haystack/issues/1291

The other issues is still opened and I cannot find any solution to it.


Solution

  • It sounds like you may be running into a minimum number of characters issue for #1. Take a look at the Haystack documents for autocomplete which shows an approach using EdgeNgramField instead of the typical CharField.