Java Code Examples for org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder#withSort()

The following examples show how to use org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder#withSort() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ByPageTest.java    From Spring-Boot-Book with Apache License 2.0 6 votes vote down vote up
@Test
/**
 * Description: 分页查询+排序
 */
public void searchByPageAndSort() {
    // 分页:
    int page = 0;
    int size = 5;//每页文档数

    // 构建查询条件
    NativeSearchQueryBuilder nativeSearchQueryBuilderQueryBuilder = new NativeSearchQueryBuilder();
    // 查询词,只能查询一个汉字,或者一个英文单词
    nativeSearchQueryBuilderQueryBuilder.withQuery(QueryBuilders.termQuery("name", "富"));
    // 搜索,获取结果
    nativeSearchQueryBuilderQueryBuilder.withSort(SortBuilders.fieldSort("id").order(SortOrder.DESC));
    nativeSearchQueryBuilderQueryBuilder.withPageable(PageRequest.of(page, size));
    Page<Product> products = productRepository.search(nativeSearchQueryBuilderQueryBuilder.build());
    // 总条数
    for (Product product : products) {
        System.out.println(product);
    }

}
 
Example 2
Source File: ByPageTest.java    From Spring-Boot-Book with Apache License 2.0 6 votes vote down vote up
@Test
/**
 * Description: 分页查询+排序
 */
public void searchByPageAndSort() {
    // 分页:
    int page = 0;
    int size = 5;//每页文档数

    // 构建查询条件
    NativeSearchQueryBuilder nativeSearchQueryBuilderQueryBuilder = new NativeSearchQueryBuilder();
    // 查询词,只能查询一个汉字,或者一个英文单词
    nativeSearchQueryBuilderQueryBuilder.withQuery(QueryBuilders.termQuery("name", "富"));
    // 搜索,获取结果
    nativeSearchQueryBuilderQueryBuilder.withSort(SortBuilders.fieldSort("id").order(SortOrder.DESC));
    nativeSearchQueryBuilderQueryBuilder.withPageable(PageRequest.of(page, size));
    Page<Product> products = productRepository.search(nativeSearchQueryBuilderQueryBuilder.build());
    // 总条数
    for (Product product : products) {
        System.out.println(product);
    }

}
 
Example 3
Source File: SearchService.java    From leyou with Apache License 2.0 6 votes vote down vote up
/**
 * 构建基本查询条件
 *
 * @param queryBuilder
 * @param request
 */
private void searchWithPageAndSort(NativeSearchQueryBuilder queryBuilder, SearchRequest request) {
    // 准备分页参数
    int page = request.getPage();
    int size = request.getSize();

    // 1、分页
    queryBuilder.withPageable(PageRequest.of(page - 1, size));
    // 2、排序
    String sortBy = request.getSortBy();
    Boolean desc = request.getDescending();
    if (StringUtils.isNotBlank(sortBy)) {
        // 如果不为空,则进行排序
        queryBuilder.withSort(SortBuilders.fieldSort(sortBy).order(desc ? SortOrder.DESC : SortOrder.ASC));
    }
}
 
Example 4
Source File: SpringDataQueryTest.java    From code with Apache License 2.0 6 votes vote down vote up
/**
 * 排序
 */
@Test
public void searchAndSort() {
    // 构建查询条件
    NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
    // 添加基本分词查询
    queryBuilder.withQuery(QueryBuilders.termQuery("category", "手机"));
    // 排序
    queryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.ASC));
    // 搜索,获取结果
    Page<Item> items = itemRepository.search(queryBuilder.build());
    // 总条数
    long total = items.getTotalElements();
    System.out.println("总条数 = " + total);
    items.forEach(System.out::println);
}
 
Example 5
Source File: PersonRepositoryTest.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 自定义高级查询
 */
@Test
public void customAdvanceSelect() {
    // 构造查询条件
    NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
    // 添加基本的分词条件
    queryBuilder.withQuery(QueryBuilders.matchQuery("remark", "东汉"));
    // 排序条件
    queryBuilder.withSort(SortBuilders.fieldSort("age").order(SortOrder.DESC));
    // 分页条件
    queryBuilder.withPageable(PageRequest.of(0, 2));
    Page<Person> people = repo.search(queryBuilder.build());
    log.info("【people】总条数 = {}", people.getTotalElements());
    log.info("【people】总页数 = {}", people.getTotalPages());
    people.forEach(person -> log.info("【person】= {},年龄 = {}", person.getName(), person.getAge()));
}
 
