django-haystack+jieba+whoosh

'''
haystack 是什么
 -- haystack 是Django开源搜索的框架,搜索引擎使用whoosh,这是一个由纯Pyhon实现的全文搜索引擎,没有二进制文件等,配置比较简单,性能比较低
中文jieba分词,由于whoosh自带是英文分词,对中文分词支持不是太好,故用jieba替换whoosh的分词组件
'''
# 安装这三个
pip install django-haystack
pip install whoosh
pip install jieba
创建一个django项目 
# django-admin startproject Hays
# cd Hays
# python manage.py startapp app
# INSTALLED_APPS = [

    'haystack', # 注意上下顺序
    'app'
]
TEMPLATES = [
        'DIRS': [os.path.join(BASE_DIR,'templates')],
]

# 配置mysql
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME':'haystsearch',
        'USER':'root',
        'PASSWORD':'',
        'PORT':'3306'
    }
}

#  全文搜索配置
HAYSTACK_CONNECTIONS = {
    'default': {
        # 指定whoosh引擎
        # 'ENGINE': 'haystack.backends.whoosh_cn_backend.WhooshEngine',
        'ENGINE': 'app.whoosh_cn_backend.WhooshEngine',      # whoosh_cn_backend是haystack的whoosh_backend.py改名的文件为了使用jieba分词
        # 索引文件路径
        'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
    }
}
# 添加此项,当数据库改变时,会自动更新索引,非常方便
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'    
配置settings
├─app
│  ├─migrations
│  │  └─__pycache__
│  └─__pycache__
├─Hays
│  └─__pycache__
├─templates
│  └─search
│      └─indexes
│          └─app
└─whoosh_index
from haystack import indexes
from .models import ArticlePost

# 修改此处,类名为模型类的名称+Index,比如模型类为GoodsInfo,则这里类名为GoodsInfoIndex(其实可以随便写)
class ArticlePostIndex(indexes.SearchIndex, indexes.Indexable):
    # text为索引字段
    # document = True,这代表haystack和搜索引擎将使用此字段的内容作为索引进行检索
    # use_template=True 指定根据表中的那些字段建立索引文件的说明放在一个文件中
    text = indexes.CharField(document=True, use_template=True)

    # 对那张表进行查询
    def get_model(self):  # 重载get_model方法,必须要有!
        # 返回这个model
        return ArticlePost

    # 建立索引的数据
    def index_queryset(self, using=None):
        # 这个方法返回什么内容,最终就会对那些方法建立索引,这里是对所有字段建立索引
        return self.get_model().objects.all()
app/search_indexes.py
from django.db import models

# Create your models here.


class UserInfo(models.Model):
    name = models.CharField(max_length=32)
    gae  = models.IntegerField()


class ArticlePost(models.Model):
    author = models.ForeignKey(UserInfo,on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    desc = models.SlugField(max_length=500)
    body = models.TextField()
app/models.py
from django.urls import path
from haystack.views import SearchView
from app import views

urlpatterns = [
    path('search/',SearchView()),
    # path('searchs/',views.searchs)  # 不用
]
app/urls
{{ object.title } }
{{ object.author.name }}
{{ object.body }}
templates/search/indexes/app/articlepost_text.txt
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
</head>
<body>
    <div class="col-md-9">
    <div class="row text-center vertical-middle-sm">
{#        <li>#}
           <form method='get' action="/app/search/" target="_blank">
              <input type="text" name="q">
              <input type="submit" value="查询">
</form>
{#        </li>#}
    </div>
  {# 如果存在搜索关键字 #}
    {% if query %}
        {% for result in page.object_list %}<div class="media">
                <div class="media-body">
                    <h4 class="list-group-item-heading">{{ result.object.title }}</h4>
                    <p class="list-group-item-text">作者:{{ result.object.author.name }}</p>
                    <p class="list-group-item-text">概要:{{ result.object.body|slice:'60'}}</p>
                </div>
            </a>
        </div>
            {% empty %}
            <h3>没有找到相关文章</h3>
        {% endfor %}
    {% endif %}

{#    分页插件,下一页和上一页记得要带上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>
</body>
</html>
templates/search/search.html
'''1.复制源码中文件并改名 '''
## python 环境修改
将 D:\python\Lib\site
-packages\haystack\backends\whoosh_backend.py文件复制到项目中 并将 whoosh_backend.py改名为 whoosh_cn_backend.py
放在APP中如:app\whoosh_cn_backend.py

'''2.修改源码中文件'''
# 在全局引入的最后一行加入jieba分词器
from jieba.analyse import ChineseAnalyzer

# 修改为中文分词法
查找
analyzer=StemmingAnalyzer()
改为
analyzer=ChineseAnalyzer()

 

python manage.py rebuild_index                      # 建立索引文件


'''
y
## 创建成功 ##如果配置不对 就会失败
Building prefix dict from the default dictionary ...
Loading model from cache C:\Users\ADMINI~1\AppData\Local\Temp\jieba.cache
Loading model cost 0.853 seconds.
Prefix dict has been built successfully.
'''
# 主要路由分发 这里我就不写了
# 数据库里面自己添加内容就可以了
# 完成nice
最后访问:http://127.0.0.1:8000/app/search/

 

 

 

posted @ 2020-07-10 16:19  Handsome、Snake  阅读(216)  评论(0编辑  收藏  举报