Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't get partial word search to work with haystack/elasticsearch

I'm trying to get partial word match working and I've already looked at related question but for some reason my setup doesn't work. I'm using haystack with elasticsearch. Can someone please tell me what I'm doing wrong?

class VendorIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.EdgeNgramField(document=True, use_template=True)
    company_name = indexes.CharField(model_attr='company_name', null=True)

    def get_model(self):
        return Vendor

    def index_queryset(self, using=None):
        """Used when the entire index for model is updated."""
        return self.get_model().objects.all()

EDIT: I've made this work by making use of autocomplete. However, I feel like this is a hack. But here is my code:

class VendorIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    company_name = indexes.CharField(model_attr='company_name', null=True)
    company_name_auto = indexes.NgramField(model_attr='company_name')
    def get_model(self):
        return Vendor

    def index_queryset(self, using=None):
        """Used when the entire index for model is updated."""
        return self.get_model().objects.all()

then in the View:

class SearchVendorView(generics.ListAPIView):
    serializer_class = serializers.CustomerVendorSerializer

    def get_queryset(self):
        results = SearchQuerySet().models(Vendor).autocomplete(company_name_auto=self.request.GET.get('q', ''))
        vendors = []

        for vendor in [result.object for result in results]:
            vendor.is_liked = Vendor.objects.from_request(self.request).get(pk=vendor.id).user_vote  
            vendors.append(vendor)      

        return vendors
like image 365
Riz Avatar asked Nov 09 '22 23:11

Riz


1 Answers

In my case: django-haystack==2.5.1 + elasticsearch==5.0.1 + java elastic search daemon v2.3.1 this is enough to get partial search:

from haystack import indexes
from authors.models import Author


class AuthorIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.EdgeNgramField(document=True, use_template=True)
    last_name = indexes.CharField(model_attr='last_name')
    first_name = indexes.CharField(model_attr='first_name')

    def get_model(self):
        return Author

    def index_queryset(self, using=None):
        """Used when the entire index for model is updated."""
        return self.get_model().objects.all()

And then python manage.py rebuild_index and you can search by:

from haystack.query import SearchQuerySet
SearchQuerySet().filter(content="alex")

to find Alexander.

like image 173
valex Avatar answered Nov 15 '22 10:11

valex