Example 6
Source File: PersonRepositoryTest.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 自定义高级查询
 */
@Test
public void customAdvanceSelect() {
    // 构造查询条件
    NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
    // 添加基本的分词条件
    queryBuilder.withQuery(QueryBuilders.matchQuery("remark", "东汉"));
    // 排序条件
    queryBuilder.withSort(SortBuilders.fieldSort("age").order(SortOrder.DESC));
    // 分页条件
    queryBuilder.withPageable(PageRequest.of(0, 2));
    Page<Person> people = repo.search(queryBuilder.build());
    log.info("【people】总条数 = {}", people.getTotalElements());
    log.info("【people】总页数 = {}", people.getTotalPages());
    people.forEach(person -> log.info("【person】= {},年龄 = {}", person.getName(), person.getAge()));
}
 
Example 7
Source File: PersonRepositoryTest.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 自定义高级查询
 */
@Test
public void customAdvanceSelect() {
    // 构造查询条件
    NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
    // 添加基本的分词条件
    queryBuilder.withQuery(QueryBuilders.matchQuery("remark", "东汉"));
    // 排序条件
    queryBuilder.withSort(SortBuilders.fieldSort("age").order(SortOrder.DESC));
    // 分页条件
    queryBuilder.withPageable(PageRequest.of(0, 2));
    Page<Person> people = repo.search(queryBuilder.build());
    log.info("【people】总条数 = {}", people.getTotalElements());
    log.info("【people】总页数 = {}", people.getTotalPages());
    people.forEach(person -> log.info("【person】= {},年龄 = {}", person.getName(), person.getAge()));
}
 
Example 8
Source File: EsProductServiceImpl.java    From BigDataPlatform with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Page<EsProduct> search(String keyword, Long brandId, Long productCategoryId, Integer pageNum, Integer pageSize,Integer sort) {
    Pageable pageable = PageRequest.of(pageNum, pageSize);
    NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
    //分页
    nativeSearchQueryBuilder.withPageable(pageable);
    //过滤
    if (brandId != null || productCategoryId != null) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (brandId != null) {
            boolQueryBuilder.must(QueryBuilders.termQuery("brandId", brandId));
        }
        if (productCategoryId != null) {
            boolQueryBuilder.must(QueryBuilders.termQuery("productCategoryId", productCategoryId));
        }
        nativeSearchQueryBuilder.withFilter(boolQueryBuilder);
    }
    //搜索
    if (StringUtils.isEmpty(keyword)) {
        nativeSearchQueryBuilder.withQuery(QueryBuilders.matchAllQuery());
    } else {
        List<FunctionScoreQueryBuilder.FilterFunctionBuilder> filterFunctionBuilders = new ArrayList<>();
        filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("name", keyword),
                ScoreFunctionBuilders.weightFactorFunction(10)));
        filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("subTitle", keyword),
                ScoreFunctionBuilders.weightFactorFunction(5)));
        filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("keywords", keyword),
                ScoreFunctionBuilders.weightFactorFunction(2)));
        FunctionScoreQueryBuilder.FilterFunctionBuilder[] builders = new FunctionScoreQueryBuilder.FilterFunctionBuilder[filterFunctionBuilders.size()];
        filterFunctionBuilders.toArray(builders);
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(builders)
                .scoreMode(FunctionScoreQuery.ScoreMode.SUM)
                .setMinScore(2);
        nativeSearchQueryBuilder.withQuery(functionScoreQueryBuilder);
    }
    //排序
    if(sort==1){
        //按新品从新到旧
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("id").order(SortOrder.DESC));
    }else if(sort==2){
        //按销量从高到低
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("sale").order(SortOrder.DESC));
    }else if(sort==3){
        //按价格从低到高
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.ASC));
    }else if(sort==4){
        //按价格从高到低
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.DESC));
    }else{
        //按相关度
        nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));
    }
    nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));
    NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
    LOGGER.info("DSL:{}", searchQuery.getQuery().toString());
    return productRepository.search(searchQuery);
}
 
