python搜索引擎和框架

1.安裝全文檢索包

# 全文檢索框架 pip install django-haystack # 全文檢索引擎 pip install whoosh # 中文分詞框架 pip install jieba

heystack一些配置都是固定寫好的,須要注意下html

2.配置全文檢索

  • 1.安裝haystack應用python

    INSTALLED_APPS = ( ... 'haystack', ) 
  • 2.在settings.py文件中配置搜索引擎django

    # 配置搜索引擎後端 HAYSTACK_CONNECTIONS = { 'default': { # 使用whoosh引擎:提示,若是不須要使用jieba框架實現分詞,就使用whoosh_backend 'ENGINE': 'haystack.backends.whoosh_cn_backend.WhooshEngine', # 索引文件路徑 'PATH': os.path.join(BASE_DIR, 'whoosh_index'),  # 在項目目錄下建立文件夾 whoosh_index } } # 當添加、修改、刪除數據時,自動生成索引 HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
  • 3.在要創建索引的表對應的應用下,建立search_indexes.py文件 
      • 定義商品索引類GoodsSKUIndex(),繼承自indexes.SearchIndexindexes.Indexable後端

      • from haystack import indexes
        from .models import GoodsSKU框架


        class GoodsSKUIndex(indexes.SearchIndex, indexes.Indexable):
          # 定義字符類型的屬性,名稱固定爲text
          # document=True表示創建的索引數據存儲到文件中
          # use_template=True表示經過模板指定表中的字段,用於查詢
          text = indexes.CharField(document=True, use_template=True)測試

          # 針對哪張表進行查詢
          def get_model(self):
            return GoodsSKUui

          # 針對哪些行進行查詢
          def index_queryset(self, using=None):
            return self.get_model().objects.filter(isDelete=False)               搜索引擎

  • 4.指定要創建索引的字段

    • templates下面新建目錄search/indexes/應用名url

      • 好比goods應用中的GoodsSKU模型類中的字段要創建索引文件夾:search/indexes/goods
      • 在新建目錄下,建立goodssku_text.txt,並編輯要創建索引的字段,以下圖   spa

      • templates/search/indexes/goods/goodssku_text_txt

  • 5.生成索引文件

     
  • # 在終端運行, 提示是否要刪除原有信息, 輸入y
  • python manage.py rebuild_index
  • 搜索表單處理

    • 搜索地址:/search/
    • 搜索方法:get
    • 接收關鍵字:q
    • action="/search/"    method="get"    文本框的name= "q" 爲固定寫法
                                          
        

配置搜索地址正則

import haystack.urls url(r'^search/', include(haystack.urls)), 

測試搜索效果,接收結果

  • 全文檢索結果:

    • 搜索出結果後,haystack會把搜索出的結果傳遞給templates/search目錄下的search.html
    • 對於search.html,咱們須要本身創建該html文件,並定義本身的搜索結果頁面 
  • 傳遞的上下文包括:

    • query:搜索關鍵字
    • page:當前頁的page對象
    • paginator:分頁paginator對象
    • 提示:
      • settings.py文件中設置HAYSTACK_SEARCH_RESULTS_PER_PAGE
      • 經過HAYSTACK_SEARCH_RESULTS_PER_PAGE能夠控制每頁顯示數量
      • 每頁顯示一條數據:HAYSTACK_SEARCH_RESULTS_PER_PAGE = 1
  • search.html編寫,相似商品列表頁面

  

相關文章
相關標籤/搜索