Matching only some words in query using Django Haystack

I am currently using the following django-haystack code to do searches on my site:

def products_search_results(request):
    q = request.GET['q']
    from haystack.query import SearchQuerySet
    products = SearchQuerySet().models(Product).filter(text=q)

This uses q as the query parameter in the search. This is also using all words in q to match the results against. This is probably (?) the intended default behavior. Here is what I am seeing.

I have a Product with a title of "Red Corvette".

Of course the search term "Red", "Red Corvette" and "Corvette" all match, but the term "Red Corvette Convertible" or "Red Corvette T-top" will not match. I would really like those to match the query, especially if there are not many results to the default query.

Is there something I can do with my haystack query to get this kind of behavior?


Use EdgeNgramField for example in your search index file:

class AppIndex(indexes.SearchIndex, indexes.Indexable):

    ngram_text = indexes.EdgeNgramField()

    def prepare(self, obj):
        """Add the content of text field from final prepared data into ngram_text field
        """
        prepared_data = super(AppIndex, self).prepare(obj)
        prepared_data['ngram_text'] = prepared_data['text']
        return prepared_data

Then query on that field (Make sure to first do rebuild_index and update_index after doing above changes):

products = SearchQuerySet().models(Product).filter(ngram_text=q)
链接地址: http://www.djcxy.com/p/38694.html

上一篇: Django PostgreSQL查询不返回任何值

下一篇: 只使用Django Haystack在查询中匹配一些单词