Elasticsearch 7 与 SpringBoot整合实现数据操作

Elasticsearch 7 与 SpringBoot整合实现数据操作

  • elasticsearch 数据
               

car

_doc

c8a03ab03c7c4ee1aa117b9895f5fe56

1

c8a03ab03c7c4ee1aa117b9895f5fe56

奔驰

3

2020-08-27 11:03:42

car

_doc

07c529bec8364734ad6a2491b4cfe43a

1

07c529bec8364734ad6a2491b4cfe43a

宝马

11

2020-08-27 11:04:22

car

_doc

285b20319249425d96adcb600930c68d

1

285b20319249425d96adcb600930c68d

雷克萨斯

1

2020-08-27 11:03:31

car

_doc

91afa37e8cb2412bad13e06bf3184c46

1

91afa37e8cb2412bad13e06bf3184c46

福特

20

null

car

_doc

2f9130d3df6d410199aa3737670b2255

1

2f9130d3df6d410199aa3737670b2255

尼桑

8

2020-08-27 10:52:09

  • maven依赖
    
        org.springframework.boot
        spring-boot-starter-parent
        2.2.2.RELEASE
         
    

    
        1.8
        UTF-8
        UTF-8

        
        3.9
        1.2.62
    

    
 
        
            org.springframework.boot
            spring-boot-starter
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-data-elasticsearch
        
        
            org.projectlombok
            lombok
            true
        
        
        
            org.apache.commons
            commons-lang3
            ${lang3.version}
        
        
            com.alibaba
            fastjson
            ${json.version}
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
            
                
                    org.junit.vintage
                    junit-vintage-engine
                
            
        
  • java配置类(不需要在yml中做配置)
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticSearch {

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials( AuthScope.ANY,
                new UsernamePasswordCredentials("elastic", ""));//es账号密码(默认用户名为elastic)
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http"))
                        .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                                httpClientBuilder.disableAuthCaching();
                                return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                            }
                        }));
        return client;
    }
}
  •  entity注解
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
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;

import java.io.Serializable;
import java.util.Date;

@Data
@NoArgsConstructor
@Accessors(chain = true)
@Document( indexName = "car",type = "_doc",shards = 5,replicas = 0)//指定索引、类型、分片数、缓存数
public class Car implements Serializable {

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

    @Field(type = FieldType.Text)
    private String name;
    @Field(type = FieldType.Integer)
    private Integer age;
    @Field(type = FieldType.Date)
    @JsonFormat(shape = JsonFormat.Shape.STRING,pattern = "yyyy-MM-dd HH:mm:ss")
    private Date date;

    public Car(String id, String name, Integer age, Date date) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.date = date;
    }
}
  • 持久层
import com.ll.elasticsearch.domain.Car;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;


@Repository
public interface CarRepository extends ElasticsearchRepository {

    Iterable findAllByNameIsLikeOrAgeBefore(String name,Integer age);
}
  •  业务层
public interface CarService {

    List findAll();

    Car saveOrUpdate(Car car);

    String delete(String id);

    Car get (String id);
}

 

import com.ll.elasticsearch.domain.Car;
import com.ll.elasticsearch.repository.CarRepository;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class CarServiceImpl implements CarService{

    @Autowired
    private CarRepository repository;

    @Override
    public List findAll() {
        Iterable all = repository.findAll();
        Iterator it = all.iterator();
        ArrayList cars = new ArrayList<>();
        while (it.hasNext())
            cars.add(it.next());
        return cars;
    }

    @Override
    public Car saveOrUpdate(Car car) {
        if (StringUtils.isBlank(car.getId())){
            car.setId(UUID.randomUUID().toString().replace("-",""));
            car.setDate(new Date());
            return this.repository.save(car);
        }else {
            Car c = this.get(car.getId());
            this.repository.deleteById(car.getId());
            car.setDate(c.getDate());
            return this.repository.save(car);
        }
    }

    @Override
    public String delete(String id) {
        Car car = this.get(id);
        if (null != car && StringUtils.isNotBlank(car.getId())){
            this.repository.delete(car);
            return car.getId();
        }
        return null;
    }

    @Override
    public Car get(String id) {
        return this.repository.findById(id).orElse(new Car());
    }
}
  • 控制层
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ll.elasticsearch.domain.Car;
import com.ll.elasticsearch.service.CarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/car")
public class CarController {

    @Autowired
    private CarService service;

    @GetMapping("/all")
    public String all(){
        List all = service.findAll();
        JSONArray cars = new JSONArray();
        cars.addAll(all);
        return cars.toJSONString();
    }

    @GetMapping("/get")
    public String get(
            @RequestParam (defaultValue = "") String id
    ){
        Car car = service.get(id);
        JSONObject object = new JSONObject();
        object.put("data",car);
        return object.toJSONString();
    }

    @PostMapping("/saveOrUpdate")
    public String saveOrUpdate(
            @RequestParam (required = false) String id,
            @RequestParam (required = false) String name,
            @RequestParam (required = false) Integer age
    ){
        Car car = new Car(id, name, age, null);
        car = service.saveOrUpdate(car);
        JSONObject object = new JSONObject();
        object.put("data",car);
        return object.toJSONString();
    }

    @PostMapping("/delete")
    public String delete(
            @RequestParam  String id
    ){
        String deleteId = service.delete(id);
        JSONObject object = new JSONObject();
        object.put("data",deleteId);
        return object.toJSONString();
    }
  • 测试数据 /car/all
[{"age":3,"date":1598526222000,"id":"c8a03ab03c7c4ee1aa117b9895f5fe56","name":"奔驰"},{"age":11,"date":1598526262000,"id":"07c529bec8364734ad6a2491b4cfe43a","name":"宝马"},{"age":1,"date":1598526211000,"id":"285b20319249425d96adcb600930c68d","name":"雷克萨斯"},{"age":20,"id":"91afa37e8cb2412bad13e06bf3184c46","name":"福特"},{"age":8,"date":1598525529000,"id":"2f9130d3df6d410199aa3737670b2255","name":"尼桑"}]

 

你可能感兴趣的:(ElasticSearch,SpringBoot,elasticsearch)