Elasticsearch 默認(rèn)分詞器和中分分詞器之間的比較及使用方法

轉(zhuǎn)載出處:https://zhuanlan.zhihu.com/p/29183128
介紹:ElasticSearch 是一個(gè)基于 Lucene 的搜索服務(wù)器。它提供了一個(gè)分布式多用戶能力的全文搜索引擎,基于 RESTful web 接口澎怒。Elasticsearch 是用 Java 開發(fā)的哺呜,并作為Apache許可條款下的開放源碼發(fā)布,是當(dāng)前流行的企業(yè)級(jí)搜索引擎。設(shè)計(jì)用于云計(jì)算中笋轨,能夠達(dá)到實(shí)時(shí)搜索冠场,穩(wěn)定家浇,可靠,快速碴裙,安裝使用方便钢悲。

Elasticsearch中,內(nèi)置了很多分詞器(analyzers)舔株。下面來(lái)進(jìn)行比較下系統(tǒng)默認(rèn)分詞器和常用的中文分詞器之間的區(qū)別莺琳。

系統(tǒng)默認(rèn)分詞器:

1、standard 分詞器

https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-standard-analyzer.html

如何使用:http://www.yiibai.com/lucene/lucene_standardanalyzer.html

英文的處理能力同于StopAnalyzer.支持中文采用的方法為單字切分载慈。他會(huì)將詞匯單元轉(zhuǎn)換成小寫形式惭等,并去除停用詞和標(biāo)點(diǎn)符號(hào)。

/**StandardAnalyzer分析器*/
public void standardAnalyzer(String msg){
    StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
   this.getTokens(analyzer, msg);
}

2办铡、simple 分詞器

https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-simple-analyzer.html

如何使用: http://www.yiibai.com/lucene/lucene_simpleanalyzer.html

功能強(qiáng)于WhitespaceAnalyzer, 首先會(huì)通過(guò)非字母字符來(lái)分割文本信息辞做,然后將詞匯單元統(tǒng)一為小寫形式。該分析器會(huì)去掉數(shù)字類型的字符料扰。

/**SimpleAnalyzer分析器*/
    public void simpleAnalyzer(String msg){
        SimpleAnalyzer analyzer = new SimpleAnalyzer(Version.LUCENE_36);
        this.getTokens(analyzer, msg);
    }

3凭豪、Whitespace 分詞器

https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-whitespace-analyzer.html

如何使用:http://www.yiibai.com/lucene/lucene_whitespaceanalyzer.html

僅僅是去除空格,對(duì)字符沒(méi)有l(wèi)owcase化,不支持中文晒杈; 并且不對(duì)生成的詞匯單元進(jìn)行其他的規(guī)范化處理嫂伞。

/**WhitespaceAnalyzer分析器*/
    public void whitespaceAnalyzer(String msg){
        WhitespaceAnalyzer analyzer = new WhitespaceAnalyzer(Version.LUCENE_36);
        this.getTokens(analyzer, msg);
    }

4、Stop 分詞器

https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-stop-analyzer.html

如何使用:http://www.yiibai.com/lucene/lucene_stopanalyzer.html

StopAnalyzer的功能超越了SimpleAnalyzer拯钻,在SimpleAnalyzer的基礎(chǔ)上增加了去除英文中的常用單詞(如the帖努,a等),也可以更加自己的需要設(shè)置常用單詞粪般;不支持中文

/**StopAnalyzer分析器*/
   public void stopAnalyzer(String msg){
       StopAnalyzer analyzer = new StopAnalyzer(Version.LUCENE_36);
       this.getTokens(analyzer, msg);
   }

5拼余、keyword 分詞器

KeywordAnalyzer把整個(gè)輸入作為一個(gè)單獨(dú)詞匯單元,方便特殊類型的文本進(jìn)行索引和檢索亩歹。針對(duì)郵政編碼匙监,地址等文本信息使用關(guān)鍵詞分詞器進(jìn)行索引項(xiàng)建立非常方便。

6小作、pattern 分詞器

https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-pattern-analyzer.html

一個(gè)pattern類型的analyzer可以通過(guò)正則表達(dá)式將文本分成"terms"(經(jīng)過(guò)token Filter 后得到的東西 )亭姥。接受如下設(shè)置:

一個(gè) pattern analyzer 可以做如下的屬性設(shè)置:

lowercaseterms是否是小寫. 默認(rèn)為 true 小寫.pattern正則表達(dá)式的pattern, 默認(rèn)是 \W+.flags正則表達(dá)式的flagsstopwords一個(gè)用于初始化stop filter的需要stop 單詞的列表.默認(rèn)單詞是空的列表

7、language 分詞器

https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-lang-analyzer.html

一個(gè)用于解析特殊語(yǔ)言文本的analyzer集合顾稀。( arabic,armenian, basque, brazilian, bulgarian, catalan, cjk, czech, danish, dutch, english, finnish, french,galician, german, greek, hindi, hungarian, indonesian, irish, italian, latvian, lithuanian, norwegian,persian, portuguese, romanian, russian, sorani, spanish, swedish, turkish, thai.)可惜沒(méi)有中文达罗。不予考慮

8、snowball 分詞器

一個(gè)snowball類型的analyzer是由standard tokenizer和standard filter静秆、lowercase filter粮揉、stop filter巡李、snowball filter這四個(gè)filter構(gòu)成的。

snowball analyzer 在Lucene中通常是不推薦使用的扶认。

9侨拦、Custom 分詞器

是自定義的analyzer。允許多個(gè)零到多個(gè)tokenizer蝠引,零到多個(gè) Char Filters. custom analyzer 的名字不能以 "_"開頭.

The following are settings that can be set for a custom analyzer type:

SettingDescriptiontokenizer通用的或者注冊(cè)的tokenizer.filter通用的或者注冊(cè)的token filterschar_filter通用的或者注冊(cè)的 character filtersposition_increment_gap距離查詢時(shí)阳谍,最大允許查詢的距離,默認(rèn)是100

自定義的模板:

index :
    analysis :
        analyzer :
            myAnalyzer2 :
                type : custom
                tokenizer : myTokenizer1
                filter : [myTokenFilter1, myTokenFilter2]
                char_filter : [my_html]
                position_increment_gap: 256
        tokenizer :
            myTokenizer1 :
                type : standard
                max_token_length : 900
        filter :
            myTokenFilter1 :
                type : stop
                stopwords : [stop1, stop2, stop3, stop4]
            myTokenFilter2 :
                type : length
                min : 0
                max : 2000
        char_filter :
              my_html :
                type : html_strip
                escaped_tags : [xxx, yyy]
                read_ahead : 1024

10螃概、fingerprint 分詞器

https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-fingerprint-analyzer.html


中文分詞器:

1矫夯、ik-analyzer

https://github.com/wks/ik-analyzer

IKAnalyzer是一個(gè)開源的,基于java語(yǔ)言開發(fā)的輕量級(jí)的中文分詞工具包吊洼。

采用了特有的“正向迭代最細(xì)粒度切分算法“训貌,支持細(xì)粒度和最大詞長(zhǎng)兩種切分模式;具有83萬(wàn)字/秒(1600KB/S)的高速處理能力冒窍。

采用了多子處理器分析模式递沪,支持:英文字母、數(shù)字综液、中文詞匯等分詞處理款慨,兼容韓文、日文字符

優(yōu)化的詞典存儲(chǔ)谬莹,更小的內(nèi)存占用檩奠。支持用戶詞典擴(kuò)展定義

