ElasticSearch7.6.2 JavaAPI创建索引并设置IK分词

文章目录

    • 1、ElasticSearch配置类
    • 2、创建测试类
    • 3、IK分词器两种分词模式
      • ik_max_word
      • ik_smart
    • 4、查看效果

1、ElasticSearch配置类

RestHighLevelClient.java

@Configuration
@Component
class ElasticSearchClientConfig {
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("127.0.0.1",9200,"http"))
        );
        return client;
    }
}

2、创建测试类

ElasticSearchRestHighLevelClientTest.java

@SpringBootTest
@RunWith(SpringRunner.class)
class ElasticSearchRestHighLevelClientTest {

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;
    
	@Test
    void testCreateIndex() throws IOException {
        //1.创建索引的请求
        CreateIndexRequest request = new CreateIndexRequest("movie_index");

        XContentBuilder builder = XContentFactory.jsonBuilder();
        builder.startObject();
        {
            builder.startObject("properties");
            {
                //创建电影ID文档字段
                builder.startObject("movie_id");
                {
                    builder.field("type", "long");
                }
                builder.endObject();
                //创建电影名字文档字段
                builder.startObject("movie_name");
                {
                    builder.field("type", "text")
                            //插入时分词
                            .field("analyzer", "ik_smart")
                            //搜索时分词
                            .field("search_analyzer", "ik_max_word");
                }
                builder.endObject();
                //创建电影描述文档字段
                builder.startObject("movie_detail");
                {
                    builder.field("type", "text")
                    		//插入时分词
                            .field("analyzer", "ik_smart")
                            //搜索时分词
                            .field("search_analyzer", "ik_max_word");
                }
                builder.endObject();
            }
            builder.endObject();
        }
        builder.endObject();
        request.mapping(builder);
        //2客户端执行请求,请求后获得响应
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(response);
    }
 }

3、IK分词器两种分词模式

ik_max_word

会将文本做最细粒度的拆分,比如会将“朝暮轮回,四季更替”拆分为 “朝暮、轮回、四季、更替、四、季

ik_smart

会做最粗粒度的拆分,比如会将“朝暮轮回,四季更替”拆分为 “朝暮、轮回、四季、更替

4、查看效果

ElasticSearch7.6.2 JavaAPI创建索引并设置IK分词_第1张图片

你可能感兴趣的:(elasticsearch)