美文网首页
django全文检索的实现

django全文检索的实现

作者: 楚糖的糖 | 来源:发表于2018-10-29 22:02 被阅读0次

    1在虚拟环境项目下安装

    pip instal django-haystack
    pip install whoosh
    

    自动的将django升级为2.0.7版本后,要再pip install django==1.8.2

    2.在settings.py下进行注册haystack,并进行配置

    INSTALLED.APPS=('haystack',)
    

    配置搜索引擎:

        'default': {
            #使用whoosh引擎
            'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
            #索引文件路径
            'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
        }
    }
    #当添加、修改、删除数据时,自动生成索引
    HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
    
    

    3.在一级路由下添加搜索的url配置

    url(r'^search/', include('haystack.urls')),                 #全文检索
    

    ==============================================
    1在apps/goods下新建search_indexes.py文件

    # 定义索引类
    from haystack import indexes
    # 导入模型类
    from goods.models import GoodsSKU
    
    # 指定某类的某些数据建立索引
    # 索引类名格式:模型类名+Index
    class GoodsSKUIndex(indexes.SearchIndex, indexes.Indexable):
    # 索引字段,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.all()
    

    ========================================================
    1.在\templates\search\indexes\goods下新建goodssku_text.txt

    {{object.name}}
    {{object.desc}}
    {{object.goods.detail}}
    
    注意:不是将这个goodssku_text.txt命名成什么名字就是名字,要与初始化索引数据下寻找的txt文件进行对比

    ==============================================

    2.初始化索引数据(也是生成索引文件):

    python manage.py rebuild_index
    

    结束后会在项目下出现一个whoosh_index的文件

    3在表单中使用如下

    <form action="/search" method="get">
                    <input type="text" class="input_text fl" name="q" placeholder="搜索商品">
        <input type="submit" class="input_btn fr" name="" value="搜索">
    </form>
    

    4.在\templates\search下新建search.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>搜寻结果</title>
    </head>
    <body>
    搜索的关键字是:{{ query }}<br>
    当前页的Page对象:{{ page.object }}<br>
    
    <ul>
        {% for item in page %}
            <li>{{ item.object }}</li>
        {% endfor %}
    </ul>
    分页paginator对象:{{ paginator }}<br>
    </body>
    </html>
    

    =============================================
    5.全文检索结果页面的美化:

    {% extends 'base_detail_list.html' %}
    {% block title %}天天生鲜--{{ query }}商品搜索结果{% endblock title %}
    {% block main_content %}
        <div class="breadcrumb">
            <a href="#">{{ query }}</a>
            <span></span>
            <a href="#">搜索结果</a>
        </div>
        <div class="main_wrap clearfix">
                <ul class="goods_type_list clearfix">
                    {% for item in page %}
                    <li>
                        <a href="{% url 'goods:detail' item.object.id %}"><img src="{{ item.object.image.url }}"></a>
                        <h4><a href="{% url 'goods:detail' item.object.id %}">{{ item.object.name }}</a></h4>
                        <div class="operate">
                            <span class="prize">¥{{ item.object.price }}</span>
                            <span class="unit">{{ item.object.price }}/{{ item.object.unite }}</span>
                            <a href="#" class="add_goods" title="加入购物车"></a>
                        </div>
                    </li>
                {% endfor %}
                </ul>
                <div class="pagenation">
                    {% if page.has_previous %}
                        <a href="/search?q={{ query }}&page={{ page.previous_page_number }}">上一页</a>
                    {% endif %}
                    {% for pindex in paginator.page_range %}
                        {% if pindex == page.number %}
                            <a href="/search?q={{ query }}&page={{ pindex }}" class="active">{{ pindex }}</a>
                        {% else %}
                             <a href="/search?q={{ query }}&page={{ pindex }}">{{ pindex }}</a>
                        {% endif %}
                    {% endfor %}
                    {% if skus_page.has_next %}
                         <a href="/search?q={{ query }}&page={{ page.next_page_number }}">下一页</a>
                    {% endif %}
                </div>
    
        </div>
    {% endblock main_content %}
    
    

    =========================================================
    分词处理
    使用的分词方式是jieba 分词,首先pip install jieba
    1理解使用jieba分词,在项目中,打开ipython3

    import jieba 
    str = "很不错的草莓"
    res = jieba.cut(str,cut_all=True)
    res
    for val in res
        print(val)
    

    2.在项目中的使用
    C:\Users\yc\Envs\dailyfresh\Lib\site-packages\haystack\backends下创建ChineseAnalyzer.py文件
    在ChineseAnalyzer.py中的代码如下

    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()
    
    

    3.在C:\Users\yc\Envs\dailyfresh\Lib\site-packages\haystack\backends复制whoosh_backend.py文件,改为whoosh_cn_backend.py:
    (1)导包

    from .ChineseAnalyzer import ChineseAnalyzer
    

    (2)更改词语分析类:在163行左右

    schema_fields[field_class.index_fieldname] = TEXT(stored=True,analyzer=ChineseAnalyzer(), field_boost=field_class.boost, sortable=True)
    

    4修改settings.py文件中的配置项:将whoosh_backend改为whoosh_cn_backend

    全文检索框架的配置

    HAYSTACK_CONNECTIONS = {
        'default': {
            #使用whoosh引擎
            'ENGINE': 'haystack.backends.whoosh_cn_backend.WhooshEngine',
            #索引文件路径
            'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
        }
    }
    

    5.重新创建索引文件:

    python manage.py rebuild_index
    

    重新运行项目

    python manage.py runserver
    

    6.实现查询到的东西的分页问题

    HAYSTACK_SEARCH_RESULTS_PER_PAGE =1     # 指定搜索结果每页显示的条数
    

    相关文章

      网友评论

          本文标题:django全文检索的实现

          本文链接:https://www.haomeiwen.com/subject/dnwitqtx.html