Example 9
Source File: EsProductServiceImpl.java    From mall-swarm with Apache License 2.0 4 votes vote down vote up
@Override
public Page<EsProduct> search(String keyword, Long brandId, Long productCategoryId, Integer pageNum, Integer pageSize,Integer sort) {
    Pageable pageable = PageRequest.of(pageNum, pageSize);
    NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
    //分页
    nativeSearchQueryBuilder.withPageable(pageable);
    //过滤
    if (brandId != null || productCategoryId != null) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (brandId != null) {
            boolQueryBuilder.must(QueryBuilders.termQuery("brandId", brandId));
        }
        if (productCategoryId != null) {
            boolQueryBuilder.must(QueryBuilders.termQuery("productCategoryId", productCategoryId));
        }
        nativeSearchQueryBuilder.withFilter(boolQueryBuilder);
    }
    //搜索
    if (StringUtils.isEmpty(keyword)) {
        nativeSearchQueryBuilder.withQuery(QueryBuilders.matchAllQuery());
    } else {
        List<FunctionScoreQueryBuilder.FilterFunctionBuilder> filterFunctionBuilders = new ArrayList<>();
        filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("name", keyword),
                ScoreFunctionBuilders.weightFactorFunction(10)));
        filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("subTitle", keyword),
                ScoreFunctionBuilders.weightFactorFunction(5)));
        filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("keywords", keyword),
                ScoreFunctionBuilders.weightFactorFunction(2)));
        FunctionScoreQueryBuilder.FilterFunctionBuilder[] builders = new FunctionScoreQueryBuilder.FilterFunctionBuilder[filterFunctionBuilders.size()];
        filterFunctionBuilders.toArray(builders);
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(builders)
                .scoreMode(FunctionScoreQuery.ScoreMode.SUM)
                .setMinScore(2);
        nativeSearchQueryBuilder.withQuery(functionScoreQueryBuilder);
    }
    //排序
    if(sort==1){
        //按新品从新到旧
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("id").order(SortOrder.DESC));
    }else if(sort==2){
        //按销量从高到低
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("sale").order(SortOrder.DESC));
    }else if(sort==3){
        //按价格从低到高
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.ASC));
    }else if(sort==4){
        //按价格从高到低
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.DESC));
    }else{
        //按相关度
        nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));
    }
    nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));
    NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
    LOGGER.info("DSL:{}", searchQuery.getQuery().toString());
    return productRepository.search(searchQuery);
}
 
Example 10
Source File: EsProductServiceImpl.java    From macrozheng with Apache License 2.0 4 votes vote down vote up
@Override
public Page<EsProduct> search(String keyword, Long brandId, Long productCategoryId, Integer pageNum, Integer pageSize,Integer sort) {
    Pageable pageable = PageRequest.of(pageNum, pageSize);
    NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
    //分页
    nativeSearchQueryBuilder.withPageable(pageable);
    //过滤
    if (brandId != null || productCategoryId != null) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (brandId != null) {
            boolQueryBuilder.must(QueryBuilders.termQuery("brandId", brandId));
        }
        if (productCategoryId != null) {
            boolQueryBuilder.must(QueryBuilders.termQuery("productCategoryId", productCategoryId));
        }
        nativeSearchQueryBuilder.withFilter(boolQueryBuilder);
    }
    //搜索
    if (StringUtils.isEmpty(keyword)) {
        nativeSearchQueryBuilder.withQuery(QueryBuilders.matchAllQuery());
    } else {
        List<FunctionScoreQueryBuilder.FilterFunctionBuilder> filterFunctionBuilders = new ArrayList<>();
        filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("name", keyword),
                ScoreFunctionBuilders.weightFactorFunction(10)));
        filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("subTitle", keyword),
                ScoreFunctionBuilders.weightFactorFunction(5)));
        filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("keywords", keyword),
                ScoreFunctionBuilders.weightFactorFunction(2)));
        FunctionScoreQueryBuilder.FilterFunctionBuilder[] builders = new FunctionScoreQueryBuilder.FilterFunctionBuilder[filterFunctionBuilders.size()];
        filterFunctionBuilders.toArray(builders);
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(builders)
                .scoreMode(FunctionScoreQuery.ScoreMode.SUM)
                .setMinScore(2);
        nativeSearchQueryBuilder.withQuery(functionScoreQueryBuilder);
    }
    //排序
    if(sort==1){
        //按新品从新到旧
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("id").order(SortOrder.DESC));
    }else if(sort==2){
        //按销量从高到低
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("sale").order(SortOrder.DESC));
    }else if(sort==3){
        //按价格从低到高
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.ASC));
    }else if(sort==4){
        //按价格从高到低
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.DESC));
    }else{
        //按相关度
        nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));
    }
    nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));
    NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
    LOGGER.info("DSL:{}", searchQuery.getQuery().toString());
    return productRepository.search(searchQuery);
}
 
