zoukankan      html  css  js  c++  java
  • 全文检索

    # **全文检索简介**

    ### 什么是全文检索

    ​    全文检索是计算机程序通过扫描文章中的每一个词,对必要的词建立一个索引,指明该词在文章中出现的次数和位置。当用户查询时根据建立的索引查找,类似于通过字典的检索字表查字的过程。

        全文检索(Full-Text Retrieval)是指以文本作为检索对象,找出含有指定词汇的文本。全面、准确和快速是衡量全文检索系统的关键指标。
        
        关于全文检索,我们要知道:1,只处理文本。2,不处理语义。3,搜索时英文不区分大小写。4,结果列表有相关度排序。5,并且可以对结果具有过滤高亮的功能

       在信息检索工具中,全文检索是最具通用性和实用性的。

    ### 全文检索应用场景

    ​    我们使用Lucene,主要是做站内搜索,即对一个系统内的资源进行搜索。如BBS、BLOG中的文章搜索,网上商店中的商品搜索等。所以,学完Lucene后我们就可以为自已的项目增加全文检索的功能。

        例如一些基于商城的全文检索系统:在项目中构建一个对于商品的全文检索功能,让买家先搜索索引库中的内容,得到商品的基本信息而且是按照某种规则排序的(例如热卖、点击率.....),感兴趣在通过连接.读取数据库的完成数据,这样既可以实现高效的查询效率,又可以为分流查询请求。

    ### 全文检索与数据查询的区别

        1.  相关度排序: 查出的结果没有相关度排序,不知道我想要的结果在哪一页。我们在使用百度搜索时,一般不需要翻页,为什么?因为百度做了相关度排序:为每一条结果打一个分数,这条结果越符合搜索条件,得分就越高,叫做相关度得分,结果列表会按照这个分数由高到低排列,所以第1页的结果就是我们最想要的结果
           2.  查询的方式: 全文检索的速度大大快于SQL的like搜索的速度。这是因为查询方式不同造成的,以查字典举例:数据库的like就是一页一页的翻,一行一行的找,而全文检索是先查目录,得到结果所在的页码,再直接翻到这一页
    3.  定位不一样:一个更侧重高效、安全的存储、一个是侧重准确、方便的搜索
     
    django全文检索组件
     全文检索里的组件简介

      **1、什么是haystack?**

        1. haystack是django的开源搜索框架,该框架支持Solr,Elasticsearch,Whoosh, *Xapian*搜索引擎,不用更改代码,直接切换引擎,减少代码量。

        2. 搜索引擎使用Whoosh,这是一个由纯Python实现的全文搜索引擎,没有二进制文件等,比较小巧,配置比较简单,当然性能自然略低。

        3. 中文分词Jieba,由于Whoosh自带的是英文分词,对中文的分词支持不是太好,故用jieba替换whoosh的分词组件。
      2、什么是jieba?

        1、很多的搜索引擎对中的支持不友好,jieba作为一个中文分词器就是加强对中文的检索功能

      3、Whoosh是什么?

        1、Python的全文搜索库,Whoosh是索引文本及搜索文本的类和函数库

        2、Whoosh 自带的是英文分词,对中文分词支持不太好,使用 jieba 替换 whoosh 的分词组件。
     django全文检索实现
    
    ### **安装工具**
    
    ```
    pip install django-haystack
    pip install whoosh
    pip install jieba
    ```
    
    #### **在setting.py中配置**
    
    ```python
    '''注册app '''
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        # haystack要放在应用的上面
        'haystack',
        'jsapp',  # 这个jsapp是自己创建的app
    ]
    
    
    ''' 模板路径 '''
    TEMPLATES = [
        {
            'DIRS': [os.path.join(BASE_DIR,'templates')],
    
        },
    ]
    
    
    '''配置haystack '''
    # 全文检索框架配置
    HAYSTACK_CONNECTIONS = {
        'default': {
            # 指定whoosh引擎
            'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
            # 'ENGINE': 'jsapp.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'
    ```
    
    
    
    #### 定义数据库
    
    ```python
    from django.db import models
    
    # Create your models here.
    class UserInfo(models.Model):
        name = models.CharField(max_length=254)
        age = 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()
    ```
    
    ## **索引文件生成**
    
      **1)在子应用下创建索引文件**
    
        **在子应用的目录下,创建一个名为 jsapp`/search_indexes.py` 的文件**
    
    ```python
    #! /usr/bin/env python
    # -*- coding: utf-8 -*-
    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()
    ```
    
    ​        **2)指定索引模板文件** 
    
    ```python
    # 创建文件路径命名必须这个规范:templates/search/indexes/应用名称/模型类名称_text.txt
    # templates/search/indexes/jsapp/articlepost_text.txt
    ```
    
    ![img](./assets/1394324-20200410162406166-1863812528.png)
    
    
    
    ```python
    #templates/search/indexes/jsapp/articlepost_text.txt
    
    {{ object.title }}
    {{ object.author.name }}
    {{ object.body }}
    ```
    
    
    
    ​        **3)使用命令创建索引**
    
    ```python
    python manage.py rebuild_index  # 建立索引文件
    ```
    
    
    
    ## 替换成jieba分词**
    
      **1)将haystack源码复制到项目中并改名**
    
    
    
    ```python
    '''1.复制源码中文件并改名 '''
    将 C:python37Libsite-packageshaystackackendswhoosh_backend.py文件复制到项目中
    并将 whoosh_backend.py改名为 whoosh_cn_backend.py 放在APP中如:jsappwhoosh_cn_backend.py
    
    '''2.修改源码中文件'''
    # 在全局引入的最后一行加入jieba分词器
    from jieba.analyse import ChineseAnalyzer
    
    # 修改为中文分词法
    查找
    analyzer=StemmingAnalyzer()
    改为
    analyzer=ChineseAnalyzer()
    ```
    
    
    
      **2)Django内settings内修改相应的haystack后台文件名**
    
    
    
    ```python
    # 全文检索框架配置
    HAYSTACK_CONNECTIONS = {
        'default': {
            # 指定whoosh引擎
            'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
            # 'ENGINE': 'jsapp.whoosh_cn_backend.WhooshEngine',      #article.whoosh_cn_backend便是你刚刚添加的文件
            # 索引文件路径
            'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
        }
    }
    # 添加此项,当数据库改变时,会自动更新索引,非常方便
    HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
    ```
    
    
    
     
    
    ## 索引文件使用
    
    #### 设置urls.py
    
    ```python
    from django.conf.urls import url
    from . import views as view
    
    urlpatterns=[
        url(r'abc/$', view.basic_search),
    
    ]
    ```
    
    #### 完成views.py的检索
    
    ```python
    from django.shortcuts import render
    
    # Create your views here.
    import json
    from django.conf import settings
    from django.core.paginator import InvalidPage, Paginator
    from django.http import Http404, HttpResponse,JsonResponse
    from haystack.forms import  ModelSearchForm
    from haystack.query import EmptySearchQuerySet
    RESULTS_PER_PAGE = getattr(settings, 'HAYSTACK_SEARCH_RESULTS_PER_PAGE', 20)
    
    
    
    def basic_search(request, load_all=True, form_class=ModelSearchForm, searchqueryset=None, extra_context=None, results_per_page=None):
        query = ''
        results = EmptySearchQuerySet()
        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()
        else:
            form = form_class(searchqueryset=searchqueryset, load_all=load_all)
    
        paginator = Paginator(results, results_per_page or RESULTS_PER_PAGE)
        try:
            page = paginator.page(int(request.GET.get('page', 1)))
        except InvalidPage:
            result = {"code": 404, "msg": 'No file found!', "data": []}
            return HttpResponse(json.dumps(result), content_type="application/json")
    
        context = {
            'form': form,
            'page': page,
            'paginator': paginator,
            'query': query,
            'suggestion': None,
        }
        if results.query.backend.include_spelling:
            context['suggestion'] = form.get_suggestion()
    
        if extra_context:
            context.update(extra_context)
    
    
        jsondata = []
        print(len(page.object_list))
        for result in page.object_list:
            data = {
                'pk': result.object.pk,
                'title': result.object.title,
                'content': result.object.body,
    
            }
            jsondata.append(data)
        result = {"code": 200, "msg": 'Search successfully!', "data": jsondata}
        return JsonResponse(result, content_type="application/json")
    ```
    
    
    
    ![img](./assets/postman.png)
    django全文检索的实现
     
  • 相关阅读:
    确保EF上下文线程内唯一
    linq的join
    编码:隐匿在计算机软硬件背后的语言
    EF删除数据
    插入数据返回主键值用 output inserted.UId
    Fancybox丰富的弹出层效果
    回车登录
    “:Choose a destination with a supported architecture in order to run on this device.”
    How to Enable Multi-Touch
    How does CCFileUTils::fullPathForFilename work
  • 原文地址:https://www.cnblogs.com/anle123/p/13359680.html
Copyright © 2011-2022 走看看