1下载ik中文/拼音分词器
ik分词器:https://github.com/medcl/elasticsearch-analysis-ik
拼音分词器:https://github.com/medcl/elasticsearch-analysis-pinyin
注意:elasticsearch版本要求严格必须相同
2 安装
1)通过releases找到和es对应版本的zip文件,或者source文件
2)进入elasticsearch安装目录plugins,新建pinyin文件夹
3)将拼音分词器zip文件解压到pinyin目录
4)重启es
3 kibana中配置
1)配置setting
1PUT my_index 2 { 3 "number_of_shards" : "5",//主分片 4 "number_of_replicas" : "1",//副本 5 "analysis" : { 6 "analyzer" : { 7 "default" : { 8 "tokenizer" : "ik_max_word"//默认多词分词 9 }, 10 "pinyin_analyzer" : { 11 "tokenizer" : "my_pinyin"//拼音分词 12 } 13 }, 14 "tokenizer" : { 15 //设置拼音分词 16 "my_pinyin" : { 17 "keep_separate_first_letter" : "false", 18 "lowercase" : "true", 19 "type" : "pinyin", 20 "limit_first_letter_length" : "16", 21 "keep_original" : "false", 22 "keep_full_pinyin" : "true" 23 } 24 } 25 } 26 }
2)配置mapping
1PUT my_index/index/_mapping 2{ 3 "properties" : { 4 "name" : { 5 "type" : "keyword", 6 "analyzer" : "ik_max_word", 7 "include_in_all" : true, 8 "fields" : { 9 "pinyin" : { 10 "type" : "text", 11 "analyzer" : "pinyin_analyzer" 12 } 13 } 14 } 15 } 16}
4 测试
通过_analyze测试下分词器是否能正常运行:
1GET my_index/_analyze 2{ 3"text":"刘德华", 4"analyzer":"pinyin_analyzer" 5}
5 spring boot 中自动创建setting mapping
1)在resources路径下创建usersearch_mapping.json和usersearch_setting.json文件
1usersearch_mapping.json{ 2 "index" : { 3 "analysis" : { 4 "analyzer" : { 5 "pinyin_analyzer" : { 6 "tokenizer" : "my_pinyin" 7 } 8 }, 9 "tokenizer" : { 10 "my_pinyin" : { 11 "type" : "pinyin", 12 "keep_separate_first_letter" : false, 13 "keep_full_pinyin" : true, 14 "keep_original" : true, 15 "limit_first_letter_length" : 16, 16 "lowercase" : true, 17 "remove_duplicated_term" : true 18 } 19 } 20 } 21 } 22} 23 24usersearch_setting.json 25 26{ 27 "user": { 28 "properties": { 29 "title": { 30 "type": "keyword", 31 "fields": { 32 "pinyin": { 33 "type": "text", 34 "store": "no", 35 "term_vector": "with_offsets", 36 "analyzer": "pinyin_analyzer" 37 } 38 } 39 } 40 } 41 } 42}
2)新建测试demo 使用@Mapping和@Setting注解
1@Mapping(mappingPath = "usersearch_setting.json") 2@Setting(settingPath = "usersearch_mapping.json") 3@Document(indexName = "user",type = "user",shards = 5,replicas = 1) 4public class UserIndex { 5 @Id 6 private String user; 7//get set省略 8}
3)使用save方法添加数据
使用ElasticsearchTemplate 中的putMapping将setting 和mapping文件执行
1public class UserContrller { 2 @Autowired 3 private UserRepository userRepository; 4 @Autowired 5 private ElasticsearchTemplate elasticsearchTemplate; 6 @RequestMapping("/add") 7 public void add(){ 8 //添加配置 9 elasticsearchTemplate.putMapping(User.class); 10 User user =new User(); 11 userIndex.setUser("陈奕迅"); 12 userRepository.save(user); 13 } 14}