I am trying to use django-haystack for search functionality in our product. When user enters a any search keyword(ie 'computer'), it should search for this keyword against multiple fields. Eg when a user enters "Computer" it should find the objects where "Computer" is present in any of the field in that object. But there is a problem. If a user enters only "Comp" into search field, it isn't finding objects at all.
So I have tried to use autocomplete. With autocomplete I was able to achieve this for only one field. For other fields again its failing return result.
I am having haystack with whoosh as backend.
Environment Detail:
Django v1.5.3
Haystack v2.1.0
Whoosh v2.5.3
Following is defined in my search_index.py file.
class Message_Index(indexes.SearchIndex, indexes.Indexable):
text = indexes.EdgeNgramField(document=True, use_template=True)
message = indexes.CharField(model_attr='messagetext', null=True)
forum = indexes.CharField(model_attr='forum', null=True)
status = indexes.CharField(model_attr='status', null=True)
tags = indexes.CharField(model_attr='tags', null=True)
author_name = indexes.EdgeNgramField(null=True)
author_number = indexes.EdgeNgramField(null=True)
message_date = indexes.DateTimeField(null=True)
def get_model(self):
return Message
def index_queryset(self, using=None):
return self.get_model().objects.all()
def prepare_author_name(self, obj):
return obj.message.user.name
def prepare_author_number(self, obj):
return obj.message.user.number
def prepare_message_date(self, obj):
return obj.message.date
def prepare_tags(self, obj):
return [tag.tag for tag in obj.tags.all()]
def prepare_message_thread(self, obj):
return obj.message.thread
I am trying to search in following way:
when I am trying to search with search_keyword = 'user1', its returning the correct result, but when I am entering search_keyword = '223', its not returning any result.
results_by_name = results.autocomplete(author_name=search_keyword)
results_by_number = results.autocomplete(author_number=search_keyword)
if results_by_name.count() > 0:
combined_resultsets(results,results_by_name,'message_date')
elif results_by_number.count() > 0:
combined_resultsets(results,results_by_number,'message_date')
combined_resultsets is function and defined as below:
def combined_resultsets(resultset1, resultset2, sortby):
if sortby is not None:
resultset1 = sorted(chain(resultset1, resultset2),key=attrgetter(sortby))
else:
resultset1 = chain(resultset1, resultset2)
Could someone help me with this?
please setting your url project to autocomplete method on view.py application root. you can follow documentation haystack on Autocomplete , and please check your template indexes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.