How do I do a partial field match using Haystack?

django, django-haystack, search, search-engine

Solution

You can achieve that behavior by making your index's text field an EdgeNgramField:

class PersonIndex(SearchIndex):
    text = EdgeNgramField(document=True, use_template=True)
    first_name = CharField(model_attr = 'first_name')
    last_name = CharField(model_attr = 'last_name')

Problem

I needed a simple search tool for my django-powered web site, so I went with Haystack and Solr. I have set everything up correctly and can find the correct search results when I type in the exact phrase, but I can't get any results when typing in a partial phrase. For example: "John" returns "John Doe" but "Joh" doesn't return anything. Model: ``` class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) ``` Search Index: ``` class PersonIndex(SearchIndex): text = CharField(document=True, use_template=True) first_name = CharField(model_attr = 'first_name') last_name = CharField(model_attr = 'last_name') site.register(Person, PersonIndex) ``` I'm guessing there's some setting I'm missing that enables partial field matching. I've seen people talking about `EdgeNGramFilterFactory()` in some forums, and I've Googled it, but I'm not quite sure of its implementation. Plus, I was hoping there was a haystack-specific way of doing it in case I ever switch out the search backend.

Original source