原理:根据条件查询参数主文档信息。然后sort的时候,查询复合条件的子文档的最大max最小min等值来排序。
GET wk_bbs_index/_search { "post_filter": { "bool": { "adjust_pure_negative": true, "must": [ { "term": { "baseInfo.cityAlias": { "boost": 1, "value": "sz" } } } ], "boost": 1 } }, "query": { "bool": { "adjust_pure_negative": true, "must": [ { "term": { "isDisable": { "boost": 1, "value": "0" } } }, { "nested": { "path": "bbsSubjectEsVos", "score_mode": "none", "query": { "term": { "bbsSubjectEsVos.subjectId": { "boost": 1, "value": "3021723" } } }, "boost": 1, "ignore_unmapped": false } } ], "boost": 1 } }, "sort": [ { "bbsSubjectEsVos.order": { "nested": { "filter": { "term": { "bbsSubjectEsVos.subjectId": { "boost": 1, "value": "3021723" } } }, "path": "bbsSubjectEsVos" }, "order": "desc" } }, { "bbsSalePriceEsVo.price": { "order": "asc" } } ], "_source": [ "pkId", "name", "bbsSalePriceEsVo.price", "bbsSubjectEsVos.subjectId", "bbsSubjectEsVos.order" ] }
需求:嵌套排序,根据主题排序号越大排序越前,然后根据价格排序
/** * 加载查询条件 * @param searchVO * @return */ public void initQuerySubjectbbsListBuilder(NativeSearchQueryBuilder queryBuilder, SubJectVO searchVO) { // 复合查询 BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); {// 数据必须有效 TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("isDisable", ContantsEnums.DISABLE_0.getIndex()); boolQueryBuilder.must(termQueryBuilder); } // 主题相关 // String fkIdLocationSt; TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("bbsSubjectEsVos.subjectId", searchVO.getSubjectId()); NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("bbsSubjectEsVos", termQueryBuilder, ScoreMode.None); boolQueryBuilder.must(nestedQueryBuilder); // 查询条件 queryBuilder.withQuery(boolQueryBuilder); // 范围查询 } /** * @desc 设置分页、排序 * @date 2020年4月3日 上午10:06:18 * @param queryBuilder 查询对象 * @param searchReq 查询参数 */ public void initQuerySubjectbbsListSort(NativeSearchQueryBuilder queryBuilder, SubJectVO searchVo) { // 加载分页信息 Pageable pageable =this.initPageTable(searchVo.getPn(), searchVo.getPs(), 0, 15); queryBuilder.withPageable(pageable); // 根据序号倒序 NestedSortBuilder nestedSort = new NestedSortBuilder("bbsSubjectEsVos"); // 嵌套查询排序,是在上面查询的结果中抽取数据排序,所以无需使用NestedQueryBuilder TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("bbsSubjectEsVos.subjectId", searchVo.getSubjectId()); nestedSort.setFilter(termQueryBuilder); SortBuilder<?> sortBuilderOrder = SortBuilders.fieldSort("bbsSubjectEsVos.order").order( SortOrder.DESC).setNestedSort(nestedSort); queryBuilder.withSort(sortBuilderOrder); // 价格顺序 SortBuilder<?> sortBuilderPrice = SortBuilders.fieldSort("bbsSalePriceEsVo.price").order( SortOrder.ASC); queryBuilder.withSort(sortBuilderPrice); }
生成的代码查询语句。