springboot整合es

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}

 

posted @ 2023-01-19 15:17  河北大学-徐小波  阅读(156)  评论(0编辑  收藏  举报