Django:haystack全文檢索詳細教程


參考:https://blog.csdn.net/AC_hell/article/details/52875927

一、安裝第三方庫及配置

  1.1  安裝插件

  pip install whoosh django-haystack jieba

  • haystack是django的開源搜索框架,該框架支持Solr,Elasticsearch,Whoosh, *Xapian*搜索引擎,不用更改代碼,直接切換引擎,減少代碼量。
  • 搜索引擎使用Whoosh,這是一個由純Python實現的全文搜索引擎,沒有二進制文件等,比較小巧,配置比較簡單,當然性能自然略低。
  • 中文分詞Jieba,由於Whoosh自帶的是英文分詞,對中文的分詞支持不是太好,故用jieba替換whoosh的分詞組件。

  其他:Python 2.7 or 3.4.4, Django 1.8.3或者以上,Debian 4.2.6_3

  1.2  settings中添加 Haystack 到Django的 INSTALLED_APPS

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # haystack要放在應用的上面
    'haystack',
    'blog',
    'account',
    'article',
]

  1.3  settings中增加搜索引擎配置

import os
HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
        'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'),
    },
}

    ENGINE為使用的引擎必須要有,如果引擎是Whoosh,則PATH必須要填寫,其為Whoosh 索引文件的存放文件夾。
其他引擎的配置見官方文檔

二、創建索引

  2.0  查看需要檢索的model文件

      ArticlePost為存儲文章的數據模型,后面查找文章就是在這個數據模型中匹配

class ArticlePost(models.Model):

    author = models.ForeignKey(User, related_name='article')
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=500)
    column = models.ForeignKey(ArticleColumn, related_name='article_column')
    body = models.TextField()
    created = models.DateTimeField(default=timezone.now())
    updated = models.DateTimeField(auto_now_add=True)
    # media/%Y%m%d/為圖片的真實放置路徑,因為settings中已經配置了MEDIA_ROOT為media文件夾
    avatar = models.ImageField(upload_to='%Y%m%d/', blank=True)

 

  2.1  新建search_indexes.py文件

      如果你想針對某個app例如article做全文檢索,則必須在article的目錄下面建立search_indexes.py文件,且文件名不能修改。內容如下:

          

import datetime
from haystack import indexes
from .models import ArticlePost


class ArticlePostIndex(indexes.SearchIndex, indexes.Indexable):  # 類名必須為需要檢索的Model_name+Index,這里需要檢索ArticlePost,所以創建ArticlePostIndex類
    text = indexes.CharField(document=True, use_template=True)  # 創建一個text字段
    # author = indexes.CharField(model_attr='author')  # 創建一個author字段,model_attr='author'代表對應數據模型ArticlePost中的author字段,可以刪
    # title = indexes.CharField(model_attr='title')  # 創建一個title字段
    # body = indexes.CharField(model_attr='body')

    # 對那張表進行查詢
    def get_model(self):  # 重載get_model方法,必須要有!
        # 返回這個model
        return ArticlePost

    # 針對哪些數據進行查詢
    def index_queryset(self, using=None):  # 重載index_..函數
        """Used when the entire index for model is updated."""
        # return self.get_model().objects.filter(updated__lte=datetime.datetime.now())
        return self.get_model().objects.all()

 

      1、索引,就像書的目錄一樣,可以快速的導航查找內容。

      2、每個索引里面必須有且只能有一個字段為 document=True,這代表haystack 和搜索引擎將使用此字段的內容作為索引進行檢索(primary field)。其他的字段只是附屬的屬性,方便調用,並不作為檢索數據,可以刪除掉。

        只要保證ArticlePost_text.txt文件中有需要檢索的字段就行了

        {{ object.title }}
        {{ object.author }}
        {{ object.body }}

      3、如果使用一個字段設置了document=True,則一般約定此字段名為text,這是在SearchIndex類里面一貫的命名,以防止后台混亂,當然名字你也可以隨便改,不過不建議改。   

      4、並且,haystack提供了use_template=True在text字段,這樣就允許我們使用數據模板去建立搜索引擎索引的文件,說得通俗點就是索引里面需要存放一些什么東西,例如 ArticlePost的 title 字段,

        這樣我們可以通過 title 內容來檢索ArticlePost數據了,舉個例子,假如你搜索 python ,那么就可以檢索出title含有 python 的ArticlePost了,怎么樣是不是很簡單?

    2.2  新建數據模板路徑ArticlePost_text.txt

      數據模板的路徑為templates/search/indexes/article/ArticlePost_text.txt注意文件的命名格式,一定要是model_text.txt,其內容為:

{{ object.title }}
{{ object.author }}
{{ object.body }}

      這個數據模板的作用是對ArticlePost.title、ArticlePost.authorArticlePost.body這三個字段建立索引,當檢索的時候會對這三個字段做全文檢索匹配。

      

    2.3  添加url路由

     在article應用的urls.py中添加路由:url(r'search/$', SearchView(), name='haystack_search'),

 

from django.conf.urls import url
from . import views, list_views
from haystack.views import SearchView

