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

    }
}
相关推荐
devpotato4 小时前
Spring Boot mTLS 报 `keystore password was incorrect`:不一定是密码错了
spring boot·tls·pkcs12·mtls
Elastic 中国社区官方博客4 小时前
Elastic-caveman : 在不损失 Elastic 最佳效果的情况下,将 AI 响应 tokens 减少64%
大数据·运维·数据库·人工智能·elasticsearch·搜索引擎·全文检索
keep one's resolveY5 小时前
SpringBoot实现重试机制的四种方案
java·spring boot·后端
身如柳絮随风扬7 小时前
深度解析 Elasticsearch 搜索服务:核心原理、架构与优化实践
大数据·elasticsearch·架构
kft13147 小时前
AI 驱动测试 2.0:当测试智能体成为你的“超级 QA“
大数据·人工智能·elasticsearch
阿丰资源7 小时前
基于Spring Boot的电影城管理系统(直接运行)
java·spring boot·后端
消失的旧时光-19438 小时前
Spring Boot 工程化进阶:统一返回 + 全局异常 + AOP 通用工具包
java·spring boot·后端·aop·自定义注解
StockTV9 小时前
印度股票实时数据 NSE和BSE的实时行情、K 线及指数数据
java·开发语言·spring boot·python
橘子海全栈攻城狮10 小时前
【最新源码】养老院系统管理A013
java·spring boot·后端·web安全·微信小程序