基礎知識回顧
分析器的組成結構:
分析器(analyzer)
- Character filters (字元過濾器)0個或多個
- Tokenizer (分詞器)有且隻有一個
- Token filters (token過濾器)0個或多個

内置分析器
1、whitespace 空白符分詞
POST _analyze
{
"analyzer": "whitespace",
"text": "你好 世界"
}
{
"tokens": [
{
"token": "你好",
"start_offset": 0,
"end_offset": 2,
"type": "word",
"position": 0
},
{
"token": "世界",
"start_offset": 3,
"end_offset": 5,
"type": "word",
"position": 1
}
]
}
2、pattern正規表達式分詞,預設表達式是
\w+
(非單詞字元)
配置參數
pattern : 一個Java正規表達式,預設 \W+
flags : Java正規表達式flags。比如:CASE_INSENSITIVE 、COMMENTS
lowercase : 是否将terms全部轉成小寫。預設true
stopwords : 一個預定義的停止詞清單,或者包含停止詞的一個清單。預設是 _none_
stopwords_path : 停止詞檔案路徑
// 拆分中文不正常
POST _analyze
{
"analyzer": "pattern",
"text": "你好世界"
}
{
"tokens": []
}
// 拆分英文正常
POST _analyze
{
"analyzer": "pattern",
"text": "hello world"
}
{
"tokens": [
{
"token": "hello",
"start_offset": 0,
"end_offset": 5,
"type": "word",
"position": 0
},
{
"token": "world",
"start_offset": 6,
"end_offset": 11,
"type": "word",
"position": 1
}
]
}
// 在索引上自定義分析器-豎線分隔
PUT my-blog
{
"settings": {
"analysis": {
"analyzer": {
"vertical_line": {
"type": "pattern",
"pattern": "\\|"
}
}
}
},
"mappings": {
"doc": {
"properties": {
"content": {
"type": "text",
"analyzer": "vertical_line"
}
}
}
}
}
// 測試索引分析器
POST /blog-v4/_analyze
{
"analyzer": "vertical_line",
"text": "你好|世界"
}
POST /blog-v4/_analyze
{
"field": "content",
"text": "你好|世界"
}
// 兩者結果都是
{
"tokens": [
{
"token": "你好",
"start_offset": 0,
"end_offset": 2,
"type": "word",
"position": 0
},
{
"token": "世界",
"start_offset": 3,
"end_offset": 5,
"type": "word",
"position": 1
}
]
}
參考
Elasticsearch 分詞器