乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      Haystack的介紹和使用

       ZackEdge 2020-02-20

      一,什么是Haystack

        搜索是一個(gè)日益重要的話題。用戶越來越依賴于搜索從噪聲信息中分離和快速找到有用信息。此外,搜索搜索可以洞察那些東西是受歡迎的,改善網(wǎng)站上難以查找的東西。

        為此,Haystack試圖整合自定義搜索,使其盡可能簡單的靈活和強(qiáng)大到足以處理更高級的用例。haystack支持多種搜索引擎,不僅僅是whoosh,使用

      solr、elastic search等搜索,也可通過haystack,而且直接切換引擎即可,甚至無需修改搜索代碼。

      二,安裝相關(guān)的包

      pip install django-haystack
      pip install whoosh
      pip install jieba

      三,配置

        1:將Haystack添加到settings.py中的INSTALLED_APPS中:

      復(fù)制代碼
      INSTALLED_APPS = [
          'django.contrib.admin',
          'django.contrib.auth',
          'django.contrib.contenttypes',
          'django.contrib.sessions',
          'django.contrib.sites',
          # 添加
          'haystack',
          # 你的app
          'blog',
      ]
      復(fù)制代碼

        2:在你的settings.py中添加一個(gè)設(shè)置來指示站點(diǎn)配置文件正在使用的后端,以及其他的后端設(shè)置。

          HAYSTACK——CONNECTIONS是必需的設(shè)置,并且應(yīng)該至少是以下的一種:

          Solr:

      復(fù)制代碼
      HAYSTACK_CONNECTIONS = {
          'default': {
              'ENGINE': 'haystack.backends.solr_backend.SolrEngine',
              'URL': 'http://127.0.0.1:8983/solr'
              # ...or for multicore...
              # 'URL': 'http://127.0.0.1:8983/solr/mysite',
          },
      }
      復(fù)制代碼

          Elasticsearch:

      復(fù)制代碼
      HAYSTACK_CONNECTIONS = {
          'default': {
              'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
              'URL': 'http://127.0.0.1:9200/',
              'INDEX_NAME': 'haystack',
          },
      }
      復(fù)制代碼

          Whoosh:

      復(fù)制代碼
      #需要設(shè)置PATH到你的Whoosh索引的文件系統(tǒng)位置
      import os
      HAYSTACK_CONNECTIONS = {
          'default': {
              'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
              'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'),
          },
      }
      
      # 自動(dòng)更新索引
      HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
      復(fù)制代碼

          Xapian:

      復(fù)制代碼
      #首先安裝Xapian后端(http://github.com/notanumber/xapian-haystack/tree/master)
      #需要設(shè)置PATH到你的Xapian索引的文件系統(tǒng)位置。
      import os
      HAYSTACK_CONNECTIONS = {
          'default': {
              'ENGINE': 'xapian_backend.XapianEngine',
              'PATH': os.path.join(os.path.dirname(__file__), 'xapian_index'),
          },
      }
      復(fù)制代碼

         下面我們以whoosh為例進(jìn)行操作。

      四:配置路由

        在整個(gè)項(xiàng)目的urls.py中,配置搜索功能的url路徑

      urlpatterns = [
          ...
          url(r'^search/', include('haystack.urls')),
      ]

      五,創(chuàng)建索引

        在你的應(yīng)用目錄下面新建一個(gè)search_indexes.py文件,文件名不能修改!

      復(fù)制代碼
      from haystack import indexes
      from app01.models import Article
      
      class ArticleIndex(indexes.SearchIndex, indexes.Indexable):
          #類名必須為需要檢索的Model_name+Index,這里需要檢索Article,所以創(chuàng)建ArticleIndex
          text = indexes.CharField(document=True, use_template=True)#創(chuàng)建一個(gè)text字段 
          #其它字段
          desc = indexes.CharField(model_attr='desc')
          content = indexes.CharField(model_attr='content')
      
          def get_model(self):#重載get_model方法,必須要有!
              return Article
      
          def index_queryset(self, using=None):
              return self.get_model().objects.all()
      復(fù)制代碼

        ps:為什么要?jiǎng)?chuàng)建索引呢,索引就像一本書的目錄,可以為讀者提供更快速的導(dǎo)航與查找。在這里也是同樣的道理,當(dāng)數(shù)據(jù)量非常大的時(shí)候,若要從

          這些數(shù)據(jù)里找出所有滿足搜索條件的幾乎是不太可能的事情,將會(huì)給服務(wù)器帶來極大的負(fù)擔(dān),所以我們需要為指定的數(shù)據(jù)添加一個(gè)索引。

          索引實(shí)現(xiàn)的細(xì)節(jié)并不是我們需要關(guān)心的事情,但是它為哪些字段創(chuàng)建索引,怎么指定,下面來說明:

          每個(gè)索引里面必須有且只能有一個(gè)字段為 document=Ture,這代表著haystack和搜索引擎將使用此字段的內(nèi)容作為索引進(jìn)行檢索(primary field)

          其他的字段只是附屬的屬性,方便調(diào)用,并不做檢索的依據(jù)。

          注意:如果一個(gè)字段設(shè)置了document=True,則一般約定此字段名為text,這是ArticleIndex類里面一貫的寫法。

          另外,我們在text字段上提供了use_template=Ture。這允許我們使用一個(gè)數(shù)據(jù)模板,來構(gòu)建文檔搜索引擎索引。你應(yīng)該在模板目錄下建立,也就是在

          templates文件夾中建立一個(gè)新的模板,search/indexes/項(xiàng)目名/模型名_text.txt,并且將以下的內(nèi)容放入txt文件中:

      #在目錄“templates/search/indexes/應(yīng)用名稱/”下創(chuàng)建“模型類名稱_text.txt”文件
      {{ object.title }}
      {{ object.desc }}
      {{ object.content }}

          這個(gè)數(shù)據(jù)模板的作用就是對Note.titleNote.user.get_full_name,Note.body這三個(gè)字段建立索引,當(dāng)檢索的時(shí)候會(huì)對這三個(gè)字段做全文檢索匹配。

      六:編輯搜索模板

          搜索模板默認(rèn)在search/search.html中,下面的代碼足以讓你搜索運(yùn)行:

      復(fù)制代碼
      <!DOCTYPE html>
      <html>
      <head>
          <title></title>
          <style>
              span.highlighted {
                  color: red;
              }
          </style>
      </head>
      <body>
      {% load highlight %}
      {% if query %}
          <h3>搜索結(jié)果如下:</h3>
          {% for result in page.object_list %}
      {#        <a href="/{{ result.object.id }}/">{{ result.object.title }}</a><br/>#}
              <a href="/{{ result.object.id }}/">{%   highlight result.object.title with query max_length 2%}</a><br/>
              <p>{{ result.object.content|safe }}</p>
              <p>{% highlight result.content with query %}</p>
          {% empty %}
              <p>啥也沒找到</p>
          {% endfor %}
      
          {% if page.has_previous or page.has_next %}
              <div>
                  {% if page.has_previous %}
                      <a href="?q={{ query }}&page={{ page.previous_page_number }}">{% endif %}&laquo; 上一頁
                  {% if page.has_previous %}</a>{% endif %}
                  |
                  {% if page.has_next %}<a href="?q={{ query }}&page={{ page.next_page_number }}">{% endif %}下一頁 &raquo;
                  {% if page.has_next %}</a>{% endif %}
              </div>
          {% endif %}
      {% endif %}
      </body>
      </html>
      復(fù)制代碼

       

        注意:page.object_list實(shí)際上是SearchResult對象的列表。這些對象返回索引的所有數(shù)據(jù)。他們可以通過{{ result.object }}來訪問,

            所以{{ result.object.title}}實(shí)際使用的是數(shù)據(jù)庫中Article對象來訪問title字段的。

       

       

      七,重建索引

        配置完成之后,接下應(yīng)該把數(shù)據(jù)庫中的數(shù)據(jù)放入索引。Haystack中自帶了一個(gè)命令工具:

      python manage.py rebuild_index

      八,使用jieba分詞

        新建一個(gè)ChineseAnalyzer.py文件:

      復(fù)制代碼
      import jieba
      from whoosh.analysis import Tokenizer, Token
      
      class ChineseTokenizer(Tokenizer):
          def __call__(self, value, positions=False, chars=False,
                       keeporiginal=False, removestops=True,
                       start_pos=0, start_char=0, mode='', **kwargs):
              t = Token(positions, chars, removestops=removestops, mode=mode,
                        **kwargs)
              seglist = jieba.cut(value, cut_all=True)
              for w in seglist:
                  t.original = t.text = w
                  t.boost = 1.0
                  if positions:
                      t.pos = start_pos + value.find(w)
                  if chars:
                      t.startchar = start_char + value.find(w)
                      t.endchar = start_char + value.find(w) + len(w)
                  yield t
      
      
      def ChineseAnalyzer():
          return ChineseTokenizer()
      復(fù)制代碼

        保存在python安裝路徑的backends文件夾中(例如:D:\python3\Lib\site-packages\haystack\backends)

        然后在該文件夾中找到一個(gè)whoosh_backend.py文件,改名為whoosh_cn_backend.py

        在內(nèi)部添加:

      from .ChineseAnalyzer import ChineseAnalyzer 

        然后查找到這行代碼:

      analyzer=StemmingAnalyzer()

        修改為:

      analyzer=ChineseAnalyzer()

      九,在模板找中創(chuàng)建搜索欄:

      <form method='get' action="/search/" target="_blank">
          <input type="text" name="q">
          <input type="submit" value="查詢">
      </form>

        本站是提供個(gè)人知識管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊一鍵舉報(bào)。
        轉(zhuǎn)藏 分享 獻(xiàn)花(0

        0條評論

        發(fā)表

        請遵守用戶 評論公約

        類似文章 更多