Django Haystack autocompletion on two (multiple) fields
Asked Answered
D

2

6

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 ... ?

Dispread answered 4/9, 2012 at 11:29 Comment(0)
M
9

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

Micropathology answered 15/4, 2013 at 22:23 Comment(0)
H
4

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

Hepatitis answered 7/10, 2014 at 13:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.