urlpatterns=[
    url(r'^article-column/$', views.article_column, name='article_column'),
  ...
  ... # SearchView()視圖函數,默認使用的HTML模板路徑為templates/search/search.html url(r'search/$', SearchView(), name='haystack_search'), ]

 

    2.4  新建search.html模板文件

      在此位置新建templates/search/search.html,內容為:

{% extends 'base.html' %}
{% block title %}文章列表{% endblock %}

{% block content %}
    <div class="col-md-9">
    <div class="row text-center vertical-middle-sm">
        <h1>搜索結果</h1>
    </div>
  {# 如果存在搜索關鍵字 #}
    {% if query %}
        {% for result in page.object_list %}<div class="media">
            <a href="{{  result.object.get_absolute_url }}" class="list-group-item active">
                    {% if result.object.avatar %}
                        <div class="media-left">
                            <img src="{{  result.object.avatar.url }}" alt="avatar" style="max-width: 100px; border-radius: 20px">
                        </div>
            {% endif %}
                <div class="media-body">
                    <h4 class="list-group-item-heading">{{ result.object.title }}</h4>
                    <p class="list-group-item-text">作者:{{ result.object.author }}</p>
                    <p class="list-group-item-text">概要:{{ result.object.body|slice:'60'}}</p>
                </div>
            </a>
        </div>
            {% empty %}
            <h3>沒有找到相關文章</h3>
        {% endfor %}
    {% endif %}

{#        {% include 'paginator.html' %}#}
{# 分頁插件,下一頁和上一頁記得要帶上q={{ query }}參數,否則單擊下一頁時會丟失搜索參數q,而顯示出來全部的文章的第二頁#}
<div class="pagination"> <span class="step-links"> {% if page.has_previous %} <a href="?q={{ query }}&page={{ page.previous_page_number }}">上一頁</a> {% endif %} <span class="current"> Page{{ page.number }} of {{ page.paginator.num_pages }} </span> {% if page.has_next %} <a href="?q={{ query }}&page={{ page.next_page_number }}">下一頁</a> {% endif %} </span> </div></div> <div class="col-md-3"> <p class="text-center">廣告位招租</p> <a href="#"><img src="https://dm30webimages.lynkco.com.cn/LynkCoPortal/Content/images/chenxing2/03yushou/pc/4.jpg" width="260px"></a></div> {% endblock %}

 

        注意一下<a href="?q={{ query }}&page={{ page.next_page_number }}">下一頁</a>,這里不要忘了q={{query}參數,如果缺少此參數的話,單擊下一頁時會跳轉至:http://127.0.0.1:8000/article/search/?page=2,

        此時只有page=2參數,代表的是全部文章的第二頁。

 

        分頁也可以在settings中配置:

#設置每頁顯示的數目,默認為20,可以自己修改
HAYSTACK_SEARCH_RESULTS_PER_PAGE = 5

 

    2.5  增加搜索入口

        在header.html文件中新增一個input搜索框,

 

    <li><a href="{% url 'blog:blog_about' %}">關於本站</a></li>
            <li><a href="{% url 'blog:blog_contact' %}">聯系我們</a></li>
        <li>
            <form action="{% url 'article:haystack_search' %}" method="get">
                <input type="text" name="q" placeholder="請輸入關鍵字">
                <input type="submit" id="search" value="搜索">
            </form>
        </li>

{#搜索框樣式#}
<style type="text/css">
#box{
width: 380px;
margin: 30px auto;
font-family: 'Microsoft YaHei';
font-size: 14px;
}
input{
width: 200px;
border: 1px solid #e2e2e2;
height: 30px;
float: left;
background-image: url(/static/images/logo.jpg);
background-repeat: no-repeat;
background-size: 25px;
background-position:5px center;
padding:0 0 0 40px;
}
#search{
width: 78px;
height: 32px;
float: right;
background: black;
color: white;
text-align: center;
line-height: 32px;
cursor: pointer;
}

</style>
 

 

          1、input標簽的name='q',代表搜索的參數,為固定寫法,不能修改為其他值。可以查看一下視圖類haystack.views.py中是怎么接受該搜索關鍵字的

    if request.GET.get('q'):
        form = form_class(request.GET, searchqueryset=searchqueryset, load_all=load_all)

        if form.is_valid():
            query = form.cleaned_data['q']
            results = form.search()

 

          2、action="{% url 'article:haystack_search' %}",代表輸入搜索關鍵字后單擊搜索按鈕時submit到上面定義的url中,如:http://127.0.0.1:8000/article/search/?q=領克03

          3、method=“get”代表搜索的關鍵字以?q=搜索關鍵字的形式傳遞后后台

          4、視圖類haystack.views.py(可以從url中鏈接到該類查看)返回的上下文context如下:

   def get_context(self):
        (paginator, page) = self.build_page()

        context = {
            'query': self.query,
            'form': self.form,
            'page': page,
            'paginator': paginator,
            'suggestion': None,
        }

          query:搜索的關鍵字

          page:當前頁的page對象

          paginator:分頁paginator對象

           上面這三個對象我們已經在search.html搜索結果文件中使用了。

    2.6  重建索引文件、測試

       使用python manage.py rebuild_index或者使用update_index命令,中間會提示選擇,輸入y,

         完成后輸入地址http://127.0.0.1:8000/article/search/?q=領克

 

 

        注意:第一次搜索【領克】沒有搜索到結果,第二次搜索【領克03】搜索出來有結果,這是為什么呢,這是因為whoosh自帶的是英文分詞,對中文支持不是很好,所以需要使用中文分詞工具jieba

        每次數據庫更新后都需要更新索引,所以haystack為大家提供了一個接口,只要在settings.py里設置:

#自動更新索引
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'

 

三、替換為jieba分詞

  3.1  創建whoosh_cn_backend.py文件

    將文件whoosh_backend.py(路徑為:python安裝路徑\Lib\site-packages\haystack\backends\whoosh_backend.py)拷貝到article這個APP下

    並重命名為whoosh_cn_backend.py,例如article/whoosh_cn_backend.py

  3.2  修改settings中搜索引擎

      修改ENGINE參數

import os
HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'article.whoosh_cn_backend.WhooshEngine',      #article.whoosh_cn_backend便是你剛剛添加的文件
        'PATH': os.path.join(BASE_DIR, 'whoosh_index'
    },
}

    3.3  重建索引,搜索中文測試一下

      建索引:python manage.py rebuild_index

      重啟:python manag.py runserver

      再次搜索關鍵字:領克

 

 

    

 

四、高亮顯示搜索關鍵詞

  原理:

    在博客文章搜索頁中我們需要對 title、author和 body 做高亮處理:{% highlight result.object.title with query %},{% highlight result.object.body with query %}。高亮處理的原理其實就是給文本中的關鍵字包上一個 span 標簽並且為其添加 highlighted 樣式(當然你也可以修改這個默認行為,具體參見下邊給出的用法)。因此我們還要給 highlighted 類指定樣式,在 search.html 中添加即可。

  1、首先在search.html文件頂部加載{% load highlight %}

  2、再將對應的{{ result.object.author }}變量替換為:{% highlight result.object.author with query %}

  3、在最后面加上一小段css樣式,見文件的最下方

  進階用法:

    

# 使用默認值  
{% highlight result.summary with query %}  

# 這里我們為 {{ result.summary }} 里所有的 {{ query }} 指定了一個<div></div>標簽,並且將class設置為highlight_me_please,這樣就可以自己通過CSS為{{ query }}添加高亮效果了,怎么樣,是不是很科學呢  
{% highlight result.summary with query html_tag "div" css_class "highlight_me_please" %}  

# 可以 max_length 限制最終{{ result.summary }} 被高亮處理后的長度
{% highlight result.summary with query max_length 40 %}  

 

 

 

  最終的文件如下

 

  

{% extends 'base.html' %}
{#首先在頂部加載highlight#}
{% load highlight %}
{% block title %}文章列表{% endblock %}

{% block content %}
    <div class="col-md-9">
    <div class="row text-center vertical-middle-sm">
        <h1>搜索結果</h1>
    </div>
{#    <div class="container">#}
    {% if query %}
{#        {% highlight result.object.title with query %}#}
{#    {% highlight result.object.body with query %}#}
        {% for result in page.object_list %}
{#        <div class="list-group">#}
            <div class="media">
            <a href="{{  result.object.get_absolute_url }}" class="list-group-item active">
                    {% if result.object.avatar %}
                        <div class="media-left">
                            <img src="{{  result.object.avatar.url }}" alt="avatar" style="max-width: 100px; border-radius: 20px">
                        </div>
            {% endif %}
                <div class="media-body">
                    <h4 class="list-group-item-heading">{% highlight result.object.title with query %}</h4>
                    <p class="list-group-item-text">作者:{% highlight result.object.author with query %}</p>
                    <p class="list-group-item-text">概要:{% highlight result.object.body with query %}</p>
                </div>
            </a>
        </div>
            {% empty %}
            <h3>沒有找到相關文章</h3>
        {% endfor %}
    {% endif %}

{#        {% include 'paginator.html' %}#}
{#    分頁插件,下一頁和上一頁記得要帶上q={{ query }}參數,否則單擊下一頁時會丟失搜索參數q,而顯示出來全部的文章的第二頁#}
    <div class="pagination">
    <span class="step-links">
        {% if page.has_previous %}
            <a href="?q={{ query }}&page={{ page.previous_page_number }}">上一頁</a>
        {% endif %}

        <span class="current">
            Page{{ page.number }} of {{ page.paginator.num_pages }}
        </span>

        {% if page.has_next %}
            <a href="?q={{ query }}&page={{ page.next_page_number }}">下一頁</a>
        {% endif %}
    </span>
</div>
    </div>


    <div class="col-md-3">
        <p class="text-center">廣告位招租</p>
            <a href="#"><img src="https://dm30webimages.lynkco.com.cn/LynkCoPortal/Content/images/chenxing2/03yushou/pc/4.jpg" width="260px"></a>
</div>

   <style> span.highlighted { color: red; } </style>

{% endblock %}

       

        看下效果:

 

 

 五、后續優化

  5.1  高亮顯示搜索到的關鍵字 √

  5.2  統計搜索出的條目數

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM