拼寫糾錯
對於已經建立的articles索引庫,elasticsearch還提供了一種查詢模式,suggest建議查詢模式
curl 127.0.0.1:9200/articles/article/_search?pretty -d '
{
"_source": false,
"suggest": {
"text": "phtyon web", # 輸入的內容
"word-phrase": { # 自定義字段名, 推薦結果會包含在該字段中
"phrase": { # 返回短語形式, 還可以使用term
"field": "_all", # 指定在哪些字段中獲取推薦詞
"size": 1 # 返回的推薦詞數量
}
}
}
}'
當我們輸入錯誤的關鍵詞phtyon web
時,es可以提供根據索引庫數據得出的正確拼寫python web
自動補全
- 自動補全對類型映射有特殊要求, 不能使用原索引庫, 需要創建單獨的自動補全索引庫
- 注意 推薦詞的類型必須是
completion
curl -X PUT 127.0.0.1:9200/completions/_mapping/words -H 'Content-Type: application/json' -d'
{
"words": {
"properties": {
"suggest": { # 自定義的字段名 存儲文章的標題
"type": "completion", # 自動補全的類型必須completion
"analyzer": "ik_max_word"
}
}
}
}
'
- 查詢自動補全
curl 127.0.0.1:9200/completions/words/_search?pretty -d '
{
"suggest": {
"title-suggest" : { # 自定義字段名, 推薦結果會包含在該字段中
"prefix" : "pyth", # 輸入的內容 補全結果python
"completion" : {
"field" : "suggest" # 指定在哪些字段中獲取推薦詞
}
}
}
}
'
搜索建議接口
- 先進行自動補全的查詢, 如果沒有結果, 再進行拼寫糾錯的查詢
class SuggestionResource(Resource):
"""
聯想建議
"""
def get(self):
"""
獲取聯想建議
"""
# 解析參數
qs_parser = RequestParser()
qs_parser.add_argument('q', type=inputs.regex(r'^.{1,50}$'), required=True, location='args')
args = qs_parser.parse_args()
q = args.q
# 先嘗試自動補全建議查詢
query = {
'from': 0,
'size': 10,
'_source': False,
'suggest': {
'word-completion': {
'prefix': q,
'completion': {
'field': 'suggest'
}
}
}
}
ret = current_app.es.search(index='completions', body=query)
options = ret['suggest']['word-completion'][0]['options']
# 如果沒得到查詢結果,進行糾錯建議查詢
if not options:
query = {
'from': 0,
'size': 10,
'_source': False,
'suggest': {
'text': q,
'word-phrase': {
'phrase': {
'field': '_all',
'size': 1
}
}
}
}
ret = current_app.es.search(index='articles', doc_type='article', body=query)
options = ret['suggest']['word-phrase'][0]['options']
results = []
for option in options:
if option['text'] not in results:
results.append(option['text'])
return {'options': results}