Example 11
Source File: ElasticSearchUtil.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
public static NativeSearchQueryBuilder getNativeSearchQueryBuilder(final Object queryBean, QueryLogicType logicType)
    throws IllegalAccessException, NoSuchFieldException {

    if (queryBean == null) {
        return null;
    }

    QueryDocument document = queryBean.getClass().getAnnotation(QueryDocument.class);
    if (null == document) {
        throw new IllegalArgumentException("查询条件类定义必须使用 @QueryDocument 注解");
    }

    // 分页信息
    // Map<String, Field> fieldMap = ReflectUtil.getFieldMap(queryBean.getClass());
    Object currentField = ReflectUtil.getFieldValue(queryBean, "current");
    if (currentField == null) {
        throw new IllegalArgumentException("未设置 current");
    }

    Object sizeField = ReflectUtil.getFieldValue(queryBean, "size");
    if (sizeField == null) {
        throw new IllegalArgumentException("未设置 size");
    }

    long current = (long) currentField;
    long size = (long) sizeField;

    PageRequest pageRequest = PageRequest.of((int) current, (int) size);
    if (pageRequest == null) {
        throw new IllegalAccessException("获取分页信息失败");
    }
    NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
    nativeSearchQueryBuilder.withPageable(pageRequest);

    // 提取查询条件
    List<QueryBuilder> queryBuilders = getQueryBuildersByDocument(queryBean, document);
    if (CollectionUtil.isNotEmpty(queryBuilders)) {
        if (logicType == null) {
            logicType = document.logicType();
        }
        BoolQueryBuilder boolQueryBuilder = getBoolQueryBuilder(logicType, queryBuilders);
        nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
    } else {
        return null;
    }

    // 提取排序条件
    List<FieldSortBuilder> sortBuilders = ElasticSearchUtil.getSortBuildersByDocument(document);
    if (CollectionUtil.isNotEmpty(sortBuilders)) {
        for (FieldSortBuilder sortBuilder : sortBuilders) {
            nativeSearchQueryBuilder.withSort(sortBuilder);
        }
    }

    return nativeSearchQueryBuilder;
}
 
Example 12
Source File: ApiCourseBiz.java    From roncoo-education with MIT License 4 votes vote down vote up
/**
 * 课程搜索列表接口
 *
 * @param courseInfoSearchBO
 * @author wuyun
 */
public Result<Page<CourseInfoSearchPageDTO>> searchList(CourseInfoSearchBO bo) {
	if (StringUtils.isEmpty(bo.getOrgNo())) {
		return Result.error("orgNo不能为空");
	}
	if (bo.getPageCurrent() <= 0) {
		bo.setPageCurrent(1);
	}
	if (bo.getPageSize() <= 0) {
		bo.setPageSize(20);
	}

	if (StringUtils.isEmpty(bo.getCourseName())) {
		return Result.success(new Page<CourseInfoSearchPageDTO>());
	}

	String heightField = "courseName";

	Field hfield = null;
	if (bo.getIsHfield() != null && bo.getIsHfield().equals(IsHfield.YES.getCode())) {
		hfield = new HighlightBuilder.Field(heightField).preTags("<mark>").postTags("</mark>");
	}

	NativeSearchQueryBuilder nsb = new NativeSearchQueryBuilder();
	if (bo.getIsHfield() != null && bo.getIsHfield().equals(IsHfield.YES.getCode())) {
		nsb.withHighlightFields(hfield);// 高亮字段
	}
	nsb.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));// 评分排序(_source)
	nsb.withSort(new FieldSortBuilder("courseSort").order(SortOrder.DESC));// 课程排序(courseSort)
	nsb.withPageable(PageRequest.of(bo.getPageCurrent() - 1, bo.getPageSize()));
	// 复合查询,外套boolQuery
	BoolQueryBuilder qb = QueryBuilders.boolQuery();
	// 精确查询termQuery不分词,must参数等价于AND
	qb.must(QueryBuilders.termQuery("orgNo", bo.getOrgNo()));
	// 模糊查询multiMatchQuery,最佳字段best_fields
	qb.must(QueryBuilders.multiMatchQuery(bo.getCourseName(), "courseName", "lecturerName").type(MultiMatchQueryBuilder.Type.BEST_FIELDS));

	nsb.withQuery(qb);

	org.springframework.data.domain.Page<EsCourse> page = elasticsearchTemplate.queryForPage(nsb.build(), EsCourse.class, resultMapperExt);
	return Result.success(EsPageUtil.transform(page, CourseInfoSearchPageDTO.class));
}
 
