【elasticsearch系列】SpringBoot整合elasticsearch客户端

【elasticsearch系列】SpringBoot整合elasticsearch客户端,第1张

【elasticsearch系列】SpringBoot整合elasticsearch客户端

目录
  • 文档
  • ElasticSearch Head
  • 实践
  • 踩坑点

文档

Elasticsearch: 权威指南
Java REST Client

可以跟着官网示例写demo

工欲善其事必先利其器,对于ES数据的查看,首先先安装一个谷歌浏览器的插件ElasticSearch Head,便于大家后期确认测试数据是否成功;

ElasticSearch Head

谷歌浏览器左上角存在一个“应用”标签,进入谷歌的应用商店;

搜索""安装成为扩展程序即可;然后打开,输入自己的ES服务地址,连接集群即可;

插件安装好之后,进入实践项目;

实践

1、pom.xml


            org.springframework.boot
            spring-boot-starter-web
        

        
            org.elasticsearch.client
            elasticsearch-rest-high-level-client
            7.15.0
        
        
            com.alibaba
            fastjson
            1.2.75
        

2、配置文件

server:
  port: 8096
spring:
  application:
    name: elasticsearch

elasticsearch:
  host: #{自定义服务器地址},例如127.0.0.1
  port: 9200 端口
  scheme: http

3、配置类

@Configuration
public class ElasticsearchConfig {

    @Value("${elasticsearch.host}")
    private String host;

    @Value("${elasticsearch.port}")
    private Integer port;

    @Value("${elasticsearch.scheme}")
    private String scheme;

    
    @Bean
    public RestHighLevelClient restHighLevelClient() {

        RestClientBuilder builder = RestClient.builder(
                //单机部署
                new HttpHost(host, port, scheme)
        );

        return new RestHighLevelClient(builder);
    }
}

5、工具类

@Slf4j
public class ElasticsearchUtil {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    //请求选项:设置授权等
    public static final RequestOptions COMMON_OPTIONS;

    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
        //设置授权
        //builder.addHeader("Authorization", "Bearer " + TOKEN);
        //自定义消费响应
        //builder.setHttpAsyncResponseConsumerFactory(
        //new HttpAsyncResponseConsumerFactory
        //.HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024));
        COMMON_OPTIONS = builder.build();
    }


    
    public void createIndex(ElasticsearchIndex elasticsearchIndex) throws IOException {
        if (elasticsearchIndex == null) {
            return;
        }
        IndexRequest indexRequest = new IndexRequest(elasticsearchIndex.getIndex());
        indexRequest.id(elasticsearchIndex.getId());
        //注意:json方式存入
        indexRequest.source(elasticsearchIndex.getLogContent(), XContentType.JSON);
        IndexResponse indexResponse = restHighLevelClient.index(indexRequest, COMMON_OPTIONS);
        log.info("create es index success, response:{}", indexResponse);
    }

    
    public boolean existsIndex(String index) throws IOException {
        GetRequest request = new GetRequest(index);
        boolean exists = restHighLevelClient.exists(request, COMMON_OPTIONS);
        log.info("existsIndex: " + exists);
        return exists;
    }
todo 后面关于索引、文档等各类工具类自定义补充,此处简单举例说明而已

}

6、ES实体

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class ElasticsearchIndex {
    
    private String index;

    
    private String type;

    
    private String id;

    
    private String content;

}

封装一个实体对象,统一交互ES;

7、单测

注意:此处文档内容直接封装成JSON格式,故工具类创建索引时采用JSON类型,如果需要改动,可以自定义;

public class ElasticsearchTest {
    @Autowired
    private ElasticsearchUtil elasticSearchUtil;


    @Test
    public void test() throws IOException {
        String content = "{"name":"测试"}";
        ElasticsearchIndex index = ElasticsearchIndex.builder()
                .index("test_index")
                .id(UUID.randomUUID().toString().replace("-",""))
                .logContent(content)
                .build();
        elasticSearchUtil.createIndex(index);
    }



}

通过插件查看测试索引和文档是否创建成功

踩坑点

[testIndex] ElasticsearchStatusException[Elasticsearch exception [type=invalid_index_name_exception, reason=Invalid index name [testIndex], must be lowercase]
溪源更开始入门时,定义索引名字时,按照Java规范定义驼峰格式testIndex,发现报以上错误,报错信息也是提示我们索引名字必须以小写格式,故定义索引等其他字段时可以参考MySQL数据库字段格式要求,"_"下划线连接多个字段;

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5611681.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存