springboot+Elasticsearch 复杂查询
以前没做过ES 里面的查询,第一次接触还是走了点弯路的。
就是这个字段你在ES 都不用模糊查的话,就可以设置 type = FieldType.Keyword,比如ID之类的。
一:建ES存储的实体
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import javax.persistence.Id;
import java.io.Serializable;
import java.util.Date;
/**
* @ClassName: MaskCallbackES
* @Description: 未戴口罩ES实体
* @Author ***
* @Date 2022/12/07 14:01
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
//indexName名字如果是字母那么必须是小写字母
@Document(indexName = "mask_callback")
public class MaskCallbackES implements Serializable {
private static final long serialVersionUID = 4L;
@Id
@Field(store = true, type = FieldType.Keyword)
private String id;
/**
* 设备编号
*/
@Field(index = false, store = true, type = FieldType.Keyword, fielddata = true)
private String cameraId;
/**
* 算法类型
*/
@Field(index = false, store = true, type = FieldType.Keyword)
private String violateType;
/**
* 告警描述
*/
@Field(index = false, store = true, type = FieldType.Auto)
private String violateDescription;
/**
* 创建时间
*/
@Field(index = false, store = true, type = FieldType.Date)
private Date createTime;
/**
* 算法推送时间
*/
@Field(index = false, store = true, type = FieldType.Auto)
private Date time;
/**
* 未戴口罩的数量
*/
@Field(index = false, store = true, type = FieldType.Auto)
private Integer noMask;
/**
* 戴口罩的数量
*/
@Field(index = false, store = true, type = FieldType.Auto)
private Integer wearMask;
}
二: 建类似于mybatis 的 Mapper,来操作ES
import ideal4j.pfa.openapi.model.MaskCallbackES;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
* 口罩识别算法保存ES mapper
* @author: ***
* @since: V2.0.0
* @date: 2022/12/07 14:20
*/
public interface MaskCallbackESMapper extends ElasticsearchRepository<MaskCallbackES, String> {
}
三:通过mapper search实现复杂查询,查询ES中所有匹配EquipmentId集合的数据,分页+按time 倒叙,至于是keyBuilder.should,还是queryBuilder.must,参考https://blog.csdn.net/pshaoyi/article/details/118418310
List<String> collect = callbackList.stream().map(ShopVo::getEquipmentId).collect(Collectors.toList());
keyBuilder.should(QueryBuilders.termsQuery("equipmentId.keyword",collect));
queryBuilder.must(keyBuilder);
QueryBuilder qb = QueryBuilders.rangeQuery("picTime").
gte(DateUtils.parseCalendarDate(createTime,DateUtils.PATTERN_OF_DATE_TIME_EN).getTimeInMillis())
.lte(cal.getTimeInMillis());
queryBuilder.must(qb);
//这边的分页只能算是form-size的浅层分页,如果数据量大的话,建议改造成scroll深度分页
Pageable pageable = PageRequest.of(page-1, pageSize, Sort.Direction.DESC,"picTime");
Iterable<ExtCallbackStatisticsES> aIterable = extCallbackStatisticsESMapper.search(queryBuilder,pageable);
return IteratorUtils.toList(aIterable.iterator());

浙公网安备 33010602011771号