Elasticsearch 7 및 SpringBoot 통합 데이터 작업

Elasticsearch 7 및 SpringBoot 통합 데이터 작업

  • elasticsearch 데이터

  •  
     
     
     
     
     
     
     
    car
    _doc
    c8a03ab03c7c4ee1aa117b9895f5fe56

    c8a03ab03c7c4ee1aa117b9895f5fe56
    내달리다

    2020-08-27 11:03:42
    car
    _doc
    07c529bec8364734ad6a2491b4cfe43a

    07c529bec8364734ad6a2491b4cfe43a
    보마
    십일
    2020-08-27 11:04:22
    car
    _doc
    285b20319249425d96adcb600930c68d

    285b20319249425d96adcb600930c68d
    렉서스

    2020-08-27 11:03:31
    car
    _doc
    91afa37e8cb2412bad13e06bf3184c46

    91afa37e8cb2412bad13e06bf3184c46
    포드
    이십
    null
    car
    _doc
    2f9130d3df6d410199aa3737670b2255

    2f9130d3df6d410199aa3737670b2255
    니산

    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
                    
                
            
  • 자바 설정 클래스(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":" "}]

    좋은 웹페이지 즐겨찾기