針對(duì)Lucene全文檢索優(yōu)化的查詢分析器IKQueryParser(作者吐血推薦);引入簡(jiǎn)單搜索表達(dá)式附帽,采用歧義分析算法優(yōu)化查詢關(guān)鍵字的搜索排列組合埠戳,能極大的提高Lucene檢索的命中率。

Maven用法:

<dependency>
    <groupId>org.wltea.ik-analyzer</groupId>
    <artifactId>ik-analyzer</artifactId>
    <version>3.2.8</version>
</dependency>

在IK Analyzer加入Maven Central Repository之前蕉扮,你需要手動(dòng)安裝整胃,安裝到本地的repository,或者上傳到自己的Maven repository服務(wù)器上喳钟。

要安裝到本地Maven repository屁使,使用如下命令,將自動(dòng)編譯奔则,打包并安裝: mvn install -Dmaven.test.skip=true

Elasticsearch添加中文分詞

安裝IK分詞插件

https://github.com/medcl/elasticsearch-analysis-ik

進(jìn)入elasticsearch-analysis-ik-master

更多安裝請(qǐng)參考博客:

1蛮寂、為elastic添加中文分詞http://blog.csdn.net/dingzfang/article/details/42776693

2、如何在Elasticsearch中安裝中文分詞器(IK+pinyin)http://www.cnblogs.com/xing901022/p/5910139.html

3应狱、Elasticsearch 中文分詞器 IK 配置和使用http://blog.csdn.net/jam00/article/details/52983056

ik 帶有兩個(gè)分詞器

ik_max_word:會(huì)將文本做最細(xì)粒度的拆分缤骨;盡可能多的拆分出詞語(yǔ)

ik_smart:會(huì)做最粗粒度的拆分唧席;已被分出的詞語(yǔ)將不會(huì)再次被其它詞語(yǔ)占有

區(qū)別:

# ik_max_word

curl -XGET 'http://localhost:9200/_analyze?pretty&analyzer=ik_max_word' -d '聯(lián)想是全球最大的筆記本廠商'
#返回

{
  "tokens" : [
    {
      "token" : "聯(lián)想",
      "start_offset" : 0,
      "end_offset" : 2,
      "type" : "CN_WORD",
      "position" : 0
    },
    {
      "token" : "是",
      "start_offset" : 2,
      "end_offset" : 3,
      "type" : "CN_CHAR",
      "position" : 1
    },
    {
      "token" : "全球",
      "start_offset" : 3,
      "end_offset" : 5,
      "type" : "CN_WORD",
      "position" : 2
    },
    {
      "token" : "最大",
      "start_offset" : 5,
      "end_offset" : 7,
      "type" : "CN_WORD",
      "position" : 3
    },
    {
      "token" : "的",
      "start_offset" : 7,
      "end_offset" : 8,
      "type" : "CN_CHAR",
      "position" : 4
    },
    {
      "token" : "筆記本",
      "start_offset" : 8,
      "end_offset" : 11,
      "type" : "CN_WORD",
      "position" : 5
    },
    {
      "token" : "筆記",
      "start_offset" : 8,
      "end_offset" : 10,
      "type" : "CN_WORD",
      "position" : 6
    },
    {
      "token" : "本廠",
      "start_offset" : 10,
      "end_offset" : 12,
      "type" : "CN_WORD",
      "position" : 7
    },
    {
      "token" : "廠商",
      "start_offset" : 11,
      "end_offset" : 13,
      "type" : "CN_WORD",
      "position" : 8
    }
  ]
}

# ik_smart

curl -XGET 'http://localhost:9200/_analyze?pretty&analyzer=ik_smart' -d '聯(lián)想是全球最大的筆記本廠商'

# 返回

{
  "tokens" : [
    {
      "token" : "聯(lián)想",
      "start_offset" : 0,
      "end_offset" : 2,
      "type" : "CN_WORD",
      "position" : 0
    },
    {
      "token" : "是",
      "start_offset" : 2,
      "end_offset" : 3,
      "type" : "CN_CHAR",
      "position" : 1
    },
    {
      "token" : "全球",
      "start_offset" : 3,
      "end_offset" : 5,
      "type" : "CN_WORD",
      "position" : 2
    },
    {
      "token" : "最大",
      "start_offset" : 5,
      "end_offset" : 7,
      "type" : "CN_WORD",
      "position" : 3
    },
    {
      "token" : "的",
      "start_offset" : 7,
      "end_offset" : 8,
      "type" : "CN_CHAR",
      "position" : 4
    },
    {
      "token" : "筆記本",
      "start_offset" : 8,
      "end_offset" : 11,
      "type" : "CN_WORD",
      "position" : 5
    },
    {
      "token" : "廠商",
      "start_offset" : 11,
      "end_offset" : 13,
      "type" : "CN_WORD",
      "position" : 6
    }
  ]
}

下面我們來(lái)創(chuàng)建一個(gè)索引橘茉,使用 ik 創(chuàng)建一個(gè)名叫 iktest 的索引怎憋,設(shè)置它的分析器用 ik ,分詞器用 ik_max_word岸蜗,并創(chuàng)建一個(gè) article 的類型尉咕,里面有一個(gè) subject 的字段,指定其使用 ik_max_word 分詞器

curl -XPUT 'http://localhost:9200/iktest?pretty' -d '{
    "settings" : {
        "analysis" : {
            "analyzer" : {
                "ik" : {
                    "tokenizer" : "ik_max_word"
                }
            }
        }
    },
    "mappings" : {
        "article" : {
            "dynamic" : true,
            "properties" : {
                "subject" : {
                    "type" : "string",
                    "analyzer" : "ik_max_word"
                }
            }
        }
    }
}'

批量添加幾條數(shù)據(jù)璃岳,這里我指定元數(shù)據(jù) _id 方便查看年缎,subject 內(nèi)容為我隨便找的幾條新聞的標(biāo)題

