Django 连通Elasticsearch之前后台串联

来自CloudWiki
跳转至: 导航搜索

前言

我们在Django 连通ElasticsearchDjango 连通Elasticsearch之创建表单中分别用Django框架 连通了后台的ES 和前台的表单,现在让我们把django的前后台连接起来,使得表单搜索的关键字 能直接进入后台ES查询,并显示结果

基本版

修改视图层

我们在表单的视图层文件 search.py 中,添加拥有查询ES的代码:

# -*- coding: utf-8 -*-

from django.http import HttpResponse
from django.shortcuts import render_to_response

import traceback
from elasticsearch import Elasticsearch
from .ElasticObj import ElasticObj

# 表单
def search_form(request):
    return render_to_response('search_form.html')

# 提交后的接收请求数据
def search(request):
    obj = ElasticObj("ott1", "ott_type1")
    h = obj.Get_Data_By_Body("电视")#搜索电视
    return HttpResponse(h)

添加表单参数

现在我们尝试将前台表单传过来的参数,传到ES中进行查询:

# -*- coding: utf-8 -*-

from django.http import HttpResponse
from django.shortcuts import render_to_response

import traceback
from elasticsearch import Elasticsearch
from .ElasticObj import ElasticObj

# 表单
def search_form(request):
    return render_to_response('search_form.html')

# 提交后的接收请求数据
def search(request):
    request.encoding='utf-8'
    if 'q' in request.GET:
        obj = ElasticObj("ott1", "ott_type1")
        h = obj.Get_Data_By_Body(request.GET['q'])#搜索电视
        #message = '你搜索的内容为: ' + request.GET['q']

    else:
        h =""
    return HttpResponse(h)

测试

登录前台搜索页:http://10.0.0.30:8000/blog/search_form/

Big1-25.png

点击搜索:

Big1-26.png

改进版

改进版的效果是 将ES搜索到的各个变量拆解,

然后将他们在网页模板上展现出来。

修改视图层

我们在表单的视图层文件 search.py 中,将ES获取到的信息拆解,以便在html中显示

# 提交后的接收请求数据
def search(request):
    request.encoding='utf-8'
    if 'q' in request.GET:
        obj = ElasticObj("ott1", "ott_type1")
        h = obj.Get_Data_By_Body(request.GET['q'])#搜索电视
        #message = '你搜索的内容为: ' + request.GET['q']

    else:
        h =""
    context          = {}
    #context['title0'] = h[0]['_source']
    context['title0'] = h[0]['_source']['title']
    context['source0'] = h[0]['_source']['source']
    context['link0'] = h[0]['_source']['link']
    #context['hello'] = "hello world"

    return render(request, 'test.html', context)

修改模板层

为项目引入一个搜索结果页的模板:

tutorial/templates/test.html

 <h2>{{title0}}</h2>
<p><b>{{source0}}</b}<
<p>{{link0}}</p>

测试

登录前台搜索页:http://10.0.0.30:8000/blog/search_form/

Big1-25.png

点击搜索:

Big1-27.png