ElasticsearchRepository条件查询+分页+排序+字段聚合

环境搭建这里就不介绍,只贴上关键的代码供大家参考!

	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
	</dependency>
涉及中英文,这里只贴出部分
package cn.sciencedb.common.domain.es;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
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;

/**
 * ElasticSearch 索引科学数据对象-英文
 * 
 * @author 张益达
 * @date 2018-08-13
 */

@Getter
@Setter
@ToString
@Document(indexName = "dataset_index_en", type = "dataset")
public class DataSetIndexEn implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    private String id;// ES 主键

    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_max_word")
    private String title;// 数据集标题

    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_max_word")
    private String introduction;// 数据集简介

    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_max_word")
    private String keyword;// 关键字

    private String author;// 数据集作者

    private String dataSetType;// 数据集类型

    private Date publishDate;// 数据集发布时间

    private String dataSetId; // 数据集id

    private String code;    //数据集标识 对应projectId

    private String taxonomy;    //学科

    private String pictureUrl; //图ong片url

    private long viewCount; //浏览数
}

controller

/**
     * 热门数据
     * @param code 数据集标识 对应projectId
     * @param dataSetType 数据集类型
     * @param locale 国际化
     * @return
     */
    @ApiOperation("热门数据")
    @GetMapping("/recommend2")
    public SdbResult recommend2(@RequestParam(name = "page", required = false, defaultValue = "0") String page,
                                @RequestParam(name = "size", required = false, defaultValue = "10") String size,
                                @RequestParam(name = "code", required = false) String code,
                                @RequestParam(name = "dataSetType", required = false) String dataSetType,
                                Locale locale) {
        // 获取分页参数
        int pageNum = Integer.parseInt(page);
        int pageSize = Integer.parseInt(size);
        Pageable pageable = PageRequest.of(pageNum, pageSize);
        return searchService.recommendData2(code, dataSetType, locale,pageable);
    }