curl -XPOST http://localhost:9200/iktest/article/_bulk?pretty -d '
{ "index" : { "_id" : "1" } }
{"subject" : ""閨蜜"崔順實(shí)被韓檢方傳喚 韓總統(tǒng)府促?gòu)夭檎嫦? }
{ "index" : { "_id" : "2" } }
{"subject" : "韓舉行"護(hù)國(guó)訓(xùn)練" 青瓦臺(tái):決不許國(guó)家安全出問(wèn)題" }
{ "index" : { "_id" : "3" } }
{"subject" : "媒體稱FBI已經(jīng)取得搜查令 檢視希拉里電郵" }
{ "index" : { "_id" : "4" } }
{"subject" : "村上春樹獲安徒生獎(jiǎng) 演講中談及歐洲排外問(wèn)題" }
{ "index" : { "_id" : "5" } }
{"subject" : "希拉里團(tuán)隊(duì)炮轟FBI 參院民主黨領(lǐng)袖批其“違法”" }
'

查詢 “希拉里和韓國(guó)”

curl -XPOST http://localhost:9200/iktest/article/_search?pretty  -d'
{
    "query" : { "match" : { "subject" : "希拉里和韓國(guó)" }},
    "highlight" : {
        "pre_tags" : ["<font color='red'>"],
        "post_tags" : ["</font>"],
        "fields" : {
            "subject" : {}
        }
    }
}
'
#返回
{
  "took" : 113,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 4,
    "max_score" : 0.034062363,
    "hits" : [ {
      "_index" : "iktest",
      "_type" : "article",
      "_id" : "2",
      "_score" : 0.034062363,
      "_source" : {
        "subject" : "韓舉行"護(hù)國(guó)訓(xùn)練" 青瓦臺(tái):決不許國(guó)家安全出問(wèn)題"
      },
      "highlight" : {
        "subject" : [ "<font color=red>韓</font>舉行"護(hù)<font color=red>國(guó)</font>訓(xùn)練" 青瓦臺(tái):決不許國(guó)家安全出問(wèn)題" ]
      }
    }, {
      "_index" : "iktest",
      "_type" : "article",
      "_id" : "3",
      "_score" : 0.0076681254,
      "_source" : {
        "subject" : "媒體稱FBI已經(jīng)取得搜查令 檢視希拉里電郵"
      },
      "highlight" : {
        "subject" : [ "媒體稱FBI已經(jīng)取得搜查令 檢視<font color=red>希拉里</font>電郵" ]
      }
    }, {
      "_index" : "iktest",
      "_type" : "article",
      "_id" : "5",
      "_score" : 0.006709609,
      "_source" : {
        "subject" : "希拉里團(tuán)隊(duì)炮轟FBI 參院民主黨領(lǐng)袖批其“違法”"
      },
      "highlight" : {
        "subject" : [ "<font color=red>希拉里</font>團(tuán)隊(duì)炮轟FBI 參院民主黨領(lǐng)袖批其“違法”" ]
      }
    }, {
      "_index" : "iktest",
      "_type" : "article",
      "_id" : "1",
      "_score" : 0.0021509775,
      "_source" : {
        "subject" : ""閨蜜"崔順實(shí)被韓檢方傳喚 韓總統(tǒng)府促?gòu)夭檎嫦?
      },
      "highlight" : {
        "subject" : [ ""閨蜜"崔順實(shí)被<font color=red>韓</font>檢方傳喚 <font color=red>韓</font>總統(tǒng)府促?gòu)夭檎嫦? ]
      }
    } ]
  }
}

這里用了高亮屬性 highlight,直接顯示到 html 中铃慷,被匹配到的字或詞將以紅色突出顯示单芜。若要用過(guò)濾搜索,直接將 match 改為 term 即可

熱詞更新配置

網(wǎng)絡(luò)詞語(yǔ)日新月異犁柜,如何讓新出的網(wǎng)絡(luò)熱詞(或特定的詞語(yǔ))實(shí)時(shí)的更新到我們的搜索當(dāng)中呢

先用 ik 測(cè)試一下

curl -XGET 'http://localhost:9200/_analyze?pretty&analyzer=ik_max_word' -d '
成龍?jiān)惛凵?'
#返回
{
  "tokens" : [ {
    "token" : "成龍",
    "start_offset" : 1,
    "end_offset" : 3,
    "type" : "CN_WORD",
    "position" : 0
  }, {
    "token" : "原名",
    "start_offset" : 3,
    "end_offset" : 5,
    "type" : "CN_WORD",
    "position" : 1
  }, {
    "token" : "陳",
    "start_offset" : 5,
    "end_offset" : 6,
    "type" : "CN_CHAR",
    "position" : 2
  }, {
    "token" : "港",
    "start_offset" : 6,
    "end_offset" : 7,
    "type" : "CN_WORD",
    "position" : 3
  }, {
    "token" : "生",
    "start_offset" : 7,
    "end_offset" : 8,
    "type" : "CN_CHAR",
    "position" : 4
  } ]
}

ik 的主詞典中沒(méi)有”陳港生” 這個(gè)詞洲鸠,所以被拆分了。 現(xiàn)在我們來(lái)配置一下

修改 IK 的配置文件 :ES 目錄/plugins/ik/config/ik/IKAnalyzer.cfg.xml

修改如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <comment>IK Analyzer 擴(kuò)展配置</comment>
    <!--用戶可以在這里配置自己的擴(kuò)展字典 -->
    <entry key="ext_dict">custom/mydict.dic;custom/single_word_low_freq.dic</entry>
     <!--用戶可以在這里配置自己的擴(kuò)展停止詞字典-->
    <entry key="ext_stopwords">custom/ext_stopword.dic</entry>
    <!--用戶可以在這里配置遠(yuǎn)程擴(kuò)展字典 -->
    <entry key="remote_ext_dict">http://192.168.1.136/hotWords.php</entry>
    <!--用戶可以在這里配置遠(yuǎn)程擴(kuò)展停止詞字典-->
    <!-- <entry key="remote_ext_stopwords">words_location</entry> -->
</properties>

