How do I do a partial field match using Haystack? How do I do a partial field match using Haystack? django django

How do I do a partial field match using Haystack?


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')


In addition to the EdgeNgramField hint that others mentioned in this page (and of course NgramField, if you work with Asian languages), I think it is worth to mention that in Django_haystack you can run raw queries on Solr via following command:

from haystack.query import SearchQuerySetfrom haystack.inputs import RawSearchQuerySet().filter(text=Raw(query))

where text is the field you want to search, and the query can be anything based on Query Parser Syntax (version 3.6, or 4.6) of Lucene.

In this way you can easily set the query to ABC* or ABC~ or anything else which fits to the syntax.


I had a similar issue while searching for non english words, for instance:

ABCABCD

If I want to search for keywords ABC, I will expect the above two results. I was able to achieve the following by converting the keyword to lowercase and using startswith:

keywords = 'ABC'results.filter(code__startswith=keywords.lower())