[TOC]
## IK 中文分詞器
1. 什么是分詞器
> 切分詞語,normalization(提升recall召回率)
> 給你一段句子,然后將這段句子拆分成一個一個的單個的單詞,同時對每個單詞進行normalization(時態轉換,單復數轉換),分瓷器
> recall,召回率:搜索的時候,增加能夠搜索到的結果的數量
> * 分詞器的作用:
> character filter:在一段文本進行分詞之前,先進行預處理,比如說最常見的就是,過濾html標簽(<span>hello<span> --> hello),& --> and(I&you --> I and you)
> tokenizer:分詞,hello you and me --> hello, you, and, me
> token filter:lowercase,stop word,synonymom,dogs --> dog,liked --> like,Tom --> tom,a/the/an --> 干掉,mother --> mom,small --> little
> 一個分詞器,很重要,將一段文本進行各種處理,最后處理好的結果才會拿去建立倒排索引
2. 內置分詞器的介紹
~~~
Set the shape to semi-transparent by calling set_trans(5)
standard analyzer:set, the, shape, to, semi, transparent, by, calling, set_trans, 5(默認的是standard)
simple analyzer:set, the, shape, to, semi, transparent, by, calling, set, trans
whitespace analyzer:Set, the, shape, to, semi-transparent, by, calling, set_trans(5)
language analyzer(特定的語言的分詞器,比如說,english,英語分詞器):set, shape, semi, transpar, call, set_tran, 5
~~~
* 安裝
1. mkdir /usr/share/elasticsearch/plugins/ik
時解壓放在/usr/share/elasticsearch/plugins/ik目錄下
1. query string分詞
> query string必須以和index建立時相同的analyzer進行分詞(搜索語句和index是一樣的索引)
> query string對exact value和full text的區別對待
~~~
date:exact value
_all:full text # 不指定index的查詢
~~~
> 比如我們有一個document,其中有一個field,包含的value是:hello you and me,建立倒排索引
> 我們要搜索這個document對應的index,搜索文本是hell me,這個搜索文本就是query string
> query string,默認情況下,es會使用它對應的field建立倒排索引時相同的分詞器去進行分詞,分詞和normalization,只有這樣,才能實現正確的搜索
> 我們建立倒排索引的時候,將dogs --> dog,結果你搜索的時候,還是一個dogs,那不就搜索不到了嗎?所以搜索的時候,那個dogs也必須變成dog才行,才能搜索到。
> 知識點:
> 不同類型的field,可能有的就是full text,有的就是exact value
~~~
post_date,date:exact value # 精確值
_all:full text,分詞,normalization # 全文索引
~~~
2. mapping引入案例遺留問題大揭秘
`GET /_search?q=2017`
`搜索的是_all field,document所有的field都會拼接成一個大串,進行分詞`
~~~
2017-01-02 my second article this is my second article in this website 11400
doc1 doc2 doc3
2017 * * *
01 *
02 *
03 *
~~~
> _all,2017,自然會搜索到3個docuemnt
`GET /_search?q=2017-01-01`
~~~
_all,2017-01-01,query string(查詢語句)會用跟建立倒排索引一樣的分詞器去進行分詞
2017
01
01
~~~
`GET /_search?q=post_date:2017-01-01 `
> date,會作為exact value(精確值)去建立索引 # query string 和index使用相同的分詞器去搜索
~~~
doc1 doc2 doc3
2017-01-01 *
2017-01-02 *
2017-01-03 *
post_date:2017-01-01,2017-01-01,doc1一條document
~~~
GET /_search?q=post_date:2017,這個在這里不講解,因為是es 5.2以后做的一個優化
3、測試分詞器
~~~
GET /_analyze
{
"analyzer": "standard",
"text": "Text to analyze"
}
~~~
### 1. 測試分詞器效果
> * IK分詞分為兩類:ik_smart和ik_max_word
ik_max_word: 會將文本做最細粒度的拆分,比如會將“中華人民共和國國歌”拆分為“中華人民共和國,中華人民,中華,華人,人民共和國,人民,人,民,共和國,共和,和,國國,國歌”,會窮盡各種可能的組合;
ik_smart: 會做最粗粒度的拆分,比如會將“中華人民共和國國歌”拆分為“中華人民共和國,國歌”。
* * * * *
#### 1.1 分詞測試
* ik_smart 測試
~~~
GET _analyze?pretty
{
"analyzer": "ik_smart",
"text": "中華人民共和國國歌"
}
~~~
得到 `中華人民共和國 國歌` 兩個詞,如下
~~~
{
"token": "中華人民共和國",
"start_offset": 0,
"end_offset": 7,
"type": "CN_WORD",
"position": 0
},
{
"token": "國歌",
"start_offset": 7,
"end_offset": 9,
"type": "CN_WORD",
"position": 1
}
~~~
* 測試 ik_max_word
~~~
GET _analyze?pretty
{
"analyzer": "ik_max_word",
"text": "中華人民共和國國歌"
}
~~~
得到 `中華人民共和國 中華人民 中華 華人 人民共和國 人民 共和國 國 國歌`
~~~
{
"token": "中華人民共和國",
"start_offset": 0,
"end_offset": 7,
"type": "CN_WORD",
"position": 0
},
{
"token": "中華人民",
"start_offset": 0,
"end_offset": 4,
"type": "CN_WORD",
"position": 1
},
{
"token": "中華",
"start_offset": 0,
"end_offset": 2,
"type": "CN_WORD",
"position": 2
},
。。。。
~~~
* 由此得到結論兩種分析器都是先分大塊詞,而ik_max_word在從大塊詞中分析,以此類推。
ik_max_word分的更加詳細
* * * * *
### 1.2 基于mysql熱更新分詞
測試分詞
~~~
GET _analyze?pretty
{
"analyzer": "ik_max_word",
"text": "王者榮耀是最好玩的游戲"
}
~~~
> 得到 `王者 榮耀 是 最好 好玩 的 游戲 ` 的分詞結果,但是我們想要`王者榮耀`是一個分詞怎么做到呢?就需要熱更新比較流行的分詞
#### 1.2.1 修改ik源碼
1. 自定義線程類HotDictReloadThread,作用時不斷的更新詞典
~~~
public class HotDictReloadThread implements Runnable {
private static final Logger logger = ESLoggerFactory.getLogger(HotDictReloadThread.class.getName());
@Override
public void run() {
logger.info("==========reload hot dic from mysql.......");
while (true){
//不斷的重新加載字典
Dictionary.getSingleton().reLoadMainDict();
}
}
}
~~~
2. 修改Dictionary類的initial方法,啟動線程不斷的更新詞典
~~~
public static synchronized Dictionary initial(Configuration cfg) {
if (singleton == null) {
synchronized (Dictionary.class) {
if (singleton == null) {
singleton = new Dictionary(cfg);
singleton.loadMainDict();
singleton.loadSurnameDict();
singleton.loadQuantifierDict();
singleton.loadSuffixDict();
singleton.loadPrepDict();
singleton.loadStopWordDict();
# 這里是我們自定義的線程類,不斷的重新加載詞典##########
new Thread(new HotDictReloadThread()).start();
if(cfg.isEnableRemoteDict()){
// 建立監控線程
for (String location : singleton.getRemoteExtDictionarys()) {
// 10 秒是初始延遲可以修改的 60是間隔時間 單位秒
pool.scheduleAtFixedRate(new Monitor(location), 10, 60, TimeUnit.SECONDS);
}
for (String location : singleton.getRemoteExtStopWordDictionarys()) {
pool.scheduleAtFixedRate(new Monitor(location), 10, 60, TimeUnit.SECONDS);
}
}
return singleton;
}
}
}
return singleton;
}
~~~
3. 自定義loadMySQLExtDict方法,加載mysql中流行詞
~~~
private static Properties prop = new Properties();
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
logger.error("error",e);
}
}
private void loadMySQLExtDict() {
try {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
Path file = PathUtils.get(getDictRoot(),"mysql.properties");
prop.load(new FileInputStream(file.toFile()));
logger.info("============JDBC reload properties");
for (Object key : prop.keySet())
logger.info("[==========] query hot dict from mysql," + prop.getProperty(String.valueOf(key)));
connection = DriverManager.getConnection(
prop.getProperty("jdbc.url"),
prop.getProperty("jdbc.user"),
prop.getProperty("jdbc.password"));
statement = connection.createStatement();
resultSet = statement.executeQuery(prop.getProperty("jdbc.reload.sql"));
while (resultSet.next()){
String theWord = resultSet.getString("word");
logger.info("[==========] hot word from mysql: " + theWord);
_MainDict.fillSegment(theWord.trim().toCharArray());
}
Thread.sleep(Integer.valueOf(prop.getProperty("jdbc.reload.interval")));
} catch (Exception e) {
e.printStackTrace();
}
}
~~~
4. 自定義loadMySQLStopwordDict方法,加載停用詞
~~~
private void loadMySQLStopwordDict() {
{
try {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
Path file = PathUtils.get(getDictRoot(),"mysql.properties");
prop.load(new FileInputStream(file.toFile()));
logger.info("============JDBC reload properties");
for (Object key : prop.keySet())
logger.info("[==========] query hot dict from mysql," + prop.getProperty(String.valueOf(key)));
connection = DriverManager.getConnection(
prop.getProperty("jdbc.url"),
prop.getProperty("jdbc.user"),
prop.getProperty("jdbc.password"));
statement = connection.createStatement();
resultSet = statement.executeQuery(prop.getProperty("jdbc.reload.stopword.sql"));
while (resultSet.next()){
String theWord = resultSet.getString("word");
logger.info("[==========] hot word from mysql: " + theWord);
_StopWords.fillSegment(theWord.trim().toCharArray());
}
Thread.sleep(Integer.valueOf(prop.getProperty("jdbc.reload.interval")));
} catch (Exception e) {
e.printStackTrace();
}
}
}
~~~
5. 在Dictionary類的loadMainDict方法,調用loadMySQLExtDict方法,加載流行詞
~~~
private void loadMainDict() {
// 建立一個主詞典實例
_MainDict = new DictSegment((char) 0);
// 讀取主詞典文件
Path file = PathUtils.get(getDictRoot(), Dictionary.PATH_DIC_MAIN);
InputStream is = null;
try {
is = new FileInputStream(file.toFile());
} catch (FileNotFoundException e) {
logger.error(e.getMessage(), e);
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 512);
String theWord = null;
do {
theWord = br.readLine();
if (theWord != null && !"".equals(theWord.trim())) {
_MainDict.fillSegment(theWord.trim().toCharArray());
}
} while (theWord != null);
} catch (IOException e) {
logger.error("ik-analyzer", e);
} finally {
try {
if (is != null) {
is.close();
is = null;
}
} catch (IOException e) {
logger.error("ik-analyzer", e);
}
}
// 加載擴展詞典
this.loadExtDict();
// 加載遠程自定義詞庫
this.loadRemoteExtDict();
//加載mysql熱詞
this.loadMySQLExtDict();
}
~~~
6. 在Dictionary類的loadStopWordDict方法,調用loadMySQLStopwordDict方法
~~~
private void loadStopWordDict() {
// 建立主詞典實例
_StopWords = new DictSegment((char) 0);
// 讀取主詞典文件
Path file = PathUtils.get(getDictRoot(), Dictionary.PATH_DIC_STOP);
InputStream is = null;
try {
is = new FileInputStream(file.toFile());
} catch (FileNotFoundException e) {
logger.error(e.getMessage(), e);
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 512);
String theWord = null;
do {
theWord = br.readLine();
if (theWord != null && !"".equals(theWord.trim())) {
_StopWords.fillSegment(theWord.trim().toCharArray());
}
} while (theWord != null);
} catch (IOException e) {
logger.error("ik-analyzer", e);
} finally {
try {
if (is != null) {
is.close();
is = null;
}
} catch (IOException e) {
logger.error("ik-analyzer", e);
}
this.loadMySQLStopwordDict();
}
~~~
7. 添加mysql配置mysql.properties
~~~
jdbc.url=jdbc:mysql://localhost:3306/es?serverTimezone=GMT
jdbc.user=root
jdbc.password=tuna
jdbc.reload.sql=select word from hot_words
jdbc.reload.stopword.sql=select stopword as word from hot_stopwords
jdbc.reload.interval=30000
~~~
* 將mysql打成jar包,覆蓋原來的