這里我是用的是遠(yuǎn)程擴(kuò)展字典馋缅,因?yàn)榭梢允褂闷渌绦蛘{(diào)用更新扒腕,且不用重啟 ES,很方便萤悴;當(dāng)然使用自定義的 mydict.dic 字典也是很方便的瘾腰,一行一個(gè)詞,自己加就可以了

既然是遠(yuǎn)程詞典覆履,那么就要是一個(gè)可訪問(wèn)的鏈接蹋盆,可以是一個(gè)頁(yè)面,也可以是一個(gè)txt的文檔内狗,但要保證輸出的內(nèi)容是 utf-8 的格式

hotWords.php 的內(nèi)容

$s = <<<'EOF'
陳港生
元樓
藍(lán)瘦
EOF;
header('Last-Modified: '.gmdate('D, d M Y H:i:s', time()).' GMT', true, 200);
header('ETag: "5816f349-19"');
echo $s;

ik 接收兩個(gè)返回的頭部屬性 Last-Modified 和 ETag怪嫌,只要其中一個(gè)有變化,就會(huì)觸發(fā)更新柳沙,ik 會(huì)每分鐘獲取一次 重啟 Elasticsearch 岩灭,查看啟動(dòng)記錄,看到了三個(gè)詞已被加載進(jìn)來(lái)

再次執(zhí)行上面的請(qǐng)求赂鲤,返回, 就可以看到 ik 分詞器已經(jīng)匹配到了 “陳港生” 這個(gè)詞噪径,同理一些關(guān)于我們公司的專有名字(例如:永輝、永輝超市数初、永輝云創(chuàng)找爱、云創(chuàng) .... )也可以自己手動(dòng)添加到字典中去。

2泡孩、結(jié)巴中文分詞

特點(diǎn):

1车摄、支持三種分詞模式:

  • 精確模式,試圖將句子最精確地切開,適合文本分析吮播;
  • 全模式变屁,把句子中所有的可以成詞的詞語(yǔ)都掃描出來(lái), 速度非常快意狠,但是不能解決歧義粟关;
  • 搜索引擎模式,在精確模式的基礎(chǔ)上环戈,對(duì)長(zhǎng)詞再次切分闷板,提高召回率,適合用于搜索引擎分詞院塞。

2遮晚、支持繁體分詞

3、支持自定義詞典

3拦止、THULAC

THULAC(THU Lexical Analyzer for Chinese)由清華大學(xué)自然語(yǔ)言處理與社會(huì)人文計(jì)算實(shí)驗(yàn)室研制推出的一套中文詞法分析工具包鹏漆,具有中文分詞和詞性標(biāo)注功能。THULAC具有如下幾個(gè)特點(diǎn):

能力強(qiáng)创泄。利用我們集成的目前世界上規(guī)模最大的人工分詞和詞性標(biāo)注中文語(yǔ)料庫(kù)(約含5800萬(wàn)字)訓(xùn)練而成艺玲,模型標(biāo)注能力強(qiáng)大。

準(zhǔn)確率高鞠抑。該工具包在標(biāo)準(zhǔn)數(shù)據(jù)集Chinese Treebank(CTB5)上分詞的F1值可達(dá)97.3%饭聚,詞性標(biāo)注的F1值可達(dá)到92.9%,與該數(shù)據(jù)集上最好方法效果相當(dāng)搁拙。

速度較快秒梳。同時(shí)進(jìn)行分詞和詞性標(biāo)注速度為300KB/s,每秒可處理約15萬(wàn)字箕速。只進(jìn)行分詞速度可達(dá)到1.3MB/s酪碘。

中文分詞工具thulac4j發(fā)布

1、規(guī)范化分詞詞典盐茎,并去掉一些無(wú)用詞兴垦;

2、重寫DAT(雙數(shù)組Trie樹)的構(gòu)造算法字柠,生成的DAT size減少了8%左右探越,從而節(jié)省了內(nèi)存;

3窑业、優(yōu)化分詞算法钦幔,提高了分詞速率。

<dependency>
  <groupId>io.github.yizhiru</groupId>
  <artifactId>thulac4j</artifactId>
  <version>${thulac4j.version}</version>
</dependency>

http://www.cnblogs.com/en-heng/p/6526598.html

thulac4j支持兩種分詞模式:

SegOnly模式常柄,只分詞沒(méi)有詞性標(biāo)注鲤氢;

SegPos模式搀擂,分詞兼有詞性標(biāo)注。

// SegOnly mode
String sentence = "滔滔的流水卷玉,向著波士頓灣無(wú)聲逝去";
SegOnly seg = new SegOnly("models/seg_only.bin");
System.out.println(seg.segment(sentence));
// [滔滔, 的, 流水, 哥倔,, 向著, 波士頓灣, 無(wú)聲, 逝去]

// SegPos mode
SegPos pos = new SegPos("models/seg_pos.bin");
System.out.println(pos.segment(sentence));
//[滔滔/a, 的/u, 流水/n, ,/w, 向著/p, 波士頓灣/ns, 無(wú)聲/v, 逝去/v]

4揍庄、NLPIR

中科院計(jì)算所 NLPIR:http://ictclas.nlpir.org/nlpir/ (可直接在線分析中文)

下載地址:https://github.com/NLPIR-team/NLPIR

中科院分詞系統(tǒng)(NLPIR)JAVA簡(jiǎn)易教程: http://www.cnblogs.com/wukongjiuwo/p/4092480.html

5、ansj分詞器

https://github.com/NLPchina/ansj_seg

這是一個(gè)基于n-Gram+CRF+HMM的中文分詞的java實(shí)現(xiàn).

分詞速度達(dá)到每秒鐘大約200萬(wàn)字左右(mac air下測(cè)試)东抹,準(zhǔn)確率能達(dá)到96%以上

目前實(shí)現(xiàn)了.中文分詞. 中文姓名識(shí)別 .

用戶自定義詞典,關(guān)鍵字提取蚂子,自動(dòng)摘要,關(guān)鍵字標(biāo)記等功能 可以應(yīng)用到自然語(yǔ)言處理等方面,適用于對(duì)分詞效果要求高的各種項(xiàng)目.

maven 引入:

<dependency>
            <groupId>org.ansj</groupId>
            <artifactId>ansj_seg</artifactId>
            <version>5.1.1</version>
</dependency>

調(diào)用demo

String str = "歡迎使用ansj_seg,(ansj中文分詞)在這里如果你遇到什么問(wèn)題都可以聯(lián)系我.我一定盡我所能.幫助大家.ansj_seg更快,更準(zhǔn),更自由!" ;
 System.out.println(ToAnalysis.parse(str));

 歡迎/v,使用/v,ansj/en,_,seg/en,,,(,ansj/en,中文/nz,分詞/n,),在/p,這里/r,如果/c,你/r,遇到/v,什么/r,問(wèn)題/n,都/d,可以/v,聯(lián)系/v,我/r,./m,我/r,一定/d,盡我所能/l,./m,幫助/v,大家/r,./m,ansj/en,_,seg/en,更快/d,,,更/d,準(zhǔn)/a,,,更/d,自由/a,!

6缭黔、哈工大的LTP

https://github.com/HIT-SCIR/ltp

LTP制定了基于XML的語(yǔ)言處理結(jié)果表示食茎,并在此基礎(chǔ)上提供了一整套自底向上的豐富而且高效的中文語(yǔ)言處理模塊(包括詞法、句法馏谨、語(yǔ)義等6項(xiàng)中文處理核心技術(shù))别渔,以及基于動(dòng)態(tài)鏈接庫(kù)(Dynamic Link Library, DLL)的應(yīng)用程序接口、可視化工具惧互,并且能夠以網(wǎng)絡(luò)服務(wù)(Web Service)的形式進(jìn)行使用哎媚。

關(guān)于LTP的使用,請(qǐng)參考: http://ltp.readthedocs.io/zh_CN/latest/

7喊儡、庖丁解牛

下載地址:http://pan.baidu.com/s/1eQ88SZS

使用分為如下幾步:

  1. 配置dic文件: 修改paoding-analysis.jar中的paoding-dic-home.properties文件拨与,將“#paoding.dic.home=dic”的注釋去掉,并配置成自己dic文件的本地存放路徑艾猜。eg:/home/hadoop/work/paoding-analysis-2.0.4-beta/dic
  2. 把Jar包導(dǎo)入到項(xiàng)目中: 將paoding-analysis.jar买喧、commons-logging.jar、lucene-analyzers-2.2.0.jar和lucene-core-2.2.0.jar四個(gè)包導(dǎo)入到項(xiàng)目中匆赃,這時(shí)就可以在代碼片段中使用庖丁解牛工具提供的中文分詞技術(shù)淤毛,例如:
Analyzer analyzer = new PaodingAnalyzer(); //定義一個(gè)解析器
String text = "庖丁系統(tǒng)是個(gè)完全基于lucene的中文分詞系統(tǒng),它就是重新建了一個(gè)analyzer算柳,叫做PaodingAnalyzer低淡,這個(gè)analyer的核心任務(wù)就是生成一個(gè)可以切詞TokenStream。"; <span style="font-family: Arial, Helvetica, sans-serif;">//待分詞的內(nèi)容</span>
TokenStream tokenStream = analyzer.tokenStream(text, new StringReader(text)); //得到token序列的輸出流
try {
    Token t;
    while ((t = tokenStream.next()) != null)
    {
           System.out.println(t); //輸出每個(gè)token
    }
} catch (IOException e) {
    e.printStackTrace();
}

8瞬项、sogo在線分詞

sogo在線分詞采用了基于漢字標(biāo)注的分詞方法查牌,主要使用了線性鏈鏈CRF(Linear-chain CRF)模型。詞性標(biāo)注模塊主要基于結(jié)構(gòu)化線性模型(Structured Linear Model)

在線使用地址為: http://www.sogou.com/labs/webservice/

9滥壕、word分詞

地址: https://github.com/ysc/word

word分詞是一個(gè)Java實(shí)現(xiàn)的分布式的中文分詞組件纸颜,提供了多種基于詞典的分詞算法,并利用ngram模型來(lái)消除歧義绎橘。能準(zhǔn)確識(shí)別英文胁孙、數(shù)字唠倦,以及日期、時(shí)間等數(shù)量詞涮较,能識(shí)別人名稠鼻、地名、組織機(jī)構(gòu)名等未登錄詞狂票。能通過(guò)自定義配置文件來(lái)改變組件行為候齿,能自定義用戶詞庫(kù)、自動(dòng)檢測(cè)詞庫(kù)變化闺属、支持大規(guī)模分布式環(huán)境慌盯,能靈活指定多種分詞算法,能使用refine功能靈活控制分詞結(jié)果掂器,還能使用詞頻統(tǒng)計(jì)亚皂、詞性標(biāo)注、同義標(biāo)注国瓮、反義標(biāo)注灭必、拼音標(biāo)注等功能。提供了10種分詞算法乃摹,還提供了10種文本相似度算法禁漓,同時(shí)還無(wú)縫和Lucene、Solr孵睬、ElasticSearch璃饱、Luke集成。注意:word1.3需要JDK1.8

maven 中引入依賴:

<dependencies>
    <dependency>
        <groupId>org.apdplat</groupId>
        <artifactId>word</artifactId>
        <version>1.3</version>
    </dependency>
</dependencies>

ElasticSearch插件:

1肪康、打開命令行并切換到elasticsearch的bin目錄
cd elasticsearch-2.1.1/bin

2荚恶、運(yùn)行plugin腳本安裝word分詞插件:
./plugin install http://apdplat.org/word/archive/v1.4.zip

安裝的時(shí)候注意:
    如果提示:
        ERROR: failed to download
    或者
        Failed to install word, reason: failed to download
    或者
        ERROR: incorrect hash (SHA1)
    則重新再次運(yùn)行命令,如果還是不行磷支,多試兩次

如果是elasticsearch1.x系列版本谒撼,則使用如下命令:
./plugin -u http://apdplat.org/word/archive/v1.3.1.zip -i word

3、修改文件elasticsearch-2.1.1/config/elasticsearch.yml雾狈,新增如下配置:
index.analysis.analyzer.default.type : "word"
index.analysis.tokenizer.default.type : "word"

4廓潜、啟動(dòng)ElasticSearch測(cè)試效果,在Chrome瀏覽器中訪問(wèn):
http://localhost:9200/_analyze?analyzer=word&text=楊尚川是APDPlat應(yīng)用級(jí)產(chǎn)品開發(fā)平臺(tái)的作者

5善榛、自定義配置
修改配置文件elasticsearch-2.1.1/plugins/word/word.local.conf

6辩蛋、指定分詞算法
修改文件elasticsearch-2.1.1/config/elasticsearch.yml,新增如下配置:
index.analysis.analyzer.default.segAlgorithm : "ReverseMinimumMatching"
index.analysis.tokenizer.default.segAlgorithm : "ReverseMinimumMatching"

這里segAlgorithm可指定的值有:
正向最大匹配算法:MaximumMatching
逆向最大匹配算法:ReverseMaximumMatching
正向最小匹配算法:MinimumMatching
逆向最小匹配算法:ReverseMinimumMatching
雙向最大匹配算法:BidirectionalMaximumMatching
雙向最小匹配算法:BidirectionalMinimumMatching
雙向最大最小匹配算法:BidirectionalMaximumMinimumMatching
全切分算法:FullSegmentation
最少詞數(shù)算法:MinimalWordCount
最大Ngram分值算法:MaxNgramScore
如不指定移盆,默認(rèn)使用雙向最大匹配算法:BidirectionalMaximumMatching

10悼院、jcseg分詞器

https://code.google.com/archive/p/jcseg/

11、stanford分詞器

Stanford大學(xué)的一個(gè)開源分詞工具咒循,目前已支持漢語(yǔ)据途。

首先绞愚,去【1】下載Download Stanford Word Segmenter version 3.5.2,取得里面的 data 文件夾颖医,放在maven project的 src/main/resources 里位衩。

然后,maven依賴添加:

<properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <corenlp.version>3.6.0</corenlp.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>edu.stanford.nlp</groupId>
            <artifactId>stanford-corenlp</artifactId>
            <version>${corenlp.version}</version>
        </dependency>
        <dependency>
            <groupId>edu.stanford.nlp</groupId>
            <artifactId>stanford-corenlp</artifactId>
            <version>${corenlp.version}</version>
            <classifier>models</classifier>
        </dependency>
        <dependency>
            <groupId>edu.stanford.nlp</groupId>
            <artifactId>stanford-corenlp</artifactId>
            <version>${corenlp.version}</version>
            <classifier>models-chinese</classifier>
        </dependency>
    </dependencies>

測(cè)試:

import java.util.Properties;

import edu.stanford.nlp.ie.crf.CRFClassifier;

public class CoreNLPSegment {

    private static CoreNLPSegment instance;
    private CRFClassifier         classifier;

    private CoreNLPSegment(){
        Properties props = new Properties();
        props.setProperty("sighanCorporaDict", "data");
        props.setProperty("serDictionary", "data/dict-chris6.ser.gz");
        props.setProperty("inputEncoding", "UTF-8");
        props.setProperty("sighanPostProcessing", "true");
        classifier = new CRFClassifier(props);
        classifier.loadClassifierNoExceptions("data/ctb.gz", props);
        classifier.flags.setProperties(props);
    }

    public static CoreNLPSegment getInstance() {
        if (instance == null) {
            instance = new CoreNLPSegment();
        }

        return instance;
    }

    public String[] doSegment(String data) {
        return (String[]) classifier.segmentString(data).toArray();
    }

    public static void main(String[] args) {

        String sentence = "他和我在學(xué)校里常打桌球熔萧。";
        String ret[] = CoreNLPSegment.getInstance().doSegment(sentence);
        for (String str : ret) {
            System.out.println(str);
        }

    }

}

博客

https://blog.sectong.com/blog/corenlp_segment.html

http://blog.csdn.net/lightty/article/details/51766602

12糖驴、Smartcn

Smartcn為Apache2.0協(xié)議的開源中文分詞系統(tǒng),Java語(yǔ)言編寫佛致,修改的中科院計(jì)算所ICTCLAS分詞系統(tǒng)贮缕。很早以前看到Lucene上多了一個(gè)中文分詞的contribution,當(dāng)時(shí)只是簡(jiǎn)單的掃了一下.class文件的文件名晌杰,通過(guò)文件名可以看得出又是一個(gè)改的ICTCLAS的分詞系統(tǒng)。

http://lucene.apache.org/core/5_1_0/analyzers-smartcn/org/apache/lucene/analysis/cn/smart/SmartChineseAnalyzer.html

13筷弦、pinyin 分詞器

pinyin分詞器可以讓用戶輸入拼音肋演,就能查找到相關(guān)的關(guān)鍵詞。比如在某個(gè)商城搜索中烂琴,輸入yonghui爹殊,就能匹配到永輝。這樣的體驗(yàn)還是非常好的奸绷。

pinyin分詞器的安裝與IK是一樣的梗夸。下載地址:https://github.com/medcl/elasticsearch-analysis-pinyin

一些參數(shù)請(qǐng)參考 GitHub 的 readme 文檔。

這個(gè)分詞器在1.8版本中号醉,提供了兩種分詞規(guī)則:

  • pinyin,就是普通的把漢字轉(zhuǎn)換成拼音反症;
  • pinyin_first_letter,提取漢字的拼音首字母

使用:

1.Create a index with custom pinyin analyzer

curl -XPUT http://localhost:9200/medcl/ -d'
{
    "index" : {
        "analysis" : {
            "analyzer" : {
                "pinyin_analyzer" : {
                    "tokenizer" : "my_pinyin"
                    }
            },
            "tokenizer" : {
                "my_pinyin" : {
                    "type" : "pinyin",
                    "keep_separate_first_letter" : false,
                    "keep_full_pinyin" : true,
                    "keep_original" : true,
                    "limit_first_letter_length" : 16,
                    "lowercase" : true,
                    "remove_duplicated_term" : true
                }
            }
        }
    }
}'

2.Test Analyzer, analyzing a chinese name, such as 劉德華

http://localhost:9200/medcl/_analyze?text=%e5%88%98%e5%be%b7%e5%8d%8e&analyzer=pinyin_analyzer

{
  "tokens" : [
    {
      "token" : "liu",
      "start_offset" : 0,
      "end_offset" : 1,
      "type" : "word",
      "position" : 0
    },
    {
      "token" : "de",
      "start_offset" : 1,
      "end_offset" : 2,
      "type" : "word",
      "position" : 1
    },
    {
      "token" : "hua",
      "start_offset" : 2,
      "end_offset" : 3,
      "type" : "word",
      "position" : 2
    },
    {
      "token" : "劉德華",
      "start_offset" : 0,
      "end_offset" : 3,
      "type" : "word",
      "position" : 3
    },
    {
      "token" : "ldh",
      "start_offset" : 0,
      "end_offset" : 3,
      "type" : "word",
      "position" : 4
    }
  ]
}

3.Create mapping

curl -XPOST http://localhost:9200/medcl/folks/_mapping -d'
{
    "folks": {
        "properties": {
            "name": {
                "type": "keyword",
                "fields": {
                    "pinyin": {
                        "type": "text",
                        "store": "no",
                        "term_vector": "with_offsets",
                        "analyzer": "pinyin_analyzer",
                        "boost": 10
                    }
                }
            }
        }
    }
}'

4.Indexing

curl -XPOST http://localhost:9200/medcl/folks/andy -d'{"name":"劉德華"}'

5.Let's search

http://localhost:9200/medcl/folks/_search?q=name:%E5%88%98%E5%BE%B7%E5%8D%8E
curl http://localhost:9200/medcl/folks/_search?q=name.pinyin:%e5%88%98%e5%be%b7
curl http://localhost:9200/medcl/folks/_search?q=name.pinyin:liu
curl http://localhost:9200/medcl/folks/_search?q=name.pinyin:ldh
curl http://localhost:9200/medcl/folks/_search?q=name.pinyin:de+hua

6.Using Pinyin-TokenFilter

curl -XPUT http://localhost:9200/medcl1/ -d'
{
    "index" : {
        "analysis" : {
            "analyzer" : {
                "user_name_analyzer" : {
                    "tokenizer" : "whitespace",
                    "filter" : "pinyin_first_letter_and_full_pinyin_filter"
                }
            },
            "filter" : {
                "pinyin_first_letter_and_full_pinyin_filter" : {
                    "type" : "pinyin",
                    "keep_first_letter" : true,
                    "keep_full_pinyin" : false,
                    "keep_none_chinese" : true,
                    "keep_original" : false,
                    "limit_first_letter_length" : 16,
                    "lowercase" : true,
                    "trim_whitespace" : true,
                    "keep_none_chinese_in_first_letter" : true
                }
            }
        }
    }
}'

Token Test:劉德華 張學(xué)友 郭富城 黎明 四大天王

curl -XGET http://localhost:9200/medcl1/_analyze?text=%e5%88%98%e5%be%b7%e5%8d%8e+%e5%bc%a0%e5%ad%a6%e5%8f%8b+%e9%83%ad%e5%af%8c%e5%9f%8e+%e9%bb%8e%e6%98%8e+%e5%9b%9b%e5%a4%a7%e5%a4%a9%e7%8e%8b&analyzer=user_name_analyzer

{
  "tokens" : [
    {
      "token" : "ldh",
      "start_offset" : 0,
      "end_offset" : 3,
      "type" : "word",
      "position" : 0
    },
    {
      "token" : "zxy",
      "start_offset" : 4,
      "end_offset" : 7,
      "type" : "word",
      "position" : 1
    },
    {
      "token" : "gfc",
      "start_offset" : 8,
      "end_offset" : 11,
      "type" : "word",
      "position" : 2
    },
    {
      "token" : "lm",
      "start_offset" : 12,
      "end_offset" : 14,
      "type" : "word",
      "position" : 3
    },
    {
      "token" : "sdtw",
      "start_offset" : 15,
      "end_offset" : 19,
      "type" : "word",
      "position" : 4
    }
  ]
}

7.Used in phrase query

(1)畔派、

 PUT /medcl/
  {
      "index" : {
          "analysis" : {
              "analyzer" : {
                  "pinyin_analyzer" : {
                      "tokenizer" : "my_pinyin"
                      }
              },
              "tokenizer" : {
                  "my_pinyin" : {
                      "type" : "pinyin",
                      "keep_first_letter":false,
                      "keep_separate_first_letter" : false,
                      "keep_full_pinyin" : true,
                      "keep_original" : false,
                      "limit_first_letter_length" : 16,
                      "lowercase" : true
                  }
              }
          }
      }
  }
  GET /medcl/folks/_search
  {
    "query": {"match_phrase": {
      "name.pinyin": "劉德華"
    }}
  }

(2)铅碍、

PUT /medcl/
  {
      "index" : {
          "analysis" : {
              "analyzer" : {
                  "pinyin_analyzer" : {
                      "tokenizer" : "my_pinyin"
                      }
              },
              "tokenizer" : {
                  "my_pinyin" : {
                      "type" : "pinyin",
                      "keep_first_letter":false,
                      "keep_separate_first_letter" : true,
                      "keep_full_pinyin" : false,
                      "keep_original" : false,
                      "limit_first_letter_length" : 16,
                      "lowercase" : true
                  }
              }
          }
      }
  }

  POST /medcl/folks/andy
  {"name":"劉德華"}

  GET /medcl/folks/_search
  {
    "query": {"match_phrase": {
      "name.pinyin": "劉德h"
    }}
  }

  GET /medcl/folks/_search
  {
    "query": {"match_phrase": {
      "name.pinyin": "劉dh"
    }}
  }

  GET /medcl/folks/_search
  {
    "query": {"match_phrase": {
      "name.pinyin": "dh"
    }}
  }

14、Mmseg 分詞器

也支持 Elasticsearch

下載地址:https://github.com/medcl/elasticsearch-analysis-mmseg/releases 根據(jù)對(duì)應(yīng)的版本進(jìn)行下載

如何使用:

1线椰、創(chuàng)建索引:

curl -XPUT http://localhost:9200/index

2胞谈、創(chuàng)建 mapping

curl -XPOST http://localhost:9200/index/fulltext/_mapping -d'
{
        "properties": {
            "content": {
                "type": "text",
                "term_vector": "with_positions_offsets",
                "analyzer": "mmseg_maxword",
                "search_analyzer": "mmseg_maxword"
            }
        }

}'

3.Indexing some docs

curl -XPOST http://localhost:9200/index/fulltext/1 -d'
{"content":"美國(guó)留給伊拉克的是個(gè)爛攤子嗎"}
'

curl -XPOST http://localhost:9200/index/fulltext/2 -d'
{"content":"公安部:各地校車將享最高路權(quán)"}
'

curl -XPOST http://localhost:9200/index/fulltext/3 -d'
{"content":"中韓漁警沖突調(diào)查:韓警平均每天扣1艘中國(guó)漁船"}
'

curl -XPOST http://localhost:9200/index/fulltext/4 -d'
{"content":"中國(guó)駐洛杉磯領(lǐng)事館遭亞裔男子槍擊 嫌犯已自首"}
'

4.Query with highlighting(查詢高亮)

curl -XPOST http://localhost:9200/index/fulltext/_search  -d'
{
    "query" : { "term" : { "content" : "中國(guó)" }},
    "highlight" : {
        "pre_tags" : ["<tag1>", "<tag2>"],
        "post_tags" : ["</tag1>", "</tag2>"],
        "fields" : {
            "content" : {}
        }
    }
}
'

5、結(jié)果:

{
    "took": 14,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "failed": 0
    },
    "hits": {
        "total": 2,
        "max_score": 2,
        "hits": [
            {
                "_index": "index",
                "_type": "fulltext",
                "_id": "4",
                "_score": 2,
                "_source": {
                    "content": "中國(guó)駐洛杉磯領(lǐng)事館遭亞裔男子槍擊 嫌犯已自首"
                },
                "highlight": {
                    "content": [
                        "<tag1>中國(guó)</tag1>駐洛杉磯領(lǐng)事館遭亞裔男子槍擊 嫌犯已自首 "
                    ]
                }
            },
            {
                "_index": "index",
                "_type": "fulltext",
                "_id": "3",
                "_score": 2,
                "_source": {
                    "content": "中韓漁警沖突調(diào)查:韓警平均每天扣1艘中國(guó)漁船"
                },
                "highlight": {
                    "content": [
                        "均每天扣1艘<tag1>中國(guó)</tag1>漁船 "
                    ]
                }
            }
        ]
    }
}