Example 13
Source File: EsProductServiceImpl.java    From mall with Apache License 2.0 4 votes vote down vote up
@Override
public Page<EsProduct> search(String keyword, Long brandId, Long productCategoryId, Integer pageNum, Integer pageSize,Integer sort) {
    Pageable pageable = PageRequest.of(pageNum, pageSize);
    NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
    //分页
    nativeSearchQueryBuilder.withPageable(pageable);
    //过滤
    if (brandId != null || productCategoryId != null) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (brandId != null) {
            boolQueryBuilder.must(QueryBuilders.termQuery("brandId", brandId));
        }
        if (productCategoryId != null) {
            boolQueryBuilder.must(QueryBuilders.termQuery("productCategoryId", productCategoryId));
        }
        nativeSearchQueryBuilder.withFilter(boolQueryBuilder);
    }
    //搜索
    if (StringUtils.isEmpty(keyword)) {
        nativeSearchQueryBuilder.withQuery(QueryBuilders.matchAllQuery());
    } else {
        List<FunctionScoreQueryBuilder.FilterFunctionBuilder> filterFunctionBuilders = new ArrayList<>();
        filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("name", keyword),
                ScoreFunctionBuilders.weightFactorFunction(10)));
        filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("subTitle", keyword),
                ScoreFunctionBuilders.weightFactorFunction(5)));
        filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("keywords", keyword),
                ScoreFunctionBuilders.weightFactorFunction(2)));
        FunctionScoreQueryBuilder.FilterFunctionBuilder[] builders = new FunctionScoreQueryBuilder.FilterFunctionBuilder[filterFunctionBuilders.size()];
        filterFunctionBuilders.toArray(builders);
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(builders)
                .scoreMode(FunctionScoreQuery.ScoreMode.SUM)
                .setMinScore(2);
        nativeSearchQueryBuilder.withQuery(functionScoreQueryBuilder);
    }
    //排序
    if(sort==1){
        //按新品从新到旧
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("id").order(SortOrder.DESC));
    }else if(sort==2){
        //按销量从高到低
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("sale").order(SortOrder.DESC));
    }else if(sort==3){
        //按价格从低到高
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.ASC));
    }else if(sort==4){
        //按价格从高到低
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.DESC));
    }else{
        //按相关度
        nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));
    }
    nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));
    NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
    LOGGER.info("DSL:{}", searchQuery.getQuery().toString());
    return productRepository.search(searchQuery);
}
 
Example 14
Source File: EsProductServiceImpl.java    From macrozheng-mall with MIT License 4 votes vote down vote up
@Override
public Page<EsProduct> search(String keyword, Long brandId, Long productCategoryId, Integer pageNum, Integer pageSize,Integer sort) {
    Pageable pageable = new PageRequest(pageNum, pageSize);
    NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
    //分页
    nativeSearchQueryBuilder.withPageable(pageable);
    //过滤
    if (brandId != null || productCategoryId != null) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (brandId != null) {
            boolQueryBuilder.must(QueryBuilders.termQuery("brandId", brandId));
        }
        if (productCategoryId != null) {
            boolQueryBuilder.must(QueryBuilders.termQuery("productCategoryId", productCategoryId));
        }
        nativeSearchQueryBuilder.withFilter(boolQueryBuilder);
    }
    //搜索
    FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery()
            .add(QueryBuilders.matchQuery("name", keyword),
                    ScoreFunctionBuilders.weightFactorFunction(10))
            .add(QueryBuilders.matchQuery("subTitle", keyword),
                    ScoreFunctionBuilders.weightFactorFunction(5))
            .add(QueryBuilders.matchQuery("keywords", keyword),
                    ScoreFunctionBuilders.weightFactorFunction(2))
            .scoreMode("sum")
            .setMinScore(2);
    if (StringUtils.isEmpty(keyword)) {
        nativeSearchQueryBuilder.withQuery(QueryBuilders.matchAllQuery());
    } else {
        nativeSearchQueryBuilder.withQuery(functionScoreQueryBuilder);
    }
    //排序
    if(sort==1){
        //按新品从新到旧
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("id").order(SortOrder.DESC));
    }else if(sort==2){
        //按销量从高到低
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("sale").order(SortOrder.DESC));
    }else if(sort==3){
        //按价格从低到高
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.ASC));
    }else if(sort==4){
        //按价格从高到低
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.DESC));
    }else{
        //按相关度
        nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));
    }
    nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));
    nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));
    NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
    LOGGER.info("DSL:{}", searchQuery.getQuery().toString());
    return productRepository.search(searchQuery);
}