Example usage for org.apache.lucene.search Sort getSort

List of usage examples for org.apache.lucene.search Sort getSort

Introduction

In this page you can find the example usage for org.apache.lucene.search Sort getSort.

Prototype

public SortField[] getSort() 

Source Link

Document

Representation of the sort criteria.

Usage

From source file:org.infoglue.deliver.externalsearch.ExternalSearchService.java

License:Open Source License

public SearchResult search(SearchRequest params) throws SystemException {
    List<Object> result = new ArrayList<Object>();
    if (isSearchable()) {
        try {/*  w w w .  j  a  v  a  2  s .c  o m*/
            StandardAnalyzer analyzer = new StandardAnalyzer();
            Query query = params.getQuery(analyzer);

            Hits hits;
            if (params.shouldSort()) {
                Sort sort = params.getOrdering();
                if (logger.isDebugEnabled()) {
                    logger.debug("Searching with sort. Sort: " + Arrays.toString(sort.getSort()));
                }
                hits = indexSearcher.search(query, sort);
            } else {
                logger.debug("Searching without sort");
                hits = indexSearcher.search(query);
            }

            // Examine the Hits object to see if there were any matches
            int hitCount = hits.length();
            if (logger.isDebugEnabled()) {
                logger.debug("hit count: " + hitCount + " for query: " + query.toString());
            }
            if (hitCount > 0) {
                if (params.getCount() != null) {
                    hitCount = Math.min(hitCount, params.getStartIndex() + params.getCount());
                }
                for (int i = params.getStartIndex() == null ? 0 : params.getStartIndex(); i < hitCount; i++) {
                    try {
                        Document document = hits.doc(i);

                        if (logger.isDebugEnabled()) {
                            StringBuilder sb = new StringBuilder();
                            for (Object field : document.getFields()) {
                                sb.append(document.get(field.toString())).append(", ");
                            }
                            logger.debug("Search found document: " + sb);
                        }

                        byte[] resultBytes = document
                                .getBinaryValue(SearchResult.getResultLabel(params.getLanguage()));
                        if (resultBytes != null) {
                            ObjectInputStream ois = new ObjectInputStream(
                                    new ByteArrayInputStream(resultBytes));
                            Object post = ois.readObject();
                            result.add(post);
                        }
                    } catch (Exception ex) {
                        logger.warn(
                                "There was an error preparing a search hit for the result list. The item will be excluded from the list. Message: "
                                        + ex.getMessage() + ". Type: " + ex.getClass());
                    }
                }
            }
            return new SearchResult(result, hits.length());
        } catch (ParseException pex) {
            logger.warn("Invalid Lucene search query in external search service. Service.name: " + name
                    + ". Message: " + pex.getMessage());
            throw new SystemException("Invalid Lucene search query. See warning logs for more information.");
        } catch (Throwable tr) {
            logger.error("Error when searching in external search service. Service.name: " + name
                    + ". Message: " + tr.getMessage() + ". Type: " + tr.getClass());
            logger.warn("Error when updating index for external search service. Service.name: " + name, tr);
            throw new SystemException("Error in Lucene search. See warning logs for more information.");
        }
    }

    return new SearchResult(Collections.emptyList(), 0);
}

From source file:org.opencms.search.CmsSearchIndex.java

License:Open Source License

/**
 * Checks if the score for the results must be calculated based on the provided sort option.<p>  
 * //from   w w  w .j ava 2  s  . c o m
 * Since Lucene 3 apparently the score is no longer calculated by default, but only if the 
 * searcher is explicitly told so. This methods checks if, based on the given sort, 
 * the score must be calculated.<p> 
 * 
 * @param searcher the index searcher to prepare 
 * @param sort the sort option to use
 */
protected void prepareSortScoring(IndexSearcher searcher, Sort sort) {

    boolean doScoring = false;
    if (sort != null) {
        if ((sort == CmsSearchParameters.SORT_DEFAULT) || (sort == CmsSearchParameters.SORT_TITLE)) {
            // these default sorts do need score calculation
            doScoring = true;
        } else if ((sort == CmsSearchParameters.SORT_DATE_CREATED)
                || (sort == CmsSearchParameters.SORT_DATE_LASTMODIFIED)) {
            // these default sorts don't need score calculation
            doScoring = false;
        } else {
            // for all non-defaults: check if the score field is present, in that case we must calculate the score
            SortField[] fields = sort.getSort();
            for (SortField field : fields) {
                if (field == SortField.FIELD_SCORE) {
                    doScoring = true;
                    break;
                }
            }
        }
    }
    searcher.setDefaultFieldSortScoring(doScoring, doScoring);
}

From source file:org.uberfire.ext.metadata.backend.elastic.index.ElasticSearchIndexProvider.java

License:Apache License

protected Optional<SearchResponse> findByQueryRaw(List<String> indices, Query query, Sort sort, int limit) {
    try {//ww w.  j av  a2 s . c  o  m

        List<String> indexes = indices;
        if (indices.isEmpty()) {
            indexes = this.getIndices();
        }
        QueryStringQueryBuilder queryBuilder = QueryBuilders
                .queryStringQuery(escapeSpecialCharacters(query.toString()));
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(queryBuilder);
        if (sort != null) {
            Arrays.stream(sort.getSort()).filter(sortField -> sortField.getField() != null)
                    .forEach(sortField -> {
                        addSort(searchSourceBuilder, sortField);
                    });
        }
        if (limit > 0 && limit <= ELASTICSEARCH_MAX_SIZE) {
            searchSourceBuilder.size(limit);
        } else {
            searchSourceBuilder.size(ELASTICSEARCH_MAX_SIZE);
        }
        return Optional
                .of(this.getClient().prepareSearch(sanitizeIndexes(indexes).toArray(new String[indexes.size()]))
                        .setSource(searchSourceBuilder).get());
    } catch (ElasticsearchException e) {
        logger.debug(MessageFormat.format("Can't perform search: {0}", e.getMessage()));
    }
    return Optional.empty();
}

From source file:org.uberfire.ext.metadata.backend.infinispan.ickl.IckleConverter.java

License:Apache License

public String convert(Sort sort) {

    if (sort == null || sort.getSort() == null) {
        return "";
    }//from ww  w. j  ava2 s. c  o m

    List<SortField> fields = Arrays.asList(sort.getSort());

    String sortString = fields.stream().filter(sortField -> sortField.getField() != null).map(sortField -> {
        String key = this.converterImpl.convertKey(sortField.getField());
        String sortDirection = ASC;
        if (sortField.getReverse()) {
            sortDirection = DESC;
        }
        return key + " " + sortDirection;
    }).collect(Collectors.joining(","));

    return sortString;
}