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

    }
}
相关推荐
万亿少女的梦1683 小时前
基于SpringBoot的考研学习交流系统设计与开发
spring boot·mysql·vue·系统设计·论坛系统
利威尔·3 小时前
常用git命令
大数据·elasticsearch·搜索引擎
二宝哥6 小时前
创建Gradle多模块SpringBoot项目
java·spring boot·后端
杨运交7 小时前
[044][Web模块]基于 Google Authenticator 的 TOTP 双因素认证框架设计与实现
spring boot
二宝哥7 小时前
springboot项目使用Gradle工具实现依赖版本控制
java·spring boot·后端·gradle·版本
卓怡学长9 小时前
w273基于springboot的智能笔记的开发与应用
java·spring boot·spring·intellij-idea
say_fall9 小时前
【Git 精品详解】企业规范:企业级开发模型、Git Flow、发版流程规范、Code Owner 制度、事故应急回滚
大数据·linux·服务器·git·学习·elasticsearch
Kyrie_Li19 小时前
Spring Boot Kafka 生产级配置全解析:从入门到精通
spring boot·后端·kafka
Elastic 中国社区官方博客1 天前
跟踪资金流向:使用 ES|QL 和跨集群搜索追踪洗钱网络
大数据·人工智能·安全·elasticsearch·搜索引擎·金融·全文检索