Elasticsearch 7.14.x 简单入门(二)

项目地址:https://gitee.com/diannaodongshizhang/elastic-search

ElasticSearch不采用注解实现所需功能

实体类
Vehicle

public class Vehicle {
    private String id;
    private String number;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }
}

vehicle.json

{
  "properties": {
    "id": {
      "type": "keyword"
    },
    "number": {
      "type": "text"
    }
  }
}

工具类

/**
 * 读取文件输出转为String类型
 */
public class Util {
    private static final Logger Log = LoggerFactory.getLogger(Util.class);

    public static String loadAsString(final String path){
        try{
            final File resource = new ClassPathResource(path).getFile();
            return new String(Files.readAllBytes(resource.toPath()));
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

服务层

知识拓展

@PostConstruct该注解被用来修饰一个非静态的void()方法。被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。

通常我们会是在Spring框架中使用到@PostConstruct注解 该注解的方法在整个Bean初始化中的执行顺序:

Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注释的方法)

@Service
public class IndexService {
    private static final Logger LOG = LoggerFactory.getLogger(Util.class);
    private static final List<String> INDICES_TO_CREATE = List.of(Indices.VEHICLE_INDEX);
    private final RestHighLevelClient client;

    @Autowired
    public IndexService(@Qualifier("elasticsearchClient") RestHighLevelClient client) {
        this.client = client;
    }

    @PostConstruct
    public void tryToCreateIndices(){
        final String settings = Util.loadAsString("static/es-settings.json");

        for (final String indexName : INDICES_TO_CREATE){
            try {
                boolean indexExists = client
                        .indices()
                        .exists(new GetIndexRequest(indexName), RequestOptions.DEFAULT);
                if(indexExists){
                    continue;
                }
                final String mappings = Util.loadAsString("static/mapping/"+indexName+".json");
                if(settings == null || mappings == null){
                    LOG.error("Filed to create index with name '{}'",indexName);
                    continue;
                }
                final CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
                createIndexRequest.settings(settings, XContentType.JSON);
                createIndexRequest.mapping(mappings,XContentType.JSON);

                client.indices().create(createIndexRequest,RequestOptions.DEFAULT);
            }catch (final Exception e){
                LOG.error(e.getMessage(),e);
            }
        }
    }
}
@Service
public class VehicleService {
    private static final ObjectMapper MAPPER = new ObjectMapper();
    private static final Logger LOG = LoggerFactory.getLogger(VehicleService.class);
    private final RestHighLevelClient client;

    @Autowired
    public VehicleService(@Qualifier("elasticsearchClient") RestHighLevelClient client) {
        this.client = client;
    }

    public Boolean index(final Vehicle vehicle){
        try{
            final String vehicleAsString = MAPPER.writeValueAsString(vehicle);
            final IndexRequest request = new IndexRequest(Indices.VEHICLE_INDEX);
            request.id(vehicle.getId());
            request.source(vehicleAsString, XContentType.JSON);

            //响应是否正常
            final IndexResponse response = client.index(request, RequestOptions.DEFAULT);
            return response!= null && response.status().equals(RestStatus.OK);
        }catch (final Exception e){
            LOG.error(e.getMessage(),e);
            return false;
        }
    }

    public Vehicle getById(final String vehicleId){
        try{
            final GetResponse documentFields = client.get(
                    new GetRequest(Indices.VEHICLE_INDEX,vehicleId),
                    RequestOptions.DEFAULT
            );
            if (documentFields == null || documentFields.isSourceEmpty()){
                return  null;
            }
            return MAPPER.readValue(documentFields.getSourceAsString(),Vehicle.class);
        }catch (final Exception e) {
            LOG.error(e.getMessage(),e);
            return null;
        }
    }
}

@RestController
@RequestMapping("/api/vehicle")
public class VehicleController {

    private final VehicleService service;


    public VehicleController(VehicleService service) {
        this.service = service;
    }

    @PostMapping
    public void index(@RequestBody final Vehicle vehicle){
        service.index(vehicle);
    }

    @GetMapping("/{id}")
    public Vehicle getById(@PathVariable final String id){
        return service.getById(id);
    }
}

实验结果

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值