下面我将详细讲解“es+flask搜索小项目实现分页+高亮的示例代码”完整攻略,包含两条示例说明。
示例一:使用Python Flask框架和Elasticsearch检索引擎实现搜索功能
步骤一:准备工作
- 安装Python Flask框架以及它的依赖包。
- 安装Elasticsearch检索引擎驱动程序的Python客户端库:elasticsearch-py。
步骤二:构建Flask应用程序框架
from flask import Flask, request, render_template, jsonify
from elasticsearch import Elasticsearch
app = Flask(__name__)
es_host = "localhost"
es_port = "9200"
index_name = "my_index"
es = Elasticsearch([{'host': es_host, 'port': es_port}])
@app.route("/")
def home():
return render_template("search.html")
@app.route("/search", methods=['POST'])
def search():
keywords = request.form['keywords']
# 搜索请求:
search_results = es.search(index=index_name, body={
"query": {
"multi_match": {
"query": keywords,
"fields": ["title^3", "content", "author^2"]
}
},
"highlight": {
"pre_tags": ["<b>"],
"post_tags": ["</b>"],
"fields": {
"title": {},
"content": {},
"author": {}
}
}
})
# 处理搜索结果:
hits = search_results['hits']['hits']
results = []
for hit in hits:
result = hit['_source']
result['id'] = hit['_id']
result['score'] = hit['_score']
result['highlight'] = hit['highlight']
results.append(result)
return jsonify({"results": results})
步骤三:使用Jinja2模板引擎创建搜索页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>搜索</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<form id="search_form" action="/search" method="POST">
<input type="text" name="keywords" placeholder="搜索关键字">
<input type="submit" value="搜索">
</form>
<table>
<thead>
<tr>
<th>标题</th>
<th>作者</th>
<th>正文</th>
<th>关键词</th>
<th>得分</th>
</tr>
</thead>
<tbody id="search_results">
</tbody>
</table>
<script>
$("#search_form").submit(function (event) {
event.preventDefault(); // 防止提交
var keywords = $("input[name='keywords']").val();
$.ajax({
type: "POST",
url: "/search",
data: {"keywords": keywords},
dataType: "json",
success: function (response) {
var results = response['results'];
$("#search_results").html("");
for (var i = 0; i < results.length; i++) {
var result = results[i];
var title = result['highlight']['title'][0];
var content = result['highlight']['content'][0];
var author = result['highlight']['author'][0];
var keywords = result['keywords'];
var score = result['score'];
var tr = '<tr><td>' + title + '</td>' +
'<td>' + author + '</td>' +
'<td>' + content + '</td>' +
'<td>' + keywords + '</td>' +
'<td>' + score + '</td></tr>';
$("#search_results").append(tr);
}
},
error: function (response) {
console.log(response);
}
})
});
</script>
</body>
</html>
以上就是使用Python Flask框架和Elasticsearch检索引擎实现搜索功能的完整攻略。
示例二:Flask+Elasticsearch实现分页+高亮搜索
步骤一:在mapping上启用highlight属性
修改创建index的mapping,将需要高亮的fields加上highlight属性,例如:
{
"mappings": {
"properties": {
"title": {"type": "text", "analyzer": "ik_max_word", "search_analyzer": "ik_max_word", "fields": {"raw": {"type": "keyword"}} ,"index": True ,"highlight": {"type": "unified", "pre_tags": "<i>", "post_tags": "</i>", "number_of_fragments": 3}},
"content": {"type": "text", "analyzer": "ik_smart", "search_analyzer": "ik_smart", "fields": {"raw": {"type": "keyword"}} ,"index": True ,"highlight": {"type": "unified", "pre_tags": "<i>", "post_tags": "</i>", "number_of_fragments": 3}}
}
}
}
步骤二:在查询中指定高亮部分
修改查询部分代码,使用Query DSL指定高亮部分。
from flask import Flask, request, render_template, jsonify
from elasticsearch import Elasticsearch
app = Flask(__name__)
es_host = "localhost"
es_port = "9200"
index_name = "my_index"
es = Elasticsearch([{'host': es_host, 'port': es_port}])
@app.route('/')
def index():
return render_template('index.html')
@app.route('/search')
def search():
keywords = request.args.get('keywords', '')
page = int(request.args.get('page', 1))
page_size = int(request.args.get('page_size', 10))
start = (page - 1) * page_size
search_body = {
'from': start,
'size': page_size,
'query': {
'multi_match': {
'query': keywords,
'fields': ['title', 'content']
}
},
'highlight': {
'pre_tags': ['<span style="color:red">'],
'post_tags': ['</span>'],
'fields': {
'title': {},
'content': {}
}
}
}
results = es.search(index=index_name, body=search_body)
total = results['hits']['total']['value']
hits = results['hits']['hits']
search_results = []
for hit in hits:
result = hit['_source']
result['_id'] = hit['_id']
result['_score'] = hit['_score']
if 'highlight' in hit:
highlight = hit['highlight']
if 'title' in highlight:
result['title'] = ''.join(highlight['title'])
if 'content' in highlight:
result['content'] = ''.join(highlight['content'])
search_results.append(result)
total_page = (total + page_size - 1) // page_size
previous_page = page - 1 if page > 1 else None
next_page = page + 1 if page < total_page else None
return jsonify({
'total': total,
'total_page': total_page,
'current_page': page,
'previous_page': previous_page,
'next_page': next_page,
'results': search_results
})
步骤三:使用Jinja2模板引擎创建搜索页面
<!DOCTYPE html>
<html>
<head>
<title>搜索</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div id="search">
<input type="text" name="keywords" id="keywords">
<button id="search_btn">搜索</button>
<div id="search_results"></div>
<div id="page_info"></div>
<button id="prev_btn" disabled>上一页</button>
<button id="next_btn" disabled>下一页</button>
</div>
<script>
var page = 1;
var page_size = 10;
function search() {
var keywords = $('#keywords').val();
$.getJSON('/search', {
'keywords': keywords,
'page': page,
'page_size': page_size
}, function (data) {
var total = data['total'];
var total_page = data['total_page'];
var current_page = data['current_page'];
var previous_page = data['previous_page'];
var next_page = data['next_page'];
var results = data['results'];
var search_html = '';
for (var i = 0; i < results.length; i++) {
var result = results[i];
var id = result['_id'];
var title = result['title'];
var content = result['content'];
var score = result['_score'];
search_html += '<div class="result">';
search_html += '<h3><a href="/detail/' + id + '">' + title + '</a></h3>';
search_html += '<div class="score">得分:' + score + '</div>';
search_html += '<div class="content">' + content + '</div>';
search_html += '</div>';
}
var page_info_html = '共' + total + '个搜索结果,当前第' + current_page + '/' + total_page + '页';
if (previous_page) {
$('#prev_btn').removeAttr('disabled');
} else {
$('#prev_btn').attr('disabled', 'disabled');
}
if (next_page) {
$('#next_btn').removeAttr('disabled');
} else {
$('#next_btn').attr('disabled', 'disabled');
}
$('#search_results').html(search_html);
$('#page_info').html(page_info_html);
});
}
$('#search_btn').click(function () {
page = 1;
search();
});
$('#prev_btn').click(function () {
page -= 1;
search();
});
$('#next_btn').click(function () {
page += 1;
search();
});
</script>
</body>
</html>
以上就是Flask+Elasticsearch实现分页+高亮搜索的完整攻略。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:es+flask搜索小项目实现分页+高亮的示例代码 - Python技术站