1. 程式人生 > 其它 >Django全文搜尋框架haystack 和 drf_haystack

Django全文搜尋框架haystack 和 drf_haystack

1、安裝和配置

# 安裝
pip install whoosh
pip install jieba
pip install django-haystack
pip install drf_haystack

配置

# 在INSTALL_APPS里加上 haystack (加在最後)
INSTALLED_APPS = [
    ...
    'haystack',
    ...
]
# 增加搜尋引擎配置(有solr,whoosh,elastic search),這裡選擇whoosh
HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
        'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'),
    },
}
# 配置自動更新索引
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
# 配置搜尋結果的分頁器的每頁數量(rest-framework裡面用不到)
# HAYSTACK_SEARCH_RESULTS_PER_PAGE = 10

2、指明要索引的欄位


建立上圖所示路徑及檔案

# 建立檔案 templates/search/indexes/myapp/note_text.txt
# myapp是想要建立索引的app,note是你要建立縮印的那個模型名字(小寫)
# txt檔案內容:將title、content、和id三個欄位新增到索引
{{ object.title }}
{{ object.content }}
{{ object.id }}

3、編輯search_indexes.py檔案

# 在app中新建search_indexes.py檔案,並編輯以下內容
from haystack import indexes

from .models import Article


class ArticleIndex(indexes.SearchIndex, indexes.Indexable):
    """
    Article索引資料模型類
    """
    text = indexes.CharField(document=True, use_template=True)
    id = indexes.IntegerField(model_attr='id')
    title = indexes.CharField(model_attr='title')
    content = indexes.CharField(model_attr='content')
    # 下面的createtime欄位並沒有在上面加索引,寫上是因為後面的過濾filter和排序order_by用到
    # 注意:這裡修改的話一定要重新建立索引,才能生效。python manage.py rebuild_index
    createtime = indexes.DateTimeField(model_attr='createtime')

    def get_model(self):
        """返回建立索引的模型類"""
        return Article

    def index_queryset(self, using=None):
        """返回要建立索引的資料查詢集"""
        return self.get_model().objects.all()

4、編輯索引的serializer序列化器

# 在serializer.py檔案中進行編輯
class ArticleIndexSerializer(HaystackSerializer):
    """
    Article索引結果資料序列化器
    """
    class Meta:
        index_classes = [ArticleIndex]
        fields = ('text', 'id', 'title', 'content', 'createtime')
        # 這裡可以寫ignore_fields來忽略搜尋那個欄位

5、編輯檢視

class ArticleSearchViewSet(HaystackViewSet):
    """
    Article搜尋
    """
    index_models = [Article]
    serializer_class = ArticleIndexSerializer

6、別忘了編輯路由

router.register('articles/search', views.ArticleSearchViewSet, base_name='articles_search')

參考了:https://blog.csdn.net/smartwu_sir/article/details/80209907