Java Code Examples for org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder#withQuery()
The following examples show how to use
org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder#withQuery() .
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: QueryTest.java From Spring-Boot-Book with Apache License 2.0 | 6 votes |
@Test /** * Description: 多参数termsQuery */ public void termsQuery() { // 构建查询条件 NativeSearchQueryBuilder nativeSearchQueryBuilderQueryBuilder = new NativeSearchQueryBuilder(); // 查询词,只能查询一个汉字,或者一个英文单词 nativeSearchQueryBuilderQueryBuilder.withQuery(QueryBuilders.termsQuery("name", "富","帅")); // 搜索,获取结果 Page<Product> products = productRepository.search(nativeSearchQueryBuilderQueryBuilder.build()); // 总条数 for (Product product : products) { System.out.println(product); } }
Example 2
Source File: QueryTest.java From Spring-Boot-Book with Apache License 2.0 | 6 votes |
@Test /** * Description: 单个词查询 */ public void termQuery() { // 构建查询条件 NativeSearchQueryBuilder nativeSearchQueryBuilderQueryBuilder = new NativeSearchQueryBuilder(); // 查询词,只能查询一个汉字,或者一个英文单词 nativeSearchQueryBuilderQueryBuilder.withQuery(QueryBuilders.termQuery("name", "富")); // 搜索,获取结果 Page<Product> products = productRepository.search(nativeSearchQueryBuilderQueryBuilder.build()); // 总条数 for (Product product : products) { System.out.println(product); } }
Example 3
Source File: PersonRepositoryTest.java From spring-boot-demo with MIT License | 6 votes |
/** * 自定义高级查询 */ @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 4
Source File: FuzzySearchTest.java From Spring-Boot-Book with Apache License 2.0 | 6 votes |
@Test /** * Description:相似内容查询。 */ public void multiMoreLikeThisQuery() { // 查询条件 NativeSearchQueryBuilder nativeSearchQueryBuilderQueryBuilder = new NativeSearchQueryBuilder(); // 左右模糊 nativeSearchQueryBuilderQueryBuilder.withQuery(QueryBuilders.moreLikeThisQuery(new String[]{"name"}, new String[]{"红"}, null)); nativeSearchQueryBuilderQueryBuilder.withQuery(QueryBuilders.moreLikeThisQuery(new String[]{"name"}, new String[]{"红"}, null)); nativeSearchQueryBuilderQueryBuilder.withQuery(QueryBuilders.moreLikeThisQuery(new String[]{"name"}, new String[]{"红"}, null)); // 搜索,获取结果 Page<Product> products = productRepository.search(nativeSearchQueryBuilderQueryBuilder.build()); for (Product product : products) { System.out.println(product); } }
Example 5
Source File: SpringDataQueryTest.java From code with Apache License 2.0 | 5 votes |
/** * fuzzyQuery:模糊匹配 */ @Test public void testFuzzyQuery() { NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder(); builder.withQuery(QueryBuilders.fuzzyQuery("title", "小米")); Page<Item> items = this.itemRepository.search(builder.build()); items.forEach(System.out::println); }
Example 6
Source File: FuzzySearchTest.java From Spring-Boot-Book with Apache License 2.0 | 5 votes |
@Test /** * Description:相似内容查询。 */ public void moreLikeThisQuery() { // 查询条件 NativeSearchQueryBuilder nativeSearchQueryBuilderQueryBuilder = new NativeSearchQueryBuilder(); // 左右模糊 nativeSearchQueryBuilderQueryBuilder.withQuery(QueryBuilders.moreLikeThisQuery(new String[]{"name"}, new String[]{"红"}, null)); // 搜索,获取结果 Page<Product> products = productRepository.search(nativeSearchQueryBuilderQueryBuilder.build()); for (Product product : products) { System.out.println(product); } }
Example 7
Source File: SearchController.java From Spring-Boot-Book with Apache License 2.0 | 5 votes |
@GetMapping("search") public ModelAndView searchByPageAndSort(Integer start, String key) { // 分页: if (start == null) { start = 0; } int size = 2;//每页文档数 // 构建查询条件 NativeSearchQueryBuilder nativeSearchQueryBuilderQueryBuilder = new NativeSearchQueryBuilder(); // nativeSearchQueryBuilderQueryBuilder.withQuery(QueryBuilders.matchQuery("name", key)); nativeSearchQueryBuilderQueryBuilder.withQuery(QueryBuilders.multiMatchQuery(key, "name", "body")); //nativeSearchQueryBuilderQueryBuilder.withHighlightFields(new HighlightBuilder.Field("name").preTags("<span style='background-color: #FFFF00'>").postTags("</span>")); // 搜索,获取结果 // nativeSearchQueryBuilderQueryBuilder.withSort(SortBuilders.fieldSort("id").order(SortOrder.DESC)); nativeSearchQueryBuilderQueryBuilder.withPageable(PageRequest.of(start, size)); Page<Product> products = productRepository.search(nativeSearchQueryBuilderQueryBuilder.build()); // 总条数 for (Product product : products) { System.out.println(product); } ModelAndView mav = new ModelAndView("search"); mav.addObject("page", products); mav.addObject("keys", key); return mav; }
Example 8
Source File: SpringDataQueryTest.java From code with Apache License 2.0 | 5 votes |
/** * matchQuery:词条匹配,先分词然后在调用termQuery进行匹配 */ @Test public void matchQuery() { // 构建查询条件 NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder(); // match会对输入进行分词处理后再去查询,部分命中的结果也会按照评分由高到低显示出来。 queryBuilder.withQuery(QueryBuilders.matchQuery("title", "坚果R1")); // 搜索,获取结果 Page<Item> items = itemRepository.search(queryBuilder.build()); // 总条数 long total = items.getTotalElements(); System.out.println("total = " + total); items.forEach(System.out::println); }
Example 9
Source File: FuzzySearchTest.java From Spring-Boot-Book with Apache License 2.0 | 5 votes |
@Test /** * Description: 通配符查询wildcard query。 */ public void wildcardQuery2() { // 查询条件 NativeSearchQueryBuilder nativeSearchQueryBuilderQueryBuilder = new NativeSearchQueryBuilder(); nativeSearchQueryBuilderQueryBuilder.withQuery(QueryBuilders.wildcardQuery("name","金?")); // 搜索,获取结果 Page<Product> products= productRepository.search(nativeSearchQueryBuilderQueryBuilder.build()); for (Product product : products) { System.out.println(product); } }
Example 10
Source File: FuzzySearchTest.java From Spring-Boot-Book with Apache License 2.0 | 5 votes |
@Test /** * Description: 分词模糊查询。 */ public void fuzzyQuery() { // 查询条件 NativeSearchQueryBuilder nativeSearchQueryBuilderQueryBuilder = new NativeSearchQueryBuilder(); nativeSearchQueryBuilderQueryBuilder.withQuery(QueryBuilders.fuzzyQuery("name","士").fuzziness(Fuzziness.ONE)); // 搜索,获取结果 Page<Product> products= productRepository.search(nativeSearchQueryBuilderQueryBuilder.build()); for (Product product : products) { System.out.println(product); } }
Example 11
Source File: EsProductServiceImpl.java From mall with Apache License 2.0 | 5 votes |
@Override public Page<EsProduct> recommend(Long id, Integer pageNum, Integer pageSize) { Pageable pageable = PageRequest.of(pageNum, pageSize); List<EsProduct> esProductList = productDao.getAllEsProductList(id); if (esProductList.size() > 0) { EsProduct esProduct = esProductList.get(0); String keyword = esProduct.getName(); Long brandId = esProduct.getBrandId(); Long productCategoryId = esProduct.getProductCategoryId(); //根据商品标题、品牌、分类进行搜索 List<FunctionScoreQueryBuilder.FilterFunctionBuilder> filterFunctionBuilders = new ArrayList<>(); filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("name", keyword), ScoreFunctionBuilders.weightFactorFunction(8))); filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("subTitle", keyword), ScoreFunctionBuilders.weightFactorFunction(2))); filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("keywords", keyword), ScoreFunctionBuilders.weightFactorFunction(2))); filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("brandId", brandId), ScoreFunctionBuilders.weightFactorFunction(5))); filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("productCategoryId", productCategoryId), ScoreFunctionBuilders.weightFactorFunction(3))); FunctionScoreQueryBuilder.FilterFunctionBuilder[] builders = new FunctionScoreQueryBuilder.FilterFunctionBuilder[filterFunctionBuilders.size()]; filterFunctionBuilders.toArray(builders); FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(builders) .scoreMode(FunctionScoreQuery.ScoreMode.SUM) .setMinScore(2); //用于过滤掉相同的商品 BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder(); boolQueryBuilder.mustNot(QueryBuilders.termQuery("id",id)); //构建查询条件 NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder(); builder.withQuery(functionScoreQueryBuilder); builder.withFilter(boolQueryBuilder); builder.withPageable(pageable); NativeSearchQuery searchQuery = builder.build(); LOGGER.info("DSL:{}", searchQuery.getQuery().toString()); return productRepository.search(searchQuery); } return new PageImpl<>(null); }
Example 12
Source File: EsProductServiceImpl.java From macrozheng with Apache License 2.0 | 5 votes |
@Override public Page<EsProduct> recommend(Long id, Integer pageNum, Integer pageSize) { Pageable pageable = PageRequest.of(pageNum, pageSize); List<EsProduct> esProductList = productDao.getAllEsProductList(id); if (esProductList.size() > 0) { EsProduct esProduct = esProductList.get(0); String keyword = esProduct.getName(); Long brandId = esProduct.getBrandId(); Long productCategoryId = esProduct.getProductCategoryId(); //根据商品标题、品牌、分类进行搜索 List<FunctionScoreQueryBuilder.FilterFunctionBuilder> filterFunctionBuilders = new ArrayList<>(); filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("name", keyword), ScoreFunctionBuilders.weightFactorFunction(8))); filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("subTitle", keyword), ScoreFunctionBuilders.weightFactorFunction(2))); filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("keywords", keyword), ScoreFunctionBuilders.weightFactorFunction(2))); filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("brandId", brandId), ScoreFunctionBuilders.weightFactorFunction(10))); filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("productCategoryId", productCategoryId), ScoreFunctionBuilders.weightFactorFunction(6))); FunctionScoreQueryBuilder.FilterFunctionBuilder[] builders = new FunctionScoreQueryBuilder.FilterFunctionBuilder[filterFunctionBuilders.size()]; filterFunctionBuilders.toArray(builders); FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(builders) .scoreMode(FunctionScoreQuery.ScoreMode.SUM) .setMinScore(2); NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder(); builder.withQuery(functionScoreQueryBuilder); builder.withPageable(pageable); NativeSearchQuery searchQuery = builder.build(); LOGGER.info("DSL:{}", searchQuery.getQuery().toString()); return productRepository.search(searchQuery); } return new PageImpl<>(null); }
Example 13
Source File: QueryTest.java From Spring-Boot-Book with Apache License 2.0 | 5 votes |
@Test /** * Description: matchQuery分词查询,采用默认的分词器。 */ public void matchQuery() { // 查询条件 NativeSearchQueryBuilder nativeSearchQueryBuilderQueryBuilder = new NativeSearchQueryBuilder(); // 查询词 nativeSearchQueryBuilderQueryBuilder.withQuery(QueryBuilders.matchQuery("name", "红士")); // 搜索,获取结果 Page<Product> products= productRepository.search(nativeSearchQueryBuilderQueryBuilder.build()); for (Product product : products) { System.out.println(product); } }
Example 14
Source File: EsProductServiceImpl.java From mall-swarm with Apache License 2.0 | 5 votes |
@Override public EsProductRelatedInfo searchRelatedInfo(String keyword) { NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder(); //搜索条件 if(StringUtils.isEmpty(keyword)){ builder.withQuery(QueryBuilders.matchAllQuery()); }else{ builder.withQuery(QueryBuilders.multiMatchQuery(keyword,"name","subTitle","keywords")); } //聚合搜索品牌名称 builder.addAggregation(AggregationBuilders.terms("brandNames").field("brandName")); //集合搜索分类名称 builder.addAggregation(AggregationBuilders.terms("productCategoryNames").field("productCategoryName")); //聚合搜索商品属性,去除type=1的属性 AbstractAggregationBuilder aggregationBuilder = AggregationBuilders.nested("allAttrValues","attrValueList") .subAggregation(AggregationBuilders.filter("productAttrs",QueryBuilders.termQuery("attrValueList.type",1)) .subAggregation(AggregationBuilders.terms("attrIds") .field("attrValueList.productAttributeId") .subAggregation(AggregationBuilders.terms("attrValues") .field("attrValueList.value")) .subAggregation(AggregationBuilders.terms("attrNames") .field("attrValueList.name")))); builder.addAggregation(aggregationBuilder); NativeSearchQuery searchQuery = builder.build(); return elasticsearchTemplate.query(searchQuery, response -> { LOGGER.info("DSL:{}",searchQuery.getQuery().toString()); return convertProductRelatedInfo(response); }); }
Example 15
Source File: EsProductServiceImpl.java From macrozheng-mall with MIT License | 5 votes |
@Override public EsProductRelatedInfo searchRelatedInfo(String keyword) { NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder(); //搜索条件 if(StringUtils.isEmpty(keyword)){ builder.withQuery(QueryBuilders.matchAllQuery()); }else{ builder.withQuery(QueryBuilders.multiMatchQuery(keyword,"name","subTitle","keywords")); } //聚合搜索品牌名称 builder.addAggregation(AggregationBuilders.terms("brandNames").field("brandName")); //集合搜索分类名称 builder.addAggregation(AggregationBuilders.terms("productCategoryNames").field("productCategoryName")); //聚合搜索商品属性,去除type=1的属性 AbstractAggregationBuilder aggregationBuilder = AggregationBuilders.nested("allAttrValues") .path("attrValueList") .subAggregation(AggregationBuilders.filter("productAttrs") .filter(QueryBuilders.termQuery("attrValueList.type",1)) .subAggregation(AggregationBuilders.terms("attrIds") .field("attrValueList.productAttributeId") .subAggregation(AggregationBuilders.terms("attrValues") .field("attrValueList.value")) .subAggregation(AggregationBuilders.terms("attrNames") .field("attrValueList.name")))); builder.addAggregation(aggregationBuilder); NativeSearchQuery searchQuery = builder.build(); return elasticsearchTemplate.query(searchQuery, response -> { LOGGER.info("DSL:{}",searchQuery.getQuery().toString()); return convertProductRelatedInfo(response); }); }
Example 16
Source File: EsProductServiceImpl.java From macrozheng with Apache License 2.0 | 4 votes |
@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 17
Source File: SearchService.java From leyou with Apache License 2.0 | 4 votes |
/** * 搜索商品 * * @param request * @return */ public SearchResult search(SearchRequest request) { // 判断是否有搜索条件,如果没有,直接返回null。不允许搜索全部商品 if (StringUtils.isBlank(request.getKey())) { return null; } // 1、初始化自定义查询构建器 NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder(); //QueryBuilder basicQuery = QueryBuilders.matchQuery("all", request.getKey()).operator(Operator.AND); BoolQueryBuilder boolQueryBuilder = buildBooleanQueryBuilder(request); // 1.1、基本查询 //queryBuilder.withQuery(basicQuery); queryBuilder.withQuery(boolQueryBuilder); // 通过sourceFilter设置返回的结果字段,我们只需要id、subTitle、skus queryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{"id", "subTitle", "skus"}, null)); // 1.2.分页排序 // 获取分页参数 Integer page = request.getPage(); Integer size = request.getSize(); // 添加分页 queryBuilder.withPageable(PageRequest.of(page - 1, size)); // 1.3、聚合 // 聚合名称 String categoryAggName = "categories"; // 商品分类聚合名称 String brandAggName = "brands"; // 品牌聚合名称 // 对商品分类进行聚合 queryBuilder.addAggregation(AggregationBuilders.terms(categoryAggName).field("cid3")); // 对品牌进行聚合 queryBuilder.addAggregation(AggregationBuilders.terms(brandAggName).field("brandId")); // 2、查询,获取结果 AggregatedPage<Goods> goodsPage = (AggregatedPage<Goods>) this.goodsRepository.search(queryBuilder.build()); // 3、解析查询结果 // 3.1、分页信息 Long total = goodsPage.getTotalElements(); int totalPage = (total.intValue() + request.getSize() - 1) / request.getSize(); // 3.2、商品分类的聚合结果 List<Map<String, Object>> categories = getCategoryAggResult(goodsPage.getAggregation(categoryAggName)); // 3.3、品牌的聚合结果 List<Brand> brands = getBrandAggResult(goodsPage.getAggregation(brandAggName)); // 根据商品分类个数判断是否需要聚合 List<Map<String, Object>> specs = null; if (!CollectionUtils.isEmpty(categories) && categories.size() == 1) { // 如果商品分类只有一个才进行聚合,并根据分类与基本查询条件聚合 specs = getParamAggResult((Long) categories.get(0).get("id"), boolQueryBuilder); } // 返回结果 return new SearchResult(total, totalPage, goodsPage.getContent(), categories, brands, specs); }
Example 18
Source File: ElasticSearchUtil.java From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International | 4 votes |
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 19
Source File: EsProductServiceImpl.java From BigDataPlatform with GNU General Public License v3.0 | 4 votes |
@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 20
Source File: ApiCourseBiz.java From roncoo-education with MIT License | 4 votes |
/** * 课程搜索列表接口 * * @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)); }