49、elasticsearch(搜索引擎)用Django实现搜索结果分页

百度云搜索,搜各种资料:http://www.lqkweb.com
搜网盘,搜各种资料:http://www.swpan.cn
酷站群,搜各种网站源码:http://www.kuzq.cn

逻辑处理函数

  计算搜索耗时
  在开始搜索前:start_time = datetime.now()获取当前时间
  在搜索结束后:end_time = datetime.now()获取当前时间
  last_time = (end_time-start_time).total_seconds()结束时间减去开始时间等于用时,转换成秒

from django.shortcuts import render

# Create your views here.
from django.shortcuts import render,HttpResponse
from django.views.generic.base import View
from app1.models import lagouType               # 导入操作elasticsearch(搜索引擎)类
import json
from elasticsearch import Elasticsearch         # 导入原生的elasticsearch(搜索引擎)接口
client = Elasticsearch(hosts=["127.0.0.1"])     # 连接原生的elasticsearch
from datetime import datetime

def indexluoji(request):
    print(request.method)  # 获取用户请求的路径
    return render(request, 'index.html')

def suggestluoji(request):                                      # 搜索自动补全逻辑处理
    key_words = request.GET.get('s', '')                        # 获取到请求词
    re_datas = []
    if key_words:
        s = lagouType.search()                                  # 实例化elasticsearch(搜索引擎)类的search查询
        s = s.suggest('my_suggest', key_words, completion={
            "field": "suggest", "fuzzy": {
                "fuzziness": 1
            },
            "size": 5
        })
        suggestions = s.execute_suggest()
        for match in suggestions.my_suggest[0].options:
            source = match._source
            re_datas.append(source["title"])
    return HttpResponse(json.dumps(re_datas), content_type="application/json")

def searchluoji(request):                                       # 搜索逻辑处理
    key_words = request.GET.get('q', '')                        # 获取到请求词
    page = request.GET.get('p', '1')                            # 获取访问页码
    try:
        page = int(page)
    except:
        page = 1
    start_time = datetime.now()                                 # 获取当前时间
    response = client.search(                                   # 原生的elasticsearch接口的search()方法,就是搜索,可以支持原生elasticsearch语句查询
        index="lagou",                                          # 设置索引名称
        doc_type="biao",                                        # 设置表名称
        body={                                                  # 书写elasticsearch语句
            "query": {
                "multi_match": {                                # multi_match查询
                    "query": key_words,                         # 查询关键词
                    "fields": ["title", "description"]          # 查询字段
                }
            },
            "from": (page-1)*10,                                          # 从第几条开始获取
            "size": 10,                                         # 获取多少条数据
            "highlight": {                                      # 查询关键词高亮处理
                "pre_tags": [''],         # 高亮开始标签
                "post_tags": [''],                       # 高亮结束标签
                "fields": {                                     # 高亮设置
                    "title": {},                                # 高亮字段
                    "description": {}                           # 高亮字段
                }
            }
        }
    )
    end_time = datetime.now()                                   # 获取当前时间
    last_time = (end_time-start_time).total_seconds()           # 结束时间减去开始时间等于用时,转换成秒
    total_nums = response["hits"]["total"]                      # 获取查询结果的总条数
    if (page % 10) > 0:                                         # 计算页数
        paga_nums = int(total_nums/10)+1
    else:
        paga_nums = int(total_nums/10)
    hit_list = []                                               # 设置一个列表来储存搜索到的信息,返回给html页面
    for hit in response["hits"]["hits"]:                        # 循环查询到的结果
        hit_dict = {}                                           # 设置一个字典来储存循环结果
        if "title" in hit["highlight"]:                         # 判断title字段,如果高亮字段有类容
            hit_dict["title"] = "".join(hit["highlight"]["title"])      # 获取高亮里的title
        else:
            hit_dict["title"] = hit["_source"]["title"]                 # 否则获取不是高亮里的title

        if "description" in hit["highlight"]:                           # 判断description字段,如果高亮字段有类容
            hit_dict["description"] = "".join(hit["highlight"]["description"])[:500]    # 获取高亮里的description
        else:
            hit_dict["description"] = hit["_source"]["description"]     # 否则获取不是高亮里的description

        hit_dict["url"] = hit["_source"]["url"]                         # 获取返回url

        hit_list.append(hit_dict)                                       # 将获取到内容的字典,添加到列表
    return render(request, 'result.html', {"page": page,                # 当前页码
                                           "total_nums": total_nums,    # 数据总条数
                                           "all_hits": hit_list,        # 数据列表
                                           "key_words": key_words,      # 搜索词
                                           "paga_nums": paga_nums,      # 页数
                                           "last_time": last_time       # 搜索时间
                                           })                           # 显示页面和将列表和搜索词返回到html

HTML



{#引入静态文件路径#}
{% load staticfiles %}



python-lcv-search搜索引擎





    
        
                                           
    
                          文章             问答             职位              
                                           网站
                                     
  •                         伯乐在线                         (None)                     
  •                     
  •                         知乎                         (9862)                     
  •                     
  •                         拉勾网                         (9862)                     
  •                                                                           更多                                                                                                                                                   
                
                                                      找到约 {{ total_nums }} 条结果(用时{{ last_time }}秒),共约{{ paga_nums }}页                 

                                         {% for hit in all_hits %}                                                                                   {% autoescape off %} {{ hit.title }} {% endautoescape %}                                 -                                                                      来源:                                     网络                                                                                                       得分:                                     3.401155                                                                                                                            {% autoescape off %} {{ hit.description }} {% endautoescape %}                                                                           {% endfor %}                                                                                                                                    
    热门搜索
                                                     
  • linux
  •                                                                            
    我的搜索
                                                                                          Copyright ©projectsedu.com 版权所有  E-mail:[email protected]     var search_url = "/search/"     $('.searchList').on('click', '.searchItem', function(){         $('.searchList .searchItem').removeClass('current');         $(this).addClass('current');         });     $.each($('.subfieldContext'), function(i, item){         $(this).find('li:gt(2)').hide().end().find('li:last').show();             });     function removeByValue(arr, val) {       for(var i=0; i     $('.searchList').on('click', '.searchItem', function(){         $('.searchList .searchItem').removeClass('current');         $(this).addClass('current');     });     // 联想下拉显示隐藏     $('.searchInput').on('focus', function(){         $('.dataList').show()     });     // 联想下拉点击     $('.dataList').on('click', 'li', function(){         var text = $(this).text();         $('.searchInput').val(text);         $('.dataList').hide()     });     hideElement($('.dataList'), $('.searchInput'));

    结果:

    image

    image

    你可能感兴趣的:(elasticsearch,django)