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

    }
}
相关推荐
倒流时光三十年9 分钟前
SpringBoot 数据库同步 Elasticsearch 性能优化
数据库·spring boot·elasticsearch
码农小卡拉33 分钟前
深入解析Spring Boot文件加载顺序与加载方式
java·数据库·spring boot
Dragon Wu41 分钟前
Spring Security Oauth2.1 授权码模式实现前后端分离的方案
java·spring boot·后端·spring cloud·springboot·springcloud
人间打气筒(Ada)1 小时前
jenkins基于Pipeline发布项目
java·pipeline·jenkins·流水线·ci·cd·cicd
星辰_mya1 小时前
Elasticsearch更新了分词器之后
大数据·elasticsearch·搜索引擎
Elastic 中国社区官方博客2 小时前
Elasticsearch:Workflows 介绍 - 9.3
大数据·数据库·人工智能·elasticsearch·ai·全文检索
一 乐2 小时前
校园二手交易|基于springboot + vue校园二手交易系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端
80530单词突击赢2 小时前
SpringBoot整合SpringMVC全解析
java·spring boot·后端
vx1_Biye_Design2 小时前
基于Spring Boot+Vue的学生管理系统设计与实现-计算机毕业设计源码46223
java·vue.js·spring boot·spring·eclipse·tomcat·maven
vx_Biye_Design2 小时前
基于Spring Boot+vue的湖北旅游景点门票预约平台的设计--毕设附源码29593
java·vue.js·spring boot·spring cloud·servlet·eclipse·课程设计