这里是重点!!!
serviceimpl

	/**
     * 检索聚合查询,这里对taxonomy(学科分类进行聚合)
     * @param params
     * @return
     */
    @Override
    public SdbResult searchQuery(String q, String dataSetType, String taxonomy, String code, String username, boolean ordertime, boolean orderinfluence, String page, String size, Locale locale) {

        Map<String, Object> map = Maps.newHashMap();
        Pageable pageable = PageRequest.of(Integer.parseInt(page), Integer.parseInt(size));
        //检索条件
        BoolQueryBuilder bqb = QueryBuilders.boolQuery();
        if(StringUtils.isNotEmpty(dataSetType))
            bqb.must(QueryBuilders.matchPhraseQuery("dataSetType", dataSetType));
        if(StringUtils.isNotEmpty(code))
            bqb.must(QueryBuilders.matchPhraseQuery("code", code));
        if(StringUtils.isNotEmpty(taxonomy))
            bqb.must(QueryBuilders.matchPhraseQuery("taxonomy", taxonomy));
        if(StringUtils.isNotEmpty(q))
            bqb.must(QueryBuilders.multiMatchQuery(q, "title", "keyword", "introduction"));
        //排序条件
        FieldSortBuilder fsb = null;
        if(ordertime){
            fsb = SortBuilders.fieldSort("publishDate").order(SortOrder.DESC);
        }
        if(orderinfluence){
            fsb = SortBuilders.fieldSort("referenceNumber").order(SortOrder.DESC);
        }
		//聚合条件
        TermsAggregationBuilder builder1 = AggregationBuilders.terms("taxonomy").field("taxonomy.keyword");
        TermsAggregationBuilder builder2 = AggregationBuilders.terms("year").field("year.keyword");
        TermsAggregationBuilder builder = builder1.subAggregation(builder2);
        //构建查询
        SearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(bqb)
                .withSort(fsb)
                .addAggregation(builder)
                .withPageable(pageable)
                .build();
        if ("en".equals(locale.getLanguage())) {
            AggregatedPage<DataSetIndexEn> search = (AggregatedPage)sdoIndexEnRepository.search(query);
            long totalElements = search.getTotalElements();
            int totalPages = search.getTotalPages();
            List<DataSetIndexEn> content = search.getContent();
			Terms term1 = (Terms)search.getAggregations().getAsMap().get("taxonomy");
            log.debug("term1============"+term1.toString());
            for (Terms.Bucket bucket : term1.getBuckets()) {
                log.debug("一级内容"+bucket.toString());
                map.put(bucket.getKey().toString(), bucket.getDocCount());
                Terms terms_year = bucket.getAggregations().get("year");
                for (Terms.Bucket year_bucket : terms_year.getBuckets()) {
                    log.debug("二级内容"+year_bucket.toString());
                    map.put(year_bucket.getKey().toString(), year_bucket.getDocCount());
                }
            }
            map.put("total",totalElements);
            map.put("totalPages",totalPages);
            map.put("recommendData",content);
        } else {
            AggregatedPage<DataSetIndexZh> search = (AggregatedPage)sdoIndexZhRepository.search(query);
            long totalElements = search.getTotalElements();
            int totalPages = search.getTotalPages();
            List<DataSetIndexZh> content = search.getContent();
			Terms term1 = (Terms)search.getAggregations().getAsMap().get("taxonomy");
            log.debug("term1============"+term1.toString());
            for (Terms.Bucket bucket : term1.getBuckets()) {
                log.debug("一级内容"+bucket.toString());
                map.put(bucket.getKey().toString(), bucket.getDocCount());
                Terms terms_year = bucket.getAggregations().get("year");
                for (Terms.Bucket year_bucket : terms_year.getBuckets()) {
                    log.debug("二级内容"+year_bucket.toString());
                    map.put(year_bucket.getKey().toString(), year_bucket.getDocCount());
                }
            }
            map.put("total",totalElements);
            map.put("totalPages",totalPages);
            map.put("recommendData",content);
        }
        return success(map);
    }

 	/**
     * 获取最近更新数据集
     *
     * @param code
     * @param dataSetType
     * @param locale 国际化
     * @return SdbResult
     */
    @Override
    public SdbResult latestData(String code, String dataSetType, Locale locale) {
        String language = locale.getLanguage();
        Map<String, Object> map = Maps.newHashMap();
        //创建查询条件
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        if(StringUtils.isNotEmpty(code))
            builder.must(QueryBuilders.matchPhraseQuery("code", code));
        if(StringUtils.isNotEmpty(dataSetType))
            builder.must(QueryBuilders.matchPhraseQuery("dataSetType", dataSetType));

        if("en".equals(language)){
        	//使用PageRequest of进行排序
            Pageable pageable = PageRequest.of(1, 8, Sort.Direction.DESC, "publishDate");
            List<DataSetIndexEn> content = sdoIndexEnRepository.search(builder,pageable).getContent();
            map.put("latest",content);
        }else{
            Pageable pageable = PageRequest.of(0, 8, Sort.Direction.DESC, "publishDate");
            List<DataSetIndexZh> content = sdoIndexZhRepository.search(builder,pageable).getContent();
            map.put("latest",content);
        }

        return success(map);
    }

Repository

/**
 * 中文数据Repository
 * 
 * @author 张益达
 * @date 2018年8月23日
 */
@Repository
public interface DataSetZhRepository extends ElasticsearchRepository<DataSetIndexZh, String> {

    List<DataSetIndexZh> findByDataSetType(String dataSetType, Pageable pageable);

    List<DataSetIndexZh> findByCode(String code,Pageable pageable);

    List<DataSetIndexZh> findByCodeAndDataSetType(String code, String dataSetType, Pageable pageable);

    DataSetIndexZhfindByDataSetId(String dataSetId);
}

聚合结果:
在这里插入图片描述

发布了19 篇原创文章 · 获赞 10 · 访问量 2万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 精致技术 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览