前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Springboot接入ES

Springboot接入ES

原创
作者头像
翰墨飘香
修改2023-08-17 11:25:09
3400
修改2023-08-17 11:25:09
举报
文章被收录于专栏:翰墨飘香翰墨飘香

一、mac os ES安装及入门

详细见https://cloud.tencent.com/developer/article/2312482

二、ES接入springboot

https://juejin.cn/post/6871957655553769485?searchId=2023081410462020F89520874DF2F08795

版本

推荐接入版本与ES集群版本一致,这里使用7.6.2

pom依赖

代码语言:javascript
复制
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.6.2</version>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.logging.log4j</groupId>
                    <artifactId>log4j-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

初始化config

推荐方式二 可以直接创建es的client

yaml

代码语言:javascript
复制
spring:
  elasticsearch:
    elasticUser: elastic
    elasticPassword: xxx
    elasticsearch:
      rest:
        hostNames: localhost:9200

ESconfig

代码语言:java
复制
@Configuration
public class EsConfig {

    @Value("${elasticsearch.username}")
    public String username;

    @Value("${elasticsearch.password}")
    public String password;

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

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


    @Bean(name = "restHighLevelClient")
    public RestHighLevelClient restHighLevelClient() {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username,
                password));
        // 通过builder创建rest client,配置http client的HttpClientConfigCallback。
        // 单击所创建的Elasticsearch实例ID,在基本信息页面获取公网地址,即为ES集群地址。
        RestClientBuilder builder = RestClient.builder(new HttpHost(host, port)).
                setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
                        .setDefaultCredentialsProvider(credentialsProvider));
        return new RestHighLevelClient(builder);
    }

}

三、Java API

创建索引

代码语言:java
复制
@Component
public class EsService {
    @Resource
    private RestHighLevelClient restHighLevelClient;

    public IndexResponse createIndex() throws IOException {
        IndexRequest request = new IndexRequest("user");
        request.id("1");
        Map<String, String> map = new HashMap<>();
        map.put("id", "1");
        map.put("name", "Kim");
        map.put("country", "USA");
        map.put("birthday", "19980804");
        request.source(map);
        IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        long version = indexResponse.getVersion();
        return indexResponse;
    }

}

插入数据

代码语言:java
复制
public IndexResponse insert(){
        IndexRequest request = new IndexRequest("hero").id("2")
                .source(XContentType.JSON,"id", "2", "name", "Mavis", "country", "China", "birthday", "19950809");
        try {
            IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);   //  1
            return indexResponse;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

更新数据

代码语言:java
复制
 public void update() throws IOException {
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("country", "UK");
        UpdateRequest request = new UpdateRequest("hero", "7").doc(jsonMap);
        UpdateResponse updateResponse = restHighLevelClient.update(request,  RequestOptions.DEFAULT);
    }

删除数据

代码语言:java
复制
public void deleteById() throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest("hero");
        deleteRequest.id("1");
        DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        
    }

查询数据

代码语言:java
复制
public SearchResponse getIndex(){
        SearchRequest request = new SearchRequest("hero");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(new TermQueryBuilder("country", "魏"));
        // 相当于mysql里边的limit 1;
        builder.size(1);
        request.source(builder);
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            SearchHit[] hits = response.getHits().getHits();
            return response;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、mac os ES安装及入门
  • 二、ES接入springboot
    • 版本
      • pom依赖
        • 初始化config
        • 三、Java API
          • 创建索引
            • 插入数据
              • 更新数据
                • 删除数据
                  • 查询数据
                  相关产品与服务
                  Elasticsearch Service
                  腾讯云 Elasticsearch Service(ES)是云端全托管海量数据检索分析服务,拥有高性能自研内核,集成X-Pack。ES 支持通过自治索引、存算分离、集群巡检等特性轻松管理集群,也支持免运维、自动弹性、按需使用的 Serverless 模式。使用 ES 您可以高效构建信息检索、日志分析、运维监控等服务,它独特的向量检索还可助您构建基于语义、图像的AI深度应用。
                  领券
                  问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档