elasticsearch 拼音分詞器 & 自動(dòng)補(bǔ)全。
2. 自動(dòng)補(bǔ)全。
當(dāng)用戶在搜索框輸入字符時(shí),我們應(yīng)該提示出與該字符有關(guān)的搜索項(xiàng),如圖。
這種根據(jù)用戶輸入的字母,提示完整詞條的功能,就是自動(dòng)補(bǔ)全了。
因?yàn)樾枰鶕?jù)拼音字母來(lái)推斷,因此要用到拼音分詞功能。
2.1. 拼音分詞器。
要實(shí)現(xiàn)根據(jù)字母做補(bǔ)全,就必須對(duì)文檔按照拼音分詞。在 GitHub 上恰好有 elasticsearch 的拼音分詞插件。地址:https://github.com/medcl/elasticsearch-analysis-pinyin。
課前資料中也提供了拼音分詞器的安裝包。
安裝方式與 IK 分詞器一樣,分三步。
? ①解壓。
? ②上傳到虛擬機(jī)中,elasticsearch 的 plugin 目錄。
? ③重啟 elasticsearch
? ④測(cè)試。
詳細(xì)安裝步驟可以參考 IK 分詞器的安裝過(guò)程。
測(cè)試用法如下。
POST /_analyze
{
"text": [
"如家酒店還不錯(cuò)"
],
"analyzer": "ik_max_word"
}
結(jié)果。
{
"tokens" : [
{
"token" : "ru",
"start_offset" : 0,
"end_offset" : 0,
"type" : "word",
"position" : 0
},
{
"token" : "rjjdhbc",
"start_offset" : 0,
"end_offset" : 0,
"type" : "word",
"position" : 0
},
{
"token" : "jia",
"start_offset" : 0,
"end_offset" : 0,
"type" : "word",
"position" : 1
},
{
"token" : "jiu",
"start_offset" : 0,
"end_offset" : 0,
"type" : "word",
"position" : 2
},
{
"token" : "dian",
"start_offset" : 0,
"end_offset" : 0,
"type" : "word",
"position" : 3
},
{
"token" : "hai",
"start_offset" : 0,
"end_offset" : 0,
"type" : "word",
"position" : 4
},
{
"token" : "bu",
"start_offset" : 0,
"end_offset" : 0,
"type" : "word",
"position" : 5
},
{
"token" : "cuo",
"start_offset" : 0,
"end_offset" : 0,
"type" : "word",
"position" : 6
}
]
}
2.2. 自定義分詞器。
默認(rèn)的拼音分詞器會(huì)將每個(gè)漢字單獨(dú)分為拼音,而我們希望的是每個(gè)詞條形成一組拼音,需要對(duì)拼音分詞器做個(gè)性化定制,形成自定義分詞器。
elasticsearch 中分詞器(analyzer)的組成包含三部分。
-
character filters:在 tokenizer 之前對(duì)文本進(jìn)行處理。例如刪除字符、替換字符。
-
tokenizer:將文本按照一定的規(guī)則切割成詞條(term)。例如 keyword,就是不分詞;還有 ik_smart。
term
n. 學(xué)期(尤用于英國(guó),學(xué)校一年分三個(gè)學(xué)期);術(shù)語(yǔ);期限;任期;期;詞語(yǔ);措辭;到期;項(xiàng)
vt. 把 … 稱為;把 … 叫做
- tokenizer filter:將 tokenizer 輸出的詞條做進(jìn)一步處理。例如大小寫轉(zhuǎn)換、同義詞處理、拼音處理等。
文檔分詞時(shí)會(huì)依次由這三部分來(lái)處理文檔。
聲明自定義分詞器的語(yǔ)法如下。
在創(chuàng)建索引庫(kù)時(shí)通過(guò) settings 配置自定義的 analyzer(分詞器)。
PUT /test
{
"settings": {
"analysis": {
// 自定義分詞器。
"analyzer": {
// 分詞器名稱。
"my_analyzer": {
"tokenizer": "ik_max_word",
"filter": "pinyin"
}
}
}
}
}
PUT /test
{
"settings": {
"analysis": {
// 自定義分詞器。
"analyzer": {
// 分詞器名稱。
"my_analyzer": {
"tokenizer": "ik_max_word",
"filter": "py"
}
},
// 自定義 tokenizer filter。
"filter": {
// 過(guò)濾器名稱。
"py": {
// 過(guò)濾器類型,這里是 pinyin。
"type": "pinyin",
"limit_first_letter_length": 16,
"keep_full_pinyin": false,
"keep_joined_full_pinyin": true,
"none_chinese_pinyin_tokenize": false,
"keep_original": true,
"remove_duplicated_term": true
}
}
}
},
"mappings": {
"properties": {
"name": {
"type": "text",
"analyzer": "my_analyzer",
"search_analyzer": "my_analyzer"
}
}
}
}
{
"acknowledged" : true,
"shards_acknowledged" : true,
"index" : "test"
}
測(cè)試。
POST /test/_analyze
{
"text": ["如家酒店還不錯(cuò)"],
"analyzer": "my_analyzer"
}
{
"tokens" : [
{
"token" : "如家",
"start_offset" : 0,
"end_offset" : 2,
"type" : "CN_WORD",
"position" : 0
},
{
"token" : "rujia",
"start_offset" : 0,
"end_offset" : 2,
"type" : "CN_WORD",
"position" : 0
},
{
"token" : "rj",
"start_offset" : 0,
"end_offset" : 2,
"type" : "CN_WORD",
"position" : 0
},
{
"token" : "酒店",
"start_offset" : 2,
"end_offset" : 4,
"type" : "CN_WORD",
"position" : 1
},
{
"token" : "jiudian",
"start_offset" : 2,
"end_offset" : 4,
"type" : "CN_WORD",
"position" : 1
},
{
"token" : "jd",
"start_offset" : 2,
"end_offset" : 4,
"type" : "CN_WORD",
"position" : 1
},
{
"token" : "還不",
"start_offset" : 4,
"end_offset" : 6,
"type" : "CN_WORD",
"position" : 2
},
{
"token" : "haibu",
"start_offset" : 4,
"end_offset" : 6,
"type" : "CN_WORD",
"position" : 2
},
{
"token" : "hb",
"start_offset" : 4,
"end_offset" : 6,
"type" : "CN_WORD",
"position" : 2
},
{
"token" : "不錯(cuò)",
"start_offset" : 5,
"end_offset" : 7,
"type" : "CN_WORD",
"position" : 3
},
{
"token" : "bucuo",
"start_offset" : 5,
"end_offset" : 7,
"type" : "CN_WORD",
"position" : 3
},
{
"token" : "bc",
"start_offset" : 5,
"end_offset" : 7,
"type" : "CN_WORD",
"position" : 3
}
]
}
總結(jié)。
如何使用拼音分詞器?
-
① 下載 pinyin 分詞器。
-
② 解壓并放到 elasticsearch 的 plugin 目錄。
-
③ 重啟即可。
如何自定義分詞器?
-
① 創(chuàng)建索引庫(kù)時(shí),在 settings 中配置,可以包含三部分。
-
② character filter
-
③ tokenizer
-
④ filter
拼音分詞器注意事項(xiàng)?
- 為了避免搜索到同音字,搜索時(shí)不要使用拼音分詞器。
字段在創(chuàng)建倒排索引時(shí)應(yīng)該用 my_analyzer 分詞器。
字段在搜索時(shí)應(yīng)該使用 ik_smart 分詞器。
PUT /test
{
"settings": {
"analysis": {
// 自定義分詞器。
"analyzer": {
// 分詞器名稱。
"my_analyzer": {
"tokenizer": "ik_max_word",
"filter": "py"
}
},
// 自定義 tokenizer filter。
"filter": {
// 過(guò)濾器名稱。
"py": {
// 過(guò)濾器類型,這里是 pinyin。
"type": "pinyin",
"limit_first_letter_length": 16,
"keep_full_pinyin": false,
"keep_joined_full_pinyin": true,
"none_chinese_pinyin_tokenize": false,
"keep_original": true,
"remove_duplicated_term": true
}
}
}
},
"mappings": {
"properties": {
"name": {
"type": "text",
"analyzer": "my_analyzer",
"search_analyzer": "ik_smart"
}
}
}
}
2.3. 自動(dòng)補(bǔ)全查詢。
elasticsearch 提供了 Completion Suggester 查詢來(lái)實(shí)現(xiàn)自動(dòng)補(bǔ)全功能。這個(gè)查詢會(huì)匹配以用戶輸入內(nèi)容開(kāi)頭的詞條并返回。為了提高補(bǔ)全查詢的效率,對(duì)于文檔中字段的類型有一些約束。
-
參與補(bǔ)全查詢的字段必須是 completion 類型。
-
字段的內(nèi)容一般是用來(lái)補(bǔ)全的多個(gè)詞條形成的數(shù)組。
比如,一個(gè)這樣的索引庫(kù)。
// 創(chuàng)建索引庫(kù)。
PUT test
{
"mappings": {
"properties": {
"title": {
"type": "completion"
}
}
}
}
然后插入下面的數(shù)據(jù)。
// 示例數(shù)據(jù)。
POST test/_doc
{
"title": [
"Sony",
"WH-1000XM5"
]
}
POST test/_doc
{
"title": [
"SK-II",
"PITERA"
]
}
POST test/_doc
{
"title": [
"Nintendo",
"switch"
]
}
查詢的 DSL 語(yǔ)句如下。
// 自動(dòng)補(bǔ)全查詢。
GET /test/_search
{
"suggest": {
"titleSuggest": {
// 關(guān)鍵字。
"text": "s",
"completion": {
// 補(bǔ)全查詢的字段。
"field": "title",
// 跳過(guò)重復(fù)的。
"skip_duplicates": true,
// 獲取前 10 條結(jié)果。
"size": 10
}
}
}
}
{
"took" : 305,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 0,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"suggest" : {
"titleSuggest" : [
{
"text" : "s",
"offset" : 0,
"length" : 1,
"options" : [
{
"text" : "SK-II",
"_index" : "test",
"_type" : "_doc",
"_id" : "xceQcIcBAo7LWD6k-sCY",
"_score" : 1.0,
"_source" : {
"title" : [
"SK-II",
"PITERA"
]
}
},
{
"text" : "Sony",
"_index" : "test",
"_type" : "_doc",
"_id" : "xMeQcIcBAo7LWD6k9MBJ",
"_score" : 1.0,
"_source" : {
"title" : [
"Sony",
"WH-1000XM5"
]
}
},
{
"text" : "switch",
"_index" : "test",
"_type" : "_doc",
"_id" : "xseQcIcBAo7LWD6k_8DL",
"_score" : 1.0,
"_source" : {
"title" : [
"Nintendo",
"switch"
]
}
}
]
}
]
}
}
2.4. 實(shí)現(xiàn)酒店搜索框自動(dòng)補(bǔ)全。
現(xiàn)在,我們的 hotel 索引庫(kù)還沒(méi)有設(shè)置拼音分詞器,需要修改索引庫(kù)中的配置。但是我們知道索引庫(kù)是無(wú)法修改的,只能刪除然后重新創(chuàng)建。
另外,我們需要添加一個(gè)字段,用來(lái)做自動(dòng)補(bǔ)全,將 brand、suggestion、city 等都放進(jìn)去,作為自動(dòng)補(bǔ)全的提示。
因此,總結(jié)一下,我們需要做的事情包括。
-
修改 hotel 索引庫(kù)結(jié)構(gòu),設(shè)置自定義拼音分詞器。
-
修改索引庫(kù)的 name、all 字段,使用自定義分詞器。
-
索引庫(kù)添加一個(gè)新字段 suggestion,類型為 completion 類型,使用自定義的分詞器。
-
給 HotelDoc 類添加 suggestion 字段,內(nèi)容包含 brand、business。
-
重新導(dǎo)入數(shù)據(jù)到 hotel 庫(kù)。
2.4.1. 修改酒店映射結(jié)構(gòu)。
代碼如下。
DELETE /hotel
// 酒店數(shù)據(jù)索引庫(kù)。
PUT /hotel
{
"settings": {
"analysis": {
"analyzer": {
"text_analyzer": {
"tokenizer": "ik_max_word",
"filter": "py"
},
"completion_analyzer": {
"tokenizer": "keyword",
"filter": "py"
}
},
"filter": {
"py": {
"limit_first_letter_length": 16,
"type": "pinyin",
"keep_full_pinyin": false,
"keep_joined_full_pinyin": true,
"none_chinese_pinyin_tokenize": false,
"keep_original": true,
"remove_duplicated_term": true
}
}
}
},
"mappings": {
"properties": {
"all": {
"type": "text",
"analyzer": "text_analyzer",
"search_analyzer": "ik_smart"
},
"id": {
"type": "keyword"
},
"address": {
"type": "keyword",
"index": false
},
"brand": {
"type": "keyword",
"copy_to": "all"
},
"business": {
"type": "keyword",
"copy_to": "all"
},
"city": {
"type": "keyword"
},
"location": {
"type": "geo_point"
},
"name": {
"type": "text",
"analyzer": "text_analyzer",
"search_analyzer": "ik_smart",
"copy_to": "all"
},
"pic": {
"type": "keyword",
"index": false
},
"price": {
"type": "integer"
},
"score": {
"type": "integer"
},
"starName": {
"type": "keyword"
},
"suggestion": {
"type": "completion",
"analyzer": "completion_analyzer"
}
}
}
}
2.4.2. 修改 HotelDoc 實(shí)體。
HotelDoc 中要添加一個(gè)字段,用來(lái)做自動(dòng)補(bǔ)全,內(nèi)容可以是酒店品牌、城市、商圈等信息。按照自動(dòng)補(bǔ)全字段的要求,最好是這些字段的數(shù)組。
因此我們?cè)?HotelDoc 中添加一個(gè) suggestion 字段,類型為 List<String>
,然后將 brand、city、business 等信息放到里面。
代碼如下。
package com.geek.elasticsearchgeek.hotel.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* @author geek
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class HotelDoc implements Serializable {
private Long id;
private String name;
private String address;
private Integer price;
private Integer score;
private String brand;
private String city;
private String starName;
private String business;
private String location;
private String pic;
/**
* 排序時(shí)的距離值。
*/
private Object distance;
private Boolean bAdvertise;
private List<String> suggestion;
public HotelDoc(Hotel hotel) {
this.id = hotel.getId();
this.name = hotel.getName();
this.address = hotel.getAddress();
this.price = hotel.getPrice();
this.score = hotel.getScore();
this.brand = hotel.getBrand();
this.city = hotel.getCity();
this.starName = hotel.getStarName();
this.business = hotel.getBusiness();
this.location = hotel.getLatitude() + ", " + hotel.getLongitude();
this.pic = hotel.getPic();
// 組裝 suggestion。
if (this.business.contains("/")) {
// business 有多個(gè)值,需要切割。
String[] split = this.business.split("/");
// 添加元素。
this.suggestion = new ArrayList<>();
this.suggestion.add(this.brand);
Collections.addAll(this.suggestion, split);
} else {
this.suggestion = Arrays.asList(this.brand, this.business);
}
}
}
2.4.3. 重新導(dǎo)入。
重新執(zhí)行之前編寫的導(dǎo)入數(shù)據(jù)功能,可以看到新的酒店數(shù)據(jù)中包含了 suggestion。
測(cè)試。
GET /hotel/_search
{
"suggest": {
"suggestions": {
"text": "h",
"completion": {
"field": "suggestion",
"skip_duplicates": true,
"size": 10
}
}
}
}
2.4.4. 自動(dòng)補(bǔ)全查詢的 JavaAPI。
之前我們學(xué)習(xí)了自動(dòng)補(bǔ)全查詢的 DSL,而沒(méi)有學(xué)習(xí)對(duì)應(yīng)的 JavaAPI,這里給出一個(gè)示例。
而自動(dòng)補(bǔ)全的結(jié)果也比較特殊,解析的代碼如下。
2.4.5. 實(shí)現(xiàn)搜索框自動(dòng)補(bǔ)全。
查看前端頁(yè)面,可以發(fā)現(xiàn)當(dāng)我們?cè)谳斎肟蜴I入時(shí),前端會(huì)發(fā)起 ajax 請(qǐng)求。
返回值是補(bǔ)全詞條的集合,類型為 List<String>
。
1)在 com.geek.elasticsearchgeek.hotel.controller
包下的 HotelController
中添加新接口,接收新的請(qǐng)求。
@RequestMapping("/suggestion")
public List<String> getSuggestions(@RequestParam("key") String prefix) {
return this.hotelService.getSuggestions(prefix);
}
2)在 com.geek.elasticsearchgeek.hotel.service
包下的 IhotelService
中添加方法。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-741032.html
List<String> getSuggestions(String prefix);
3)在 com.geek.elasticsearchgeek.hotel.service.impl.HotelService
中實(shí)現(xiàn)該方法。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-741032.html
@Override
public List<String> getSuggestions(String prefix) {
// 準(zhǔn)備 Request。
SearchRequest searchRequest = new SearchRequest("hotel");
// 準(zhǔn)備 DSL。
searchRequest.source().suggest(new SuggestBuilder().addSuggestion(
"suggestions",
SuggestBuilders.completionSuggestion("suggestion")
.prefix(prefix)
.skipDuplicates(true)
.size(10)
));
// 發(fā)起請(qǐng)求。
SearchResponse searchResponse = null;
try {
searchResponse = this.restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
} catch (IOException e) {
throw new RuntimeException(e);
}
// 解析結(jié)果。
Suggest suggest = searchResponse.getSuggest();
// 根據(jù)補(bǔ)全查詢名稱,獲取補(bǔ)全結(jié)果。
CompletionSuggestion suggestions = suggest.getSuggestion("mySuggestions");
// 獲取 options。
List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
// 遍歷。
List<String> list = new ArrayList<>(options.size());
for (CompletionSuggestion.Entry.Option option : options) {
// 補(bǔ)全的詞條。
String text = option.getText().toString();
list.add(text);
}
return list;
}
到了這里,關(guān)于elasticsearch 拼音分詞器 & 自動(dòng)補(bǔ)全。的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!