Springboot接入ES

2023-08-17 11:25:09 浏览数 (1)

一、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);
        }

    }

0 人点赞