ES: spring boot中使用RestHighLevelClient

一、配置RestHighLevelClient

复制代码
package cn.edu.tju.config;

import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;

@Configuration
public class RestClientConfig extends AbstractElasticsearchConfiguration {

    @Override
    @Bean
    public RestHighLevelClient elasticsearchClient() {

        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo("xx.xx.xx.xx:9200")
                .build();

        return RestClients.create(clientConfiguration).rest();
    }
}

二、注入RestHighLevelClient,并调用相关API

复制代码
package cn.edu.tju.controller;


import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.UUID;

import static org.elasticsearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE;

@RestController
public class EsDemoController4 {
    @Autowired
    private RestHighLevelClient highLevelClient;

    @RequestMapping("/testHi")
    public String testHi() throws Exception{
        IndexRequest request = new IndexRequest("spring-data")
                .id(UUID.randomUUID().toString())
                .source(Collections.singletonMap("yesterday", "once more"))
                .setRefreshPolicy(IMMEDIATE);

        IndexResponse response = highLevelClient.index(request, RequestOptions.DEFAULT);
        return response.getResult().toString();

    }
}
相关推荐
一线大码20 分钟前
SpringBoot 和 MySQL 的事务隔离级别关系
spring boot·后端·mysql
罗政1 小时前
基于 SpringBoot + Vue 在线点餐系统(前后端分离)
vue.js·spring boot·后端
曼岛_1 小时前
[架构之美]深入优化Spring Boot WebFlux应用
spring boot·后端·架构
雨果talk1 小时前
【一文看懂Spring循环依赖】Spring循环依赖:从陷阱破局到架构涅槃
java·spring boot·后端·spring·架构
想躺平的咸鱼干1 小时前
Elasticsearch 的自动补全以及RestAPI的使用
java·后端·elasticsearch·中间件·intellij-idea
白露与泡影3 小时前
springboot + nacos + k8s 优雅停机
spring boot·后端·kubernetes
摇滚侠3 小时前
elasticSearch是什么,如何使用,有什么用
大数据·elasticsearch·搜索引擎
seventeennnnn3 小时前
Java大厂面试真题:谢飞机的技术挑战
java·spring boot·面试·aigc·技术挑战·电商场景·内容社区
翻滚吧键盘4 小时前
Package vs. Directory (包 vs. 目录)
spring boot
无名之逆4 小时前
大三自学笔记:探索Hyperlane框架的心路历程
java·开发语言·前端·spring boot·后端·rust·编程