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();

    }
}
相关推荐
隔壁阿布都26 分钟前
使用LangChain4j +Springboot 实现大模型与向量化数据库协同回答
人工智能·spring boot·后端
古城小栈1 小时前
Spring Boot 数据持久化:MyBatis-Plus 分库分表实战指南
spring boot·后端·mybatis
悟能不能悟1 小时前
springboot全局异常
大数据·hive·spring boot
+VX:Fegn08952 小时前
计算机毕业设计|基于springboot + vue宠物寄养系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计·宠物
一 乐3 小时前
校园实验室|基于springboot + vue校园实验室管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端
Lisonseekpan3 小时前
Spring Boot Email 邮件发送完全指南
java·spring boot·后端·log4j
sheji34163 小时前
【开题答辩全过程】以 基于Springboot的体检中心信息管理系统设计与实现为例,包含答辩的问题和答案
java·spring boot·后端
天河归来3 小时前
本地windows环境升级dify到1.11.1版本
java·spring boot·docker
甜鲸鱼3 小时前
【Spring AOP】操作日志的完整实现与原理剖析
java·spring boot·spring
一 乐4 小时前
酒店客房预订|基于springboot + vue酒店客房预订系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端