Ex_treme's blog.

django搜索接口的实现

2018/05/22 Share

Django为ES写搜索建议和多段匹配检索接口

最终达到的效果就是用浏览器访问suggest和search地址并附带一个参数,返回搜索建议和多段匹配结果。

views

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
def suggest(request,key_words):
re_datas = []
if key_words:
s = QAType.search()
s = s.suggest('my_suggest', key_words, completion={
"field": "suggest", "fuzzy": {
"fuzziness": 2
},
"size": 10
})
suggestions = s.execute_suggest()
for match in suggestions.my_suggest[0].options:
source = match._source
re_datas.append(source["question"])
return HttpResponse(json.dumps(re_datas), content_type="application/json")

def search(request,key_words):
client = Elasticsearch(hosts=["127.0.0.1"])
response = client.search(
index="qa",
body={
"query": {
"multi_match": {
"query": key_words,
"fields": ["question", "topic", "answer"]
}
},
"from": 0,
"size": 10
}
)

hit_list = []
for hit in response["hits"]["hits"]:
hit_dict = {}
hit_dict["question"] = hit["_source"]["question"]
hit_dict["topic"] = hit["_source"]["topic"]
hit_dict["md5"] = hit["_source"]["md5"]
hit_dict["score"] = hit["_score"]
hit_dict["answer"] = hit["_source"]["answer"]
hit_dict["expand"] = hit["_source"]["expand"]

hit_list.append(hit_dict)


return HttpResponse(json.dumps(hit_list), content_type="application/json")

urls

1
2
3
4
5
6
7
8
9
urlpatterns = [
url(r'', xadmin.site.urls),
url(r'^admin/', admin.site.urls),
url(r'^num/', num),
url(r'^static/(?P<path>.*)$', serve, {"document_root":STATIC_ROOT}),
url(r'^suggest/(?P<key_words>.*)$',suggest),
url(r'^search/(?P<key_words>.*)$', search)

]

搜索建议效果
image
多段匹配效果
image

B/S中用javascript实现动态检测输入字段的变化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
html/css:
<div class="inputArea">
<input type="text" class="searchInput" />
<input type="button" class="searchButton" onclick="add_search()" />

</div>
<ul class="dataList">
<li>如何学好设计</li>
<li>界面设计</li>
<li>UI设计培训要多少钱</li>
<li>设计师学习</li>
<li>哪里有好的网站</li>
</ul>

js:
$(function(){
$('.searchInput').bind(' input propertychange ',function(){
var searchText = $(this).val();
var tmpHtml = ""
$.ajax({
cache: false,
type: 'get',
dataType:'json',
url:suggest_url+"?s="+searchText+"&s_type="+$(".searchItem.current").attr('data-type'),
async: true,
success: function(data) {
for (var i=0;i<data.length;i++){
tmpHtml += '<li><a href="'+search_url+'?q='+data[i]+'">'+data[i]+'</a></li>'
}
$(".dataList").html("")
$(".dataList").append(tmpHtml);
if (data.length == 0){
$('.dataList').hide()
}else {
$('.dataList').show()
}
}
});
} );
});

hideElement($('.dataList'), $('.searchInput'));
CATALOG
  1. 1. Django为ES写搜索建议和多段匹配检索接口
    1. 1.1. views
    2. 1.2. urls
    3. 1.3. 搜索建议效果 多段匹配效果
      1. 1.3.1. B/S中用javascript实现动态检测输入字段的变化