Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Haystack autocompletion on two (multiple) fields

I use haystack 1.2.6 with Whoosh 2.4 and Django 1.3. Let's say that we have the below model describing an hypothetical post.

Post(models.Model):
    title = models.CharField()
    body = models.TextField()

We built our post index like this for autocompletion on body field:

PostIndex(SearchIndex):
    text = CharField(document=True, use_template=True)
    content_auto = indexes.EdgeNgramField(model_attr='body')

Having read the haystack documentation thoroughly i cannot find if is possible to have autocompletion on both title and body fields.

So ... is it possible or ... ?

like image 717
geros Avatar asked Sep 04 '12 11:09

geros


2 Answers

I've managed to do it based on this. You just make an EdgeNgramField for each field you want to autocomplete on in your index, then apply the autocompletion to two different search querysets and concatenate them:

sqs = SearchQuerySet().models(Post)
sqs1 = sqs.filter(title_auto=q)
sqs2 = sqs.filter(body_auto=q)

sqs = sqs1 | sqs2

If you have to do extra filtering, you need to do it after the autocompletion one (at least this was the only way it worked for me).

like image 66
Facundo Olano Avatar answered Sep 30 '22 16:09

Facundo Olano


Here's a simpler way, do the concatenation in the template & use EdgeNgramField (although doing that on the body of a post is expensive :

#In search_indexes.py
PostIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.EdgeNgramField(document=True, use_template=True)

#In <app>\template\search\index\<app>\post_text.txt
{{ object.title }} {{object.body}}

Then all such queries will autocomplete on both title & body

sqs = SearchQuerySet().models(Post).autocomplete(text='hello')

P.S. Using Haystack 2.x

like image 36
user Avatar answered Sep 30 '22 16:09

user