python搜尋引擎和架構

來源:互聯網
上載者:User

標籤:roc   install   res   end   src   port   mode   text   get   

1.安裝全文檢索索引包
# 全文檢索索引架構pip install django-haystack# 全文檢索索引引擎pip install whoosh# 中文分詞架構pip install jieba

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

2.配置全文檢索索引
  • 1.安裝haystack應用

    INSTALLED_APPS = (  ...  ‘haystack‘,)
  • 2.在settings.py檔案中配置搜尋引擎

    # 配置搜尋引擎後端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 GoodsSKU

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

  • 4.指定要建立索引的欄位
    • templates下面建立目錄search/indexes/應用程式名稱

      • 比如goods應用中的GoodsSKU模型類中的欄位要建立索引檔案夾:search/indexes/goods
      • 在建立目錄下,建立goodssku_text.txt,並編輯要建立索引的欄位,如   

      • 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.urlsurl(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編寫,類似商品列表頁面

  

python搜尋引擎和架構

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.