參考博客:

為elastic添加中文分詞: http://blog.csdn.net/dingzfang/article/details/42776693

15憨愉、bosonnlp (玻森數(shù)據(jù)中文分析器)

下載地址:https://github.com/bosondata/elasticsearch-analysis-bosonnlp

如何使用:

運(yùn)行 ElasticSearch 之前需要在 config 文件夾中修改 elasticsearch.yml 來(lái)定義使用玻森中文分析器烦绳,并填寫玻森 API_TOKEN 以及玻森分詞 API 的地址,即在該文件結(jié)尾處添加:

index:
  analysis:
    analyzer:
      bosonnlp:
          type: bosonnlp
          API_URL: http://api.bosonnlp.com/tag/analysis
          # You MUST give the API_TOKEN value, otherwise it doesn't work
          API_TOKEN: *PUT YOUR API TOKEN HERE*
          # Please uncomment if you want to specify ANY ONE of the following
          # areguments, otherwise the DEFAULT value will be used, i.e.,
          # space_mode is 0,
          # oov_level is 3,
          # t2s is 0,
          # special_char_conv is 0.
          # More detials can be found in bosonnlp docs:
          # http://docs.bosonnlp.com/tag.html
          #
          #
          # space_mode: put your value here(range from 0-3)
          # oov_level: put your value here(range from 0-4)
          # t2s: put your value here(range from 0-1)
          # special_char_conv: put your value here(range from 0-1)

