org.elasticsearch.search.sort.ScoreSortBuilder Java Examples

The following examples show how to use org.elasticsearch.search.sort.ScoreSortBuilder. 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: PercolateSourceBuilder.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Similar as {@link #setTrackScores(boolean)}, but whether to sort by the score descending.
 */
public PercolateSourceBuilder setSort(boolean sort) {
    if (sort) {
        addSort(new ScoreSortBuilder());
    } else {
        this.sorts = null;
    }
    return this;
}
 
Example #2
Source File: PostServiceImpl.java    From SENS with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Page<Post> findPostsByEs(Map<String, Object> criteria, Page<Post> page) {

    //search request
    SearchRequest searchRequest = new SearchRequest("blog");

    //search builder
    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

    BoolQueryBuilder booleanQueryBuilder = QueryBuilders.boolQuery();
    for (String key : criteria.keySet()) {
        booleanQueryBuilder.must(QueryBuilders.matchQuery(key, criteria.get(key)));
    }

    sourceBuilder.query(booleanQueryBuilder);
    sourceBuilder.from(Integer.parseInt(String.valueOf((page.getCurrent() - 1) * page.getSize())));
    sourceBuilder.size(Integer.parseInt(String.valueOf(page.getSize())));
    sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

    //sort
    sourceBuilder.sort(new ScoreSortBuilder().order(SortOrder.DESC));

    //highlight
    HighlightBuilder highlightBuilder = new HighlightBuilder();
    HighlightBuilder.Field highlightTitle = new HighlightBuilder.Field("postTitle");
    highlightTitle.preTags("<span class=\"highlight\">");
    highlightTitle.postTags("</span>");
    highlightBuilder.field(highlightTitle);
    sourceBuilder.highlighter(highlightBuilder);

    // add builder into request
    searchRequest.indices("blog");
    searchRequest.source(sourceBuilder);

    //response
    SearchResponse searchResponse = null;
    List<Post> postList = new ArrayList<>();
    try {
        searchResponse = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //search hits
        SearchHits hits = searchResponse.getHits();
        long totalHits = hits.getTotalHits();

        SearchHit[] searchHits = hits.getHits();
        page.setTotal((int) totalHits);
        for (SearchHit hit : searchHits) {
            String str = hit.getSourceAsString();
            Post esPost = JSONObject.parseObject(str, Post.class);
            //高亮
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField highlight = highlightFields.get("postTitle");
            if (highlight != null) {
                Text[] fragments = highlight.fragments();
                String fragmentString = fragments[0].string();
                esPost.setPostTitle(fragmentString);
            }
            postList.add(esPost);
        }
    } catch (Exception e) {
        e.printStackTrace();
        log.error("ES未开启: {}", e);
    }
    return page.setRecords(postList);
}
 
Example #3
Source File: EsUtil.java    From java-study with Apache License 2.0 4 votes vote down vote up
/**
 * @return boolean
 * @Author pancm
 * @Description 根据条件查询
 * @Date 2019/3/21
 * @Param []
 **/
public static List<Map<String, Object>> query(String index, String type, EsQueryCondition esQueryCondition, QueryBuilder... queryBuilders) throws IOException {
    if (index == null || type == null) {
        return null;
    }
    List<Map<String, Object>> list = new ArrayList<>();
    try {
        // 查询指定的索引库
        SearchRequest searchRequest = new SearchRequest(index);
        searchRequest.types(type);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        if (esQueryCondition != null) {
            Integer form = esQueryCondition.getIndex();
            Integer pagesize = esQueryCondition.getPagesize();
            if (form != null && form > 0 && pagesize != null && pagesize > 0) {
                form = (form - 1) * pagesize;
                pagesize = form + pagesize;
                // 设置起止和结束
                sourceBuilder.from(form);
                sourceBuilder.size(pagesize);
            }
            String routing = esQueryCondition.getRouting();
            if (routing != null && routing.length() > 0) {
                // 设置路由
                searchRequest.routing(routing);
            }

            // 设置索引库表达式
            searchRequest.indicesOptions(IndicesOptions.lenientExpandOpen());

            //设置排序
            String order = esQueryCondition.getOrder();
            if (order != null) {
                String[] orderField = esQueryCondition.getOrderField();
                SortOrder order2 = order.equals(SortOrder.DESC) ? SortOrder.DESC : SortOrder.ASC;
                //如果设置了排序字段则用排序的字段进行排序,否则就默认排序
                if (orderField != null) {
                    for (String field : orderField) {
                        sourceBuilder.sort(new FieldSortBuilder(field).order(order2));
                    }
                } else {
                    sourceBuilder.sort(new ScoreSortBuilder().order(order2));
                }
            }
            String[] includeFields = esQueryCondition.getIncludeFields();
            String[] excludeFields = esQueryCondition.getExcludeFields();
            if (includeFields != null && includeFields.length > 0 && excludeFields != null && excludeFields.length > 0) {
                sourceBuilder.fetchSource(includeFields, excludeFields);
            }
            sourceBuilder.fetchSource(esQueryCondition.isCloseSource());
        }
        //设置条件
        if (queryBuilders != null) {
            for (QueryBuilder queryBuilder : queryBuilders) {
                sourceBuilder.query(queryBuilder);
            }
        }

        searchRequest.source(sourceBuilder);
        // 同步查询
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        if(queryBuilders != null|| (esQueryCondition != null && esQueryCondition.isQueryData())){
            // 结果
            searchResponse.getHits().forEach(hit -> {
                Map<String, Object> map = hit.getSourceAsMap();
                list.add(map);
            });
        }

          if(esQueryCondition != null && esQueryCondition.isNeedTotal()){
              Map<String, Object> mapTotal = new HashMap<>();
              mapTotal.put("total", searchResponse.getHits().getTotalHits());
              list.add(mapTotal);
          }

    } finally {
        if (isAutoClose) {
            close();
        }
    }
    return list;
}