spring 实现对 elasticsearch 动态索引
背景: 使用filebetat抓取程序运行日志 导致日志文件在 elasticsearch 中的 索引 按照日期每日一个索引文件 但是后台需要对这些日志 统一进行查询 则需要spring 需要实现动态查询索引
方案: 使用spring el表达式
引入包:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
定义ES 查询 Document:
package com.ruoyi.web.domain;
import lombok.Data;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import java.io.Serializable;
@Data
@Document(indexName ="test-ros-action-#{@rosLogDate.getDate()}")
public class RosSearchEs implements Serializable {
@Field
private RosMessage message;
}
定义BEAN:
package com.ruoyi.web.core.config;
import com.ruoyi.web.domain.RosLogDate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class BeanConfig {
@Bean
public RosLogDate rosLogDate(){
return new RosLogDate();
}
}
查询实现:
rosLogDate.setDate("2022-05-20");
QueryBuilder provinceItemsQuery = QueryBuilders.matchPhraseQuery("message.type","inventory");
NativeSearchQueryBuilder builder=new NativeSearchQueryBuilder();
NativeSearchQuery query=builder.withQuery(provinceItemsQuery).withPageable(Pageable.ofSize(10))
.build();
SearchHits<RosSearchEs> search = elasticsearchRestTemplate.search(query, RosSearchEs.class);