需要注意的是

必須在 API_URL 填寫給定的分詞地址以及在API_TOKEN:PUT YOUR API TOKEN HERE中填寫給定的玻森數(shù)據(jù)API_TOKEN配紫,否則無(wú)法使用玻森中文分析器径密。該 API_TOKEN 是注冊(cè)玻森數(shù)據(jù)賬號(hào)所獲得。

如果配置文件中已經(jīng)有配置過(guò)其他的 analyzer躺孝,請(qǐng)直接在 analyzer 下如上添加 bosonnlp analyzer睹晒。

如果有多個(gè) node 并且都需要 BosonNLP 的分詞插件趟庄,則每個(gè) node 下的 yaml 文件都需要如上安裝和設(shè)置。

另外伪很,玻森中文分詞還提供了4個(gè)參數(shù)(space_mode戚啥,oov_level,t2s锉试,special_char_conv)可滿足不同的分詞需求猫十。如果取默認(rèn)值,則無(wú)需任何修改呆盖;否則拖云,可取消對(duì)應(yīng)參數(shù)的注釋并賦值。

測(cè)試:

建立 index

curl -XPUT 'localhost:9200/test'

測(cè)試分析器是否配置成功

curl -XGET 'localhost:9200/test/_analyze?analyzer=bosonnlp&pretty' -d '這是玻森數(shù)據(jù)分詞的測(cè)試'

結(jié)果

{
  "tokens" : [ {
    "token" : "這",
    "start_offset" : 0,
    "end_offset" : 1,
    "type" : "word",
    "position" : 0
  }, {
    "token" : "是",
    "start_offset" : 1,
    "end_offset" : 2,
    "type" : "word",
    "position" : 1
  }, {
    "token" : "玻森",
    "start_offset" : 2,
    "end_offset" : 4,
    "type" : "word",
    "position" : 2
  }, {
    "token" : "數(shù)據(jù)",
    "start_offset" : 4,
    "end_offset" : 6,
    "type" : "word",
    "position" : 3
  }, {
    "token" : "分詞",
    "start_offset" : 6,
    "end_offset" : 8,
    "type" : "word",
    "position" : 4
  }, {
    "token" : "的",
    "start_offset" : 8,
    "end_offset" : 9,
    "type" : "word",
    "position" : 5
  }, {
    "token" : "測(cè)試",
    "start_offset" : 9,
    "end_offset" : 11,
    "type" : "word",
    "position" : 6
  } ]
}

配置 Token Filter

現(xiàn)有的 BosonNLP 分析器沒(méi)有內(nèi)置 token filter应又,如果有過(guò)濾 Token 的需求宙项,可以利用 BosonNLP Tokenizer 和 ES 提供的 token filter 搭建定制分析器。

步驟

配置定制的 analyzer 有以下三個(gè)步驟:

添加 BosonNLP tokenizer 在 elasticsearch.yml 文件中 analysis 下添加 tokenizer株扛, 并在 tokenizer 中添加 BosonNLP tokenizer 的配置:

index:
  analysis:
    analyzer:
      ...
    tokenizer:
      bosonnlp:
          type: bosonnlp
          API_URL: http://api.bosonnlp.com/tag/analysis
          # You MUST give the API_TOKEN value, otherwise it doesn't work
          API_TOKEN: *PUT YOUR API TOKEN HERE*
          # Please uncomment if you want to specify ANY ONE of the following
          # areguments, otherwise the DEFAULT value will be used, i.e.,
          # space_mode is 0,
          # oov_level is 3,
          # t2s is 0,
          # special_char_conv is 0.
          # More detials can be found in bosonnlp docs:
          # http://docs.bosonnlp.com/tag.html
          #
          #
          # space_mode: put your value here(range from 0-3)
          # oov_level: put your value here(range from 0-4)
          # t2s: put your value here(range from 0-1)
          # special_char_conv: put your value here(range from 0-1)

添加 token filter

在 elasticsearch.yml 文件中 analysis 下添加 filter尤筐, 并在 filter 中添加所需 filter 的配置(下面例子中,我們以 lowercase filter 為例):

index:
  analysis:
    analyzer:
      ...
    tokenizer:
      ...
    filter:
      lowercase:
          type: lowercase

添加定制的 analyzer

在 elasticsearch.yml 文件中 analysis 下添加 analyzer洞就, 并在 analyzer 中添加定制的 analyzer 的配置(下面例子中盆繁,我們把定制的 analyzer 命名為 filter_bosonnlp):

index:
  analysis:
    analyzer:
      ...
      filter_bosonnlp:
          type: custom
          tokenizer: bosonnlp
          filter: [lowercase]


自定義分詞器

雖然Elasticsearch帶有一些現(xiàn)成的分析器,然而在分析器上Elasticsearch真正的強(qiáng)大之處在于旬蟋,你可以通過(guò)在一個(gè)適合你的特定數(shù)據(jù)的設(shè)置之中組合字符過(guò)濾器油昂、分詞器、詞匯單元過(guò)濾器來(lái)創(chuàng)建自定義的分析器倾贰。

字符過(guò)濾器

字符過(guò)濾器 用來(lái) 整理 一個(gè)尚未被分詞的字符串冕碟。例如,如果我們的文本是HTML格式的匆浙,它會(huì)包含像<p>或者<div>這樣的HTML標(biāo)簽鸣哀,這些標(biāo)簽是我們不想索引的。我們可以使用 html清除 字符過(guò)濾器 來(lái)移除掉所有的HTML標(biāo)簽吞彤,并且像把á轉(zhuǎn)換為相對(duì)應(yīng)的Unicode字符 á 這樣我衬,轉(zhuǎn)換HTML實(shí)體。

一個(gè)分析器可能有0個(gè)或者多個(gè)字符過(guò)濾器饰恕。

分詞器:

一個(gè)分析器 必須 有一個(gè)唯一的分詞器挠羔。 分詞器把字符串分解成單個(gè)詞條或者詞匯單元。 標(biāo)準(zhǔn) 分析器里使用的 標(biāo)準(zhǔn) 分詞器 把一個(gè)字符串根據(jù)單詞邊界分解成單個(gè)詞條埋嵌,并且移除掉大部分的標(biāo)點(diǎn)符號(hào)破加,然而還有其他不同行為的分詞器存在。

詞單元過(guò)濾器:

經(jīng)過(guò)分詞雹嗦,作為結(jié)果的 詞單元流 會(huì)按照指定的順序通過(guò)指定的詞單元過(guò)濾器 范舀。

詞單元過(guò)濾器可以修改合是、添加或者移除詞單元。我們已經(jīng)提到過(guò) lowercase 和 stop 詞過(guò)濾器 锭环,但是在 Elasticsearch 里面還有很多可供選擇的詞單元過(guò)濾器聪全。 詞干過(guò)濾器 把單詞 遏制 為 詞干。 ascii_folding 過(guò)濾器移除變音符辅辩,把一個(gè)像 "très" 這樣的詞轉(zhuǎn)換為 "tres" 难礼。 ngram 和 edge_ngram 詞單元過(guò)濾器 可以產(chǎn)生 適合用于部分匹配或者自動(dòng)補(bǔ)全的詞單元。

創(chuàng)建一個(gè)自定義分析器

我們可以在 analysis 下的相應(yīng)位置設(shè)置字符過(guò)濾器玫锋、分詞器和詞單元過(guò)濾器:

PUT /my_index
{
    "settings": {
        "analysis": {
            "char_filter": { ... custom character filters ... },
            "tokenizer":   { ...    custom tokenizers     ... },
            "filter":      { ...   custom token filters   ... },
            "analyzer":    { ...    custom analyzers      ... }
        }
    }
}

這個(gè)分析器可以做到下面的這些事:

1蛾茉、使用 html清除 字符過(guò)濾器移除HTML部分。

2撩鹿、使用一個(gè)自定義的 映射 字符過(guò)濾器把 & 替換為 "和" :

"char_filter": {
    "&_to_and": {
        "type":       "mapping",
        "mappings": [ "&=> and "]
    }
}

3谦炬、使用 標(biāo)準(zhǔn) 分詞器分詞。

4节沦、小寫詞條键思,使用 小寫 詞過(guò)濾器處理。

5散劫、使用自定義 停止 詞過(guò)濾器移除自定義的停止詞列表中包含的詞:

"filter": {
    "my_stopwords": {
        "type":        "stop",
        "stopwords": [ "the", "a" ]
    }
}

我們的分析器定義用我們之前已經(jīng)設(shè)置好的自定義過(guò)濾器組合了已經(jīng)定義好的分詞器和過(guò)濾器:

"analyzer": {
    "my_analyzer": {
        "type":           "custom",
        "char_filter":  [ "html_strip", "&_to_and" ],
        "tokenizer":      "standard",
        "filter":       [ "lowercase", "my_stopwords" ]
    }
}

匯總起來(lái)稚机,完整的 創(chuàng)建索引 請(qǐng)求 看起來(lái)應(yīng)該像這樣:

PUT /my_index
{
    "settings": {
        "analysis": {
            "char_filter": {
                "&_to_and": {
                    "type":       "mapping",
                    "mappings": [ "&=> and "]
            }},
            "filter": {
                "my_stopwords": {
                    "type":       "stop",
                    "stopwords": [ "the", "a" ]
            }},
            "analyzer": {
                "my_analyzer": {
                    "type":         "custom",
                    "char_filter":  [ "html_strip", "&_to_and" ],
                    "tokenizer":    "standard",
                    "filter":       [ "lowercase", "my_stopwords" ]
            }}
}}}

索引被創(chuàng)建以后幕帆,使用 analyze API 來(lái) 測(cè)試這個(gè)新的分析器:

GET /my_index/_analyze?analyzer=my_analyzer
The quick & brown fox

下面的縮略結(jié)果展示出我們的分析器正在正確地運(yùn)行:

{
  "tokens" : [
      { "token" :   "quick",    "position" : 2 },
      { "token" :   "and",      "position" : 3 },
      { "token" :   "brown",    "position" : 4 },
      { "token" :   "fox",      "position" : 5 }
    ]
}

這個(gè)分析器現(xiàn)在是沒(méi)有多大用處的获搏,除非我們告訴 Elasticsearch在哪里用上它。我們可以像下面這樣把這個(gè)分析器應(yīng)用在一個(gè) string 字段上:

PUT /my_index/_mapping/my_type
{
    "properties": {
        "title": {
            "type":      "string",
            "analyzer":  "my_analyzer"
        }
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末失乾,一起剝皮案震驚了整個(gè)濱河市常熙,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌碱茁,老刑警劉巖裸卫,帶你破解...
    沈念sama閱讀 218,755評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異纽竣,居然都是意外死亡墓贿,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門蜓氨,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)聋袋,“玉大人,你說(shuō)我怎么就攤上這事穴吹∮睦眨” “怎么了?”我有些...
    開封第一講書人閱讀 165,138評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵港令,是天一觀的道長(zhǎng)啥容。 經(jīng)常有香客問(wèn)我锈颗,道長(zhǎng),這世上最難降的妖魔是什么咪惠? 我笑而不...
    開封第一講書人閱讀 58,791評(píng)論 1 295
  • 正文 為了忘掉前任击吱,我火速辦了婚禮,結(jié)果婚禮上硝逢,老公的妹妹穿的比我還像新娘姨拥。我一直安慰自己,他們只是感情好渠鸽,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,794評(píng)論 6 392
  • 文/花漫 我一把揭開白布叫乌。 她就那樣靜靜地躺著,像睡著了一般徽缚。 火紅的嫁衣襯著肌膚如雪憨奸。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,631評(píng)論 1 305
  • 那天凿试,我揣著相機(jī)與錄音排宰,去河邊找鬼。 笑死那婉,一個(gè)胖子當(dāng)著我的面吹牛板甘,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播详炬,決...
    沈念sama閱讀 40,362評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼盐类,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了呛谜?” 一聲冷哼從身側(cè)響起在跳,我...
    開封第一講書人閱讀 39,264評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎隐岛,沒(méi)想到半個(gè)月后猫妙,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,724評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡聚凹,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評(píng)論 3 336
  • 正文 我和宋清朗相戀三年割坠,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片妒牙。...
    茶點(diǎn)故事閱讀 40,040評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡彼哼,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出单旁,到底是詐尸還是另有隱情沪羔,我是刑警寧澤,帶...
    沈念sama閱讀 35,742評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站蔫饰,受9級(jí)特大地震影響琅豆,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜篓吁,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,364評(píng)論 3 330
  • 文/蒙蒙 一茫因、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧杖剪,春花似錦冻押、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至次兆,卻和暖如春稿茉,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背芥炭。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工漓库, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人园蝠。 一個(gè)月前我還...
    沈念sama閱讀 48,247評(píng)論 3 371
  • 正文 我出身青樓渺蒿,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親彪薛。 傳聞我的和親對(duì)象是個(gè)殘疾皇子茂装,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,979評(píng)論 2 355