第十二节 SpringBoot使用ES进行时间区间查询

亮子 2022-02-14 01:44:37 23251 0 0 0

1、添加依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>

2、修改版本

    <properties>
        <java.version>1.8</java.version>
        <elasticsearch.version>7.8.1</elasticsearch.version>
    </properties>

3、实体类

需要注意时间格式的设置。

package com.shenmazong.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.DateFormat;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

/**
 * 小说表
 * @TableName tb_story
 */
@TableName(value ="tb_story")
@Data
@Document(indexName = "tb_story", shards = 1, replicas = 1)
public class TbStory implements Serializable {
    /**
     * 小说ID
     */
    @TableId(type = IdType.AUTO)
    @Id
    private Integer id;

    /**
     * 小说名字
     */
    @Field(type = FieldType.Text, analyzer = "ik_smart")
    private String name;

    /**
     * 小说作者
     */
    @Field(type = FieldType.Keyword)
    private String author;

    /**
     * 小说内容
     */
    @Field(type = FieldType.Text, analyzer = "ik_max_word")
    private String content;

    /**
     * 点赞状态:0支持1反对
     */

    @Field(type = FieldType.Integer)
    private Integer status;

    /**
     * 软删除:0正常1删除
     */
    @Field(type = FieldType.Integer)
    private Integer deleted;

    /**
     * 创建时间
     */
    @Field(type = FieldType.Date, format = DateFormat.custom, pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
    private Date createTime;

    /**
     * 修改时间
     */
    @Field(type = FieldType.Date, format = DateFormat.custom, pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
    private Date updateTime;

    @TableField(exist = false)
    private static final long serialVersionUID = 1L;
}

4、时间区间查询

    @Test
    void testQueryRangeTime() {
        PageRequest pageable = PageRequest.of(0, 10);
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();

        RangeQueryBuilder queryBuilder = QueryBuilders.rangeQuery("createTime")
                .format("yyyy-MM-dd HH:mm:ss")
                .timeZone("GMT+8")
                .gte("2022-02-11 07:09:13").lte("2022-02-11 07:55:40")
                .includeLower(true).includeUpper(true);

        NativeSearchQuery searchQuery = builder.withPageable(pageable)
                .withQuery(queryBuilder)
                .build();

        SearchHits<TbStory> search = elasticsearchRestTemplate.search(searchQuery, TbStory.class);
        List<SearchHit<TbStory>> searchHits = search.getSearchHits();
        for (SearchHit<TbStory> searchHit : searchHits) {
            TbStory tbStory = searchHit.getContent();
            System.out.println("========================================================");
            System.out.println(tbStory);
        }
    }

5、其他区间查询

5.1、数字范围查询

//闭区间查询
QueryBuilder qb1 = QueryBuilders.rangeQuery("${fieldName}").from(${fieldValue1}).to(${fieldValue2}); 
 
//开区间查询
QueryBuilder qb1 = QueryBuilders.rangeQuery("${fieldName}").from(${fieldValue1}, false).to(${fieldValue2}, false);
 
//大于
QueryBuilder qb1 = QueryBuilders.rangeQuery("${fieldName}").gt(${fieldValue});
 
 //大于等于
QueryBuilder qb1 = QueryBuilders.rangeQuery("${fieldName}").gte(${fieldValue}); 
 
//小于
QueryBuilder qb1 = QueryBuilders.rangeQuery("${fieldName}").lt(${fieldValue}); 
 
//小于等于
QueryBuilder qb1 = QueryBuilders.rangeQuery("${fieldName}").lte(${fieldValue});

生产实例使用:

// 增加价格区间的检索条件
if (searchRequest.getMinPrice() != null) {
    queryBuilder.must(QueryBuilders.rangeQuery(avagePriceStr)
		.from(searchRequest.getMinPrice().toString()).includeLower(true)
		.includeUpper(true));
}
if (searchRequest.getMaxPrice() != null) {
    queryBuilder.must(QueryBuilders.rangeQuery(avagePriceStr)
		.to(searchRequest.getMaxPrice().add(new BigDecimal(1)).toString())
		.includeUpper(false));
}