首页 > 其他分享 >springboot整合es

springboot整合es

时间:2023-01-19 15:36:12浏览次数:37  
标签:springboot res springframework 整合 org put import es HashMap

pom.xml 增加依赖(注意版本要和springboot匹配)

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
            <version>2.7.5</version>
        </dependency>

 

application.yml增加配置项:

elasticsearch:
  uris: localhost:9200

 

注入整合:

package com.example.demo.config;

import lombok.Data;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
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;

@Data
@Configuration
public class ESClientConfig extends AbstractElasticsearchConfiguration {
    @Value("${elasticsearch.uris}")
    private String uris;

    @Override
    @Bean
    public RestHighLevelClient elasticsearchClient() {
        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo(uris)
                //.withBasicAuth(username, password)
                .build();
        return RestClients.create(clientConfiguration).rest();
    }
}

 

增加测试用的实体:

package com.example.demo.entity;

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

@Data
@Document(indexName = "test_users", createIndex = true)
public class User {
    @Id
    private Integer id;

    @Field(type = FieldType.Keyword)
    private String name;

    @Field(type = FieldType.Integer)
    private Integer age;

    @Field(type = FieldType.Text)
    private String desc;


    public User(Integer id, String name, Integer age, String desc){
        this.id = id;
        this.name = name;
        this.age = age;
        this.desc = desc;
    }


    public User(){

    }
}

 

写控制器测试:

package com.example.demo.controller;

import com.example.demo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
@ResponseBody
@RequestMapping(value ="/api/test")
public class TestController {
    @Autowired
    public ElasticsearchOperations elasticsearchOperations;

    @RequestMapping(value ="/index")
    public HashMap index(){
        SearchHits<User> userSearchHits = elasticsearchOperations.search(Query.findAll(), User.class);

        HashMap res = new HashMap();
        res.put("status", 0);
        res.put("code", 0);
        res.put("error", "");
        res.put("data", userSearchHits);
        return res;
    }

    @RequestMapping(value ="/save")
    public HashMap save(){
        User user = new User(1, "徐小波1", 27, "后端开发");
        elasticsearchOperations.save(user);

        HashMap res = new HashMap();
        res.put("status", 0);
        res.put("code", 0);
        res.put("error", "");
        res.put("data", "");
        return res;
    }

    @RequestMapping(value ="/update")
    public HashMap update(){
        User user = new User(1, "徐小波2", 28, "前端开发");
        elasticsearchOperations.save(user);

        HashMap res = new HashMap();
        res.put("status", 0);
        res.put("code", 0);
        res.put("error", "");
        res.put("data", "");
        return res;
    }

    @RequestMapping(value = "/get/{id}")
    public HashMap get(@PathVariable Integer id){
        User user = elasticsearchOperations.get(id.toString(), User.class);

        HashMap res = new HashMap();
        res.put("status", 0);
        res.put("code", 0);
        res.put("error", "");
        res.put("data", user);
        return res;
    }

    @RequestMapping(value = "/del/{id}")
    public HashMap del(@PathVariable Integer id){
        User user = new User();
        user.setId(1);
        String del = elasticsearchOperations.delete(user);

        HashMap res = new HashMap();
        res.put("status", 0);
        res.put("code", 0);
        res.put("error", "");
        res.put("data", del);
        return res;
    }

    @RequestMapping(value = "/delall")
    public HashMap delall(){
        elasticsearchOperations.delete(Query.findAll(), User.class);

        HashMap res = new HashMap();
        res.put("status", 0);
        res.put("code", 0);
        res.put("error", "");
        res.put("data", "");
        return res;
    }
}

 

效果:

/api/test/index

{"code":0,"data":{"totalHits":1,"totalHitsRelation":"EQUAL_TO","maxScore":1.0,"scrollId":null,"searchHits":[{"index":"test_users","id":"1","score":1.0,"sortValues":[],"content":{"id":1,"name":"徐小波1","age":27,"desc":"后端开发"},"highlightFields":{},"innerHits":{},"nestedMetaData":null,"routing":null,"explanation":null,"matchedQueries":[]}],"aggregations":null,"suggest":null,"empty":false},"error":"","status":0}

 

/api/test/get/1

{"code":0,"data":{"id":1,"name":"徐小波1","age":27,"desc":"后端开发"},"error":"","status":0}

 

标签:springboot,res,springframework,整合,org,put,import,es,HashMap
From: https://www.cnblogs.com/xuxiaobo/p/17061583.html

相关文章

  • springboot 热更 2023.3
    热更使用devtools或者alt+shit+f9ideaFile|Settings|Preferences|Build,Execution,Deployment|Compiler:BuildprojectautomaticallyFile|Setting......
  • 【网关开发】5.Openresty 自定义负载均衡与流量转发
    目录背景应用架构实现插件配置文件流量转发负载均衡器测试总结扩展ip_hashurl_hash背景静态的nginx配置需要将负载均衡的服务节点信息都配置在配置文件中。现在微服务或......
  • Python - requests 使用记录
    requests使用简单方法记录importrequestsfromfake_useragentimportUserAgentua=UserAgent()headers={'User-Agent':ua.random#伪装}#......
  • django-rest-swagger
    在日常工作中,程序员最苦恼的事情大概就是写文档了吧,虽然文档能够利于程序的传承,但是由于业务口径频繁变更,导致维护文档也变成了一件费时又费力的事情。因此,如果能够自动生......
  • AI换脸实战教学(FaceSwap的使用)---------第二步Tools:处理输入数据集。
    续上篇:https://www.cnblogs.com/techs-wenzhe/p/12936809.html第一步中已经提取出了源视频的人脸照片以及对应人脸遮罩(landmark以及其他自选遮罩)第二步:利用Tools处理提......
  • playbook 之 vars_files
    vars_files可以把var定义的变量分离出来方便修改和复用-hosts:127.0.0.1vars_files:-./var1.yamltasks:-name:debugdebug:msg:http://{{......
  • springboot 常用项目结构
    servicex//项目名|-admin-ui//管理服务前端代码(一般将UI和SERVICE放到一个工程中,便于管理)|-servicex-auth//模块1......
  • CodeForces 构造题专项解题报告(二)
    CodeForces构造题专项解题报告(二)\(\newcommand\m\mathbf\)\(\newcommand\oper\operatorname\)\(\newcommand\txt\texttt\)\(\text{ByDaiRuiChen007}\)来源:CodeF......
  • 找request的Trace文件
    select'TraceName:'||dest.value||'/'||lower(dbnm.value)||'_ora_'||oracle_process_id||'.trc','FileName:'||execname.execution_fil......
  • git_test
    项目的开发是一个不断迭代的过程,开发过程中程序员需要不断的对代码进行编写和更正。这就带来很多的问题。首先,开发中代码会存在多个版本,我们如何将代码在多个版本间进行切......