* 導入mysql jar

* 重啟elasticsearch
mysql中的流行詞

結果
~~~
GET _analyze
{
"analyzer": "ik_max_word",
"text": "王者榮耀很好玩"
}
~~~
得到
~~~
{
"tokens": [
{
"token": "王者榮耀",
"start_offset": 0,
"end_offset": 4,
"type": "CN_WORD",
"position": 0
},
{
"token": "王者",
"start_offset": 0,
"end_offset": 2,
"type": "CN_WORD",
"position": 1
},
{
"token": "榮耀",
"start_offset": 2,
"end_offset": 4,
"type": "CN_WORD",
"position": 2
},
{
"token": "很好",
"start_offset": 4,
"end_offset": 6,
"type": "CN_WORD",
"position": 3
},
{
"token": "好玩",
"start_offset": 5,
"end_offset": 7,
"type": "CN_WORD",
"position": 4
}
]
}
~~~
流行詞更新完畢
### 1.3 修改索引配置
~~~
PUT http://192.168.159.159:9200/index1
{
"settings": {
"refresh_interval": "5s",
"number_of_shards" : 1, // 一個主節點
"number_of_replicas" : 0 // 0個副本,后面可以加
},
"mappings": {
"_default_":{
"_all": { "enabled": false } // 關閉_all字段,因為我們只搜索title字段
},
"resource": {
"dynamic": false, // 關閉“動態修改索引”
"properties": {
"title": {
"type": "string",
"index": "analyzed",
"fields": {
"cn": {
"type": "string",
"analyzer": "ik"
},
"en": {
"type": "string",
"analyzer": "english"
}
}
}
}
}
}
}
~~~
~~~
GET index/_search
{
"query": {
"match": {
"content": "中國漁船"
}
}
}
~~~
~~~
"hits": {
"total": 2,
"max_score": 0.6099695,
"hits": [
{
"_index": "index",
"_type": "fulltext",
"_id": "4",
"_score": 0.6099695,
"_source": {
"content": "中國駐洛杉磯領事館遭亞裔男子槍擊 嫌犯已自首"
}
},
{
"_index": "index",
"_type": "fulltext",
"_id": "3",
"_score": 0.54359555,
"_source": {
"content": "中韓漁警沖突調查:韓警平均每天扣1艘中國漁船"
}
~~~
設字段的分析器
~~~
POST index/fulltext/_mapping
{
"properties": {
"content": {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_max_word"
}
}
}
~~~
### 1.4 中文分詞文檔統計
* 因為content字段是text類型,不可以聚合,所以設置 "fielddata": true,
~~~
PUT /news/_mapping/new
{
"properties": {
"content":{
"type": "text",
"fielddata": true,
"analyzer": "ik_max_word",
"search_analyzer": "ik_max_word"
}
}
}
~~~
* 查詢
#### 1.4.1 terms(分組)
~~~
GET /news/_search
{
"query": {
"match": {
"content": "中國國家領導人"
}
},
"aggs": {
"top": {
"terms": {
"size": "10",
"field": "content"
}
}
}
}
~~~
得到
~~~
"aggregations": {
"top": {
"doc_count_error_upper_bound": 1,
"sum_other_doc_count": 67,
"buckets": [
{
"key": "中國",
"doc_count": 5
},
{
"key": "在",
"doc_count": 3
},
{
"key": "人",
"doc_count": 2
},
{
"key": "沖突",
"doc_count": 2
},
~~~
中國出現在五篇文檔中,在出現在三篇文檔中
- Docker
- 什么是docker
- Docker安裝、組件啟動
- docker網絡
- docker命令
- docker swarm
- dockerfile
- mesos
- 運維
- Linux
- Linux基礎
- Linux常用命令_1
- Linux常用命令_2
- ip命令
- 什么是Linux
- SELinux
- Linux GCC編譯警告:Clock skew detected. 錯誤解決辦法
- 文件描述符
- find
- 資源統計
- LVM
- Linux相關配置
- 服務自啟動
- 服務器安全
- 字符集
- shell腳本
- shell命令
- 實用腳本
- shell 數組
- 循環與判斷
- 系統級別進程開啟和停止
- 函數
- java調用shell腳本
- 發送郵件
- Linux網絡配置
- Ubuntu
- Ubuntu發送郵件
- 更換apt-get源
- centos
- 防火墻
- 虛擬機下配置網絡
- yum重新安裝
- 安裝mysql5.7
- 配置本地yum源
- 安裝telnet
- 忘記root密碼
- rsync+ crontab
- Zabbix
- Zabbix監控
- Zabbix安裝
- 自動報警
- 自動發現主機
- 監控MySQL
- 安裝PHP常見錯誤
- 基于nginx安裝zabbix
- 監控Tomcat
- 監控redis
- web監控
- 監控進程和端口號
- zabbix自定義監控
- 觸發器函數
- zabbix監控mysql主從同步狀態
- Jenkins
- 安裝Jenkins
- jenkins+svn+maven
- jenkins執行shell腳本
- 參數化構建
- maven區分環境打包
- jenkins使用注意事項
- nginx
- nginx認證功能
- ubuntu下編譯安裝Nginx
- 編譯安裝
- Nginx搭建本地yum源
- 文件共享
- Haproxy
- 初識Haproxy
- haproxy安裝
- haproxy配置
- virtualbox
- virtualbox 復制新的虛擬機
- ubuntu下vitrualbox安裝redhat
- centos配置雙網卡
- 配置存儲
- Windows
- Windows安裝curl
- VMware vSphere
- 磁盤管理
- 增加磁盤
- gitlab
- 安裝
- tomcat
- Squid
- bigdata
- FastDFS
- FastFDS基礎
- FastFDS安裝及簡單實用
- api介紹
- 數據存儲
- FastDFS防盜鏈
- python腳本
- ELK
- logstash
- 安裝使用
- kibana
- 安準配置
- elasticsearch
- elasticsearch基礎_1
- elasticsearch基礎_2
- 安裝
- 操作
- java api
- 中文分詞器
- term vector
- 并發控制
- 對text字段排序
- 倒排和正排索引
- 自定義分詞器
- 自定義dynamic策略
- 進階練習
- 共享鎖和排它鎖
- nested object
- 父子關系模型
- 高亮
- 搜索提示
- Redis
- redis部署
- redis基礎
- redis運維
- redis-cluster的使用
- redis哨兵
- redis腳本備份還原
- rabbitMQ
- rabbitMQ安裝使用
- rpc
- RocketMQ
- 架構概念
- 安裝
- 實例
- 好文引用
- 知乎
- ACK
- postgresql
- 存儲過程
- 編程語言
- 計算機網絡
- 基礎_01
- tcp/ip
- http轉https
- Let's Encrypt免費ssl證書(基于haproxy負載)
- what's the http?
- 網關
- 網絡IO
- http
- 無狀態網絡協議
- Python
- python基礎
- 基礎數據類型
- String
- List
- 遍歷
- Python基礎_01
- python基礎_02
- python基礎03
- python基礎_04
- python基礎_05
- 函數
- 網絡編程
- 系統編程
- 類
- Python正則表達式
- pymysql
- java調用python腳本
- python操作fastdfs
- 模塊導入和sys.path
- 編碼
- 安裝pip
- python進階
- python之setup.py構建工具
- 模塊動態導入
- 內置函數
- 內置變量
- path
- python模塊
- 內置模塊_01
- 內置模塊_02
- log模塊
- collections
- Twisted
- Twisted基礎
- 異步編程初探與reactor模式
- yield-inlineCallbacks
- 系統編程
- 爬蟲
- urllib
- xpath
- scrapy
- 爬蟲基礎
- 爬蟲種類
- 入門基礎
- Rules
- 反反爬蟲策略
- 模擬登陸
- problem
- 分布式爬蟲
- 快代理整站爬取
- 與es整合
- 爬取APP數據
- 爬蟲部署
- collection for ban of web
- crawlstyle
- API
- 多次請求
- 向調度器發送請求
- 源碼學習
- LinkExtractor源碼分析
- 構建工具-setup.py
- selenium
- 基礎01
- 與scrapy整合
- Django
- Django開發入門
- Django與MySQL
- java
- 設計模式
- 單例模式
- 工廠模式
- java基礎
- java位移
- java反射
- base64
- java內部類
- java高級
- 多線程
- springmvc-restful
- pfx數字證書
- 生成二維碼
- 項目中使用log4j
- 自定義注解
- java發送post請求
- Date時間操作
- spring
- 基礎
- spring事務控制
- springMVC
- 注解
- 參數綁定
- springmvc+spring+mybatis+dubbo
- MVC模型
- SpringBoot
- java配置入門
- SpringBoot基礎入門
- SpringBoot web
- 整合
- SpringBoot注解
- shiro權限控制
- CommandLineRunner
- mybatis
- 靜態資源
- SSM整合
- Aware
- Spring API使用
- Aware接口
- mybatis
- 入門
- mybatis屬性自動映射、掃描
- 問題
- @Param 注解在Mybatis中的使用 以及傳遞參數的三種方式
- mybatis-SQL
- 逆向生成dao、model層代碼
- 反向工程中Example的使用
- 自增id回顯
- SqlSessionDaoSupport
- invalid bound statement(not found)
- 脈絡
- beetl
- beetl是什么
- 與SpringBoot整合
- shiro
- 什么是shiro
- springboot+shrio+mybatis
- 攔截url
- 枚舉
- 圖片操作
- restful
- java項目中日志處理
- JSON
- 文件工具類
- KeyTool生成證書
- 兼容性問題
- 開發規范
- 工具類開發規范
- 壓縮圖片
- 異常處理
- web
- JavaScript
- 基礎語法
- 創建對象
- BOM
- window對象
- DOM
- 閉包
- form提交-文件上傳
- td中內容過長
- 問題1
- js高級
- js文件操作
- 函數_01
- session
- jQuery
- 函數01
- data()
- siblings
- index()與eq()
- select2
- 動態樣式
- bootstrap
- 表單驗證
- 表格
- MUI
- HTML
- iframe
- label標簽
- 規范編程
- layer
- sss
- 微信小程序
- 基礎知識
- 實踐
- 自定義組件
- 修改自定義組件的樣式
- 基礎概念
- appid
- 跳轉
- 小程序發送ajax
- 微信小程序上下拉刷新
- if
- 工具
- idea
- Git
- maven
- svn
- Netty
- 基礎概念
- Handler
- SimpleChannelInboundHandler 與 ChannelInboundHandler
- 網絡編程
- 網絡I/O
- database
- oracle
- 游標
- PLSQL Developer
- mysql
- MySQL基準測試
- mysql備份
- mysql主從不同步
- mysql安裝
- mysql函數大全
- SQL語句
- 修改配置
- 關鍵字
- 主從搭建
- centos下用rpm包安裝mysql
- 常用sql
- information_scheme數據庫
- 值得學的博客
- mysql學習
- 運維
- mysql權限
- 配置信息
- 好文mark
- jsp
- jsp EL表達式
- C
- test