独角兽企业重金招聘Python工程师标准>>>
前提是ik和pinyin分词器都安装好了,并运行正常,请参考前面两篇
elasticsearch-5.1.2安装IK分词器并测试
elasticsearch-5.1.2安装pinyin分词器并测试
创建一个索引,并设置index分析器相关属性
[listen@localhost elasticsearch-cluster]$ curl -XPUT 'http://192.168.159.129:9201/ikpinyinindex/?pretty' -d '> {>"index": {> "analysis": {> "analyzer": {> "ik_pinyin_analyzer":{> "type": "custom",> "tokenizer": "ik_smart",> "filter": ["my_pinyin", "word_delimiter"]> }> },> "filter": {> "my_pinyin": {> "type": "pinyin",> "first_letter": "prefix",> "padding_char": " "> }> }> }>}> }'{"acknowledged" : true,"shards_acknowledged" : true}[listen@localhost elasticsearch-cluster]$
创建一个type并设置mapping
[listen@localhost elasticsearch-cluster]$ curl -XPUT 'http://192.168.159.129:9201/ikpinyinindex/folks/_mapping/?pretty' -d '> {>"folks":{> "properties": {> "name": {> "type": "keyword",> "fields": {> "pinyin": {>"type": "text",>"store": "no",>"term_vector": "with_positions_offsets",>"analyzer": "ik_pinyin_analyzer",>"boost": 10> }> }> }> }>}> }'{"acknowledged" : true}[listen@localhost elasticsearch-cluster]$
插入2条记录
[listen@localhost elasticsearch-cluster]$ curl -XPOST 'http://192.168.159.129:9201/ikpinyinindex/folks/andy/?pretty' -d '{"name": "刘德华"}'{"_index" : "ikpinyinindex","_type" : "folks","_id" : "andy","_version" : 1,"result" : "created","_shards" : {"total" : 2,"successful" : 1,"failed" : 0},"created" : true}[listen@localhost elasticsearch-cluster]$ [listen@localhost elasticsearch-cluster]$ curl -XPOST 'http://192.168.159.129:9201/ikpinyinindex/folks/tina/?pretty' -d '{"name": "中华人民共和国国歌"}'{"_index" : "ikpinyinindex","_type" : "folks","_id" : "tina","_version" : 1,"result" : "created","_shards" : {"total" : 2,"successful" : 1,"failed" : 0},"created" : true}[listen@localhost elasticsearch-cluster]$
测试
[listen@localhost elasticsearch-cluster]$ curl -XPOST 'http://192.168.159.129:9201/ikpinyinindex/_search/?pretty' -d '> {>"query":{> "match":{> "name.pinyin": "zhonghua"> }>},>"highlight":{> "fields": {> "name.pinyin": {}> }>}> }'{"took" : 74,"timed_out" : false,"_shards" : {"total" : 5,"successful" : 5,"failed" : 0},"hits" : {"total" : 2,"max_score" : 5.9814634,"hits" : [{"_index" : "ikpinyinindex","_type" : "folks","_id" : "tina","_score" : 5.9814634,"_source" : {"name" : "中华人民共和国国歌"},"highlight" : {"name.pinyin" : ["<em>中华人民共和国</em>国歌"]}},{"_index" : "ikpinyinindex","_type" : "folks","_id" : "andy","_score" : 2.2534127,"_source" : {"name" : "刘德华"},"highlight" : {"name.pinyin" : ["<em>刘德华</em>"]}}]}}[listen@localhost elasticsearch-cluster]$
错误的写法,返回结果为空
[listen@localhost elasticsearch-cluster]$ curl -XPOST 'http://192.168.159.129:9201/ikpinyinindex/_search/?pretty' -d '{"query":{"match":{"name": "中华"}},"highlight":{"fields": {"name.pinyin": {}}}}'{"took" : 18,"timed_out" : false,"_shards" : {"total" : 5,"successful" : 5,"failed" : 0},"hits" : {"total" : 0,"max_score" : null,"hits" : [ ]}}[listen@localhost elasticsearch-cluster]$