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.hbasene.index.search.HBaseIndexSearcher.java

License:Apache License

@Override
public TopFieldDocs search(Weight weight, Filter filter, final int nDocs, Sort sort, boolean fillFields)
        throws IOException {
    SortField[] fields = sort.getSort();
    return (fields.length == 1 && fields[0] == SortField.FIELD_SCORE)
            ? super.search(weight, filter, nDocs, sort, fillFields)
            : doSearch(weight, filter, nDocs, sort, fillFields);

}

From source file:org.hbasene.index.search.HBaseTopFieldCollector.java

License:Apache License

public HBaseTopFieldCollector(final HTablePool tablePool, final String indexName, final int nDocs,
        final Sort sort) {
    this.tablePool = tablePool;
    this.indexName = indexName;
    this.nDocs = nDocs;
    this.fields = sort.getSort();
    this.pendingDocs = 0;
    this.totalHits = 0;
    this.pq = new PriorityQueue<SortFieldDoc>(nDocs,
            this.fields[0].getReverse() ? DESCENDING_COMPARATOR : ASCENDING_COMPARATOR);

    if (fields.length > 1) {
        throw new IllegalArgumentException("Multiple fields not supported yet ");
    }/*from www .  j a v a  2s . c om*/
}

From source file:org.hibernate.hql.lucene.test.ClassBasedLuceneQueryParsingTest.java

License:Open Source License

@Test
public void shouldBuildOneFieldSort() {
    LuceneQueryParsingResult parsingResult = parseQuery(
            "select e from IndexedEntity e where e.name = 'same' order by e.title");
    Sort sort = parsingResult.getSort();
    assertThat(sort).isNotNull();//from w ww . j  a  v a  2  s .  com
    assertThat(sort.getSort().length).isEqualTo(1);
    assertThat(sort.getSort()[0].getField()).isEqualTo("title");
    assertThat(sort.getSort()[0].getReverse()).isEqualTo(false);
    assertThat(sort.getSort()[0].getType()).isEqualTo(SortField.Type.STRING);
}

From source file:org.hibernate.hql.lucene.test.ClassBasedLuceneQueryParsingTest.java

License:Open Source License

@Test
public void shouldBuildTwoFieldsSort() {
    LuceneQueryParsingResult parsingResult = parseQuery(
            "select e from IndexedEntity e where e.name = 'same' order by e.title, e.position DESC");
    Sort sort = parsingResult.getSort();
    assertThat(sort).isNotNull();/*w w  w  . ja v  a 2  s  . c o  m*/
    assertThat(sort.getSort().length).isEqualTo(2);
    assertThat(sort.getSort()[0].getField()).isEqualTo("title");
    assertThat(sort.getSort()[0].getReverse()).isEqualTo(false);
    assertThat(sort.getSort()[0].getType()).isEqualTo(SortField.Type.STRING);
    assertThat(sort.getSort()[1].getField()).isEqualTo("position");
    assertThat(sort.getSort()[1].getReverse()).isEqualTo(true);
    assertThat(sort.getSort()[1].getType()).isEqualTo(SortField.Type.LONG);
}

From source file:org.hibernate.hql.lucene.test.UntypedLuceneQueryParsingTest.java

License:Open Source License

@Test
public void shouldBuildSortForNullEncoding() {
    LuceneQueryParsingResult parsingResult = parseQuery("select e from IndexedEntity e order by e.code DESC");
    Sort sort = parsingResult.getSort();
    assertThat(sort).isNotNull();// www .  j  av  a 2 s . c o m
    assertThat(sort.getSort().length).isEqualTo(1);
    assertThat(sort.getSort()[0].getField()).isEqualTo("code");
    assertThat(sort.getSort()[0].getType()).isEqualTo(SortField.Type.LONG);
}

From source file:org.hibernate.search.reader.impl.ManagedMultiReader.java

License:LGPL

/**
 * Gets the readers to be effectively used. A given reader will be returned itself if:
 * <ul>//ww w.  j av a  2s  . c  om
 * <li>there is no sort involved.</li>
 * <li>doc value fields for all requested sort fields are contained in the index, for each entity type mapped to the
 * index</li>
 * </ul>
 * Otherwise the directory reader will be wrapped in a {@link UninvertingReader} configured in a way to satisfy the
 * requested sorts.
 */
private static IndexReader[] getEffectiveReaders(IndexManager[] indexManagers, IndexReader[] subReaders,
        SortConfigurations configuredSorts, Sort sort, boolean indexUninvertingAllowed) {
    if (sort == null || sort.getSort().length == 0) {
        return subReaders;
    }

    Set<String> indexesToBeUninverted = getIndexesToBeUninverted(configuredSorts, sort,
            indexUninvertingAllowed);
    Map<String, Type> mappings = indexesToBeUninverted.isEmpty() ? Collections.<String, Type>emptyMap()
            : getMappings(sort);
    IndexReader[] effectiveReaders = new IndexReader[subReaders.length];

    int i = 0;
    for (IndexReader reader : subReaders) {
        // take incoming reader as is
        if (!indexesToBeUninverted.contains(indexManagers[i].getIndexName())) {
            effectiveReaders[i] = reader;
        }
        // wrap with uninverting reader
        else {
            if (reader instanceof DirectoryReader) {
                DirectoryReader directoryReader = (DirectoryReader) reader;

                try {
                    effectiveReaders[i] = UninvertingReader.wrap(directoryReader, mappings);
                } catch (IOException e) {
                    throw log.couldNotCreateUninvertingReader(directoryReader, e);
                }
            } else {
                log.readerTypeUnsupportedForInverting(reader.getClass());
                effectiveReaders[i] = reader;
            }
        }

        i++;
    }

    return effectiveReaders;
}

From source file:org.hibernate.search.reader.impl.ManagedMultiReader.java

License:LGPL

/**
 * Checks for each involved entity type whether it maps all the required sortable fields; If not, it marks the index
 * for uninverting./*  w  ww .  j av a 2 s . c  o  m*/
 */
private static Set<String> getIndexesToBeUninverted(SortConfigurations configuredSorts, Sort sort,
        boolean indexUninvertingAllowed) {
    Set<String> indexesToBeUninverted = new HashSet<>();

    for (SortConfiguration sortConfiguration : configuredSorts) {
        boolean foundEntityWithAllRequiredSorts = false;
        boolean foundEntityWithMissingSorts = false;

        for (Class<?> entityType : sortConfiguration.getEntityTypes()) {
            List<String> uncoveredSorts = sortConfiguration.getUncoveredSorts(entityType, sort);

            if (!uncoveredSorts.isEmpty()) {
                indexesToBeUninverted.add(sortConfiguration.getIndexName());

                if (indexUninvertingAllowed) {
                    log.uncoveredSortsRequested(entityType, sortConfiguration.getIndexName(),
                            StringHelper.join(uncoveredSorts, ", "));
                } else {
                    throw log.uncoveredSortsRequestedWithUninvertingNotAllowed(entityType,
                            sortConfiguration.getIndexName(), StringHelper.join(uncoveredSorts, ", "));
                }

                foundEntityWithMissingSorts = true;
            } else {
                foundEntityWithAllRequiredSorts = true;
            }
        }

        if (foundEntityWithAllRequiredSorts && foundEntityWithMissingSorts) {
            throw log.inconsistentSortableFieldConfigurationForSharedIndex(sortConfiguration.getIndexName(),
                    StringHelper.join(sort.getSort(), ", "));
        }
    }

    return indexesToBeUninverted;
}

From source file:org.hibernate.search.reader.impl.ManagedMultiReader.java

License:LGPL

/**
 * Returns the uninverting reader mappings required for the given non-null sort.
 *///from   ww w .  j ava2s .co m
private static Map<String, UninvertingReader.Type> getMappings(Sort sort) {
    Map<String, UninvertingReader.Type> mappings = new HashMap<>();

    for (SortField sortField : sort.getSort()) {
        if (sortField.getField() != null) {
            switch (sortField.getType()) {
            case INT:
                mappings.put(sortField.getField(), Type.INTEGER);
                break;
            case LONG:
                mappings.put(sortField.getField(), Type.LONG);
                break;
            case FLOAT:
                mappings.put(sortField.getField(), Type.FLOAT);
                break;
            case DOUBLE:
                mappings.put(sortField.getField(), Type.DOUBLE);
                break;
            case STRING:
            case STRING_VAL:
                mappings.put(sortField.getField(), Type.SORTED);
                break;
            case BYTES:
                mappings.put(sortField.getField(), Type.BINARY);
                break;
            case CUSTOM: // Nothing to do; expecting doc value fields created by the user
                break;
            default:
                log.sortFieldTypeUnsupported(sortField.getField(), sortField.getType());
            }
        }
    }

    return mappings;
}

From source file:org.hippoecm.repository.FacetedNavigationEngineImpl.java

License:Apache License

public Result doView(String queryName, QueryImpl initialQuery, ContextImpl contextImpl,
        List<KeyValue<String, String>> facetsQueryList, List<FacetRange> rangeQuery, QueryImpl openQuery,
        Map<String, Map<String, Count>> resultset, Map<String, String> inheritedFilter,
        HitsRequested hitsRequested) throws UnsupportedOperationException, IllegalArgumentException {
    NamespaceMappings nsMappings = getNamespaceMappings();

    IndexReader indexReader = null;//from   w ww.j a  va 2 s .co m
    try {
        indexReader = getIndexReader(false);

        IndexSearcher searcher = new IndexSearcher(indexReader);
        SetDocIdSetBuilder matchingDocsSetBuilder = new SetDocIdSetBuilder();

        BooleanQuery facetsQuery = new FacetsQuery(facetsQueryList, nsMappings).getQuery();
        matchingDocsSetBuilder.add(filterDocIdSetPlainLuceneQuery(facetsQuery, indexReader));

        BooleanQuery facetRangeQuery = new FacetRangeQuery(rangeQuery, nsMappings, this).getQuery();
        matchingDocsSetBuilder.add(filterDocIdSetPlainLuceneQuery(facetRangeQuery, indexReader));

        BooleanQuery inheritedFilterQuery = new InheritedFilterQuery(inheritedFilter, nsMappings).getQuery();
        matchingDocsSetBuilder.add(filterDocIdSetPlainLuceneQuery(inheritedFilterQuery, indexReader));

        org.apache.lucene.search.Query initialLuceneQuery = null;
        if (initialQuery != null && initialQuery.scopes != null && initialQuery.scopes.length > 0) {
            if (initialQuery.scopes.length == 1) {
                initialLuceneQuery = new TermQuery(
                        new Term(ServicingFieldNames.HIPPO_PATH, initialQuery.scopes[0]));
            } else {
                initialLuceneQuery = new BooleanQuery(true);
                for (String scope : initialQuery.scopes) {
                    ((BooleanQuery) initialLuceneQuery)
                            .add(new TermQuery(new Term(ServicingFieldNames.HIPPO_PATH, scope)), Occur.SHOULD);
                }
            }
        }
        matchingDocsSetBuilder.add(filterDocIdSetPlainLuceneQuery(initialLuceneQuery, indexReader));

        FacetFiltersQuery facetFiltersQuery = null;
        if (initialQuery != null && initialQuery.facetFilters != null) {
            facetFiltersQuery = new FacetFiltersQuery(initialQuery.facetFilters, nsMappings,
                    this.getTextAnalyzer(), this.getSynonymProvider());
        }

        final BooleanQuery authorizationQuery = contextImpl.getAuthorizationQuery();
        if (authorizationQuery != null) {
            final DocIdSet authorisationIdSet = contextImpl.getAuthorisationIdSet(indexReader);
            if (authorisationIdSet != null) {
                matchingDocsSetBuilder.add(authorisationIdSet);
            }
        }

        if (resultset != null) {
            // If there are more than one facet in the 'resultset' we return an empty result as this is not allowed
            if (resultset.size() > 1) {
                log.error("The resultset cannot contain multiple facets");
                return new ResultImpl(0, null);
            }

            int cardinality = 0;
            for (String namespacedFacet : resultset.keySet()) {

                // Not a search involving scoring, thus compute bitsets for facetFiltersQuery & freeSearchInjectedSort
                if (facetFiltersQuery != null) {
                    if (facetFiltersQuery.isPlainLuceneQuery()) {
                        matchingDocsSetBuilder
                                .add(filterDocIdSetPlainLuceneQuery(facetFiltersQuery.getQuery(), indexReader));
                    } else {
                        matchingDocsSetBuilder
                                .add(filterDocIdSetJackRabbitQuery(facetFiltersQuery.getQuery(), indexReader));
                    }
                }

                if (openQuery != null) {
                    QueryAndSort queryAndSort = openQuery.getLuceneQueryAndSort(contextImpl);
                    // open query is always a jackrabbit query
                    matchingDocsSetBuilder.add(filterDocIdSetJackRabbitQuery(queryAndSort.query, indexReader));
                }

                OpenBitSet matchingDocs = matchingDocsSetBuilder.toBitSet();
                cardinality = (int) matchingDocs.cardinality();
                /*
                 * Nodes not having this facet, still should be counted if they are a hit
                 * in the query without this facet. Therefor, first get the count query without
                 * FacetPropExistsQuery.
                 */
                int numHits = 0;
                if (hitsRequested.isFixedDrillPath()) {
                    // only in the case of the fixed drillpath we use the count where the facet does not need to exist
                    numHits = (int) matchingDocs.cardinality();
                }

                ParsedFacet parsedFacet;
                try {
                    parsedFacet = ParsedFacet.getInstance(namespacedFacet);
                } catch (Exception e) {
                    log.error("Error parsing facet: ", e);
                    return new ResultImpl(0, null);
                }

                String propertyName = ServicingNameFormat.getInteralPropertyPathName(nsMappings,
                        parsedFacet.getNamespacedProperty());

                /*
                 * facetPropExists: the node must have the property as facet
                 */

                matchingDocsSetBuilder.add(filterDocIdSetPlainLuceneQuery(
                        new FacetPropExistsQuery(propertyName).getQuery(), indexReader));

                matchingDocs = matchingDocsSetBuilder.toBitSet();
                cardinality = (int) matchingDocs.cardinality();
                // this method populates the facetValueCountMap for the current facet

                // index reader is instance of JackrabbitIndexReader : we need the wrapped multi-index reader as
                // cache key : since during deletes only, the backing index reader can stay the same, we
                // also need to use numDocs to be sure we get the right cached values
                Object[] keyObjects = { matchingDocs, propertyName, parsedFacet, indexReader.getCoreCacheKey(),
                        indexReader.numDocs() };
                FVCKey fvcKey = new FVCKey(keyObjects);

                Map<String, Count> facetValueCountMap = facetValueCountCache.getIfPresent(fvcKey);
                if (facetValueCountMap == null) {
                    facetValueCountMap = new HashMap<String, Count>();
                    populateFacetValueCountMap(propertyName, parsedFacet, facetValueCountMap, matchingDocs,
                            indexReader);
                    facetValueCountCache.put(fvcKey, facetValueCountMap);
                    log.debug("Caching new facet value count map");
                } else {
                    log.debug("Reusing previously cached facet value count map");
                }

                Map<String, Count> resultFacetValueCountMap = resultset.get(namespacedFacet);
                resultFacetValueCountMap.putAll(facetValueCountMap);

                // set the numHits value
                if (hitsRequested.isFixedDrillPath()) {
                    return new ResultImpl(numHits, null);
                }
            }

            return new ResultImpl(cardinality, null);

        } else {
            // resultset is null, so search for HippoNodeType.HIPPO_RESULTSET
            if (!hitsRequested.isResultRequested()) {
                // No search with SCORING involved, this everything can be done with BitSet's
                if (facetFiltersQuery != null && facetFiltersQuery.getQuery().clauses().size() > 0) {
                    matchingDocsSetBuilder
                            .add(filterDocIdSetPlainLuceneQuery(facetFiltersQuery.getQuery(), indexReader));
                }

                if (openQuery != null) {
                    QueryAndSort queryAndSort = openQuery.getLuceneQueryAndSort(contextImpl);
                    matchingDocsSetBuilder.add(filterDocIdSetJackRabbitQuery(queryAndSort.query, indexReader));
                }

                int size = (int) matchingDocsSetBuilder.toBitSet().cardinality();
                return new ResultImpl(size, null);

            } else {

                BooleanQuery searchQuery = new BooleanQuery(false);
                Sort freeSearchInjectedSort = null;
                if (facetFiltersQuery != null && facetFiltersQuery.getQuery().clauses().size() > 0) {
                    searchQuery.add(facetFiltersQuery.getQuery(), Occur.MUST);
                }

                if (openQuery != null) {
                    QueryAndSort queryAndSort = openQuery.getLuceneQueryAndSort(contextImpl);
                    if (queryAndSort.query != null) {
                        searchQuery.add(queryAndSort.query, Occur.MUST);
                    }
                    freeSearchInjectedSort = queryAndSort.sort;
                }

                Set<String> fieldNames = new HashSet<String>();
                fieldNames.add(FieldNames.UUID);
                FieldSelector fieldSelector = new SetBasedFieldSelector(fieldNames, new HashSet<String>());

                int fetchTotal = hitsRequested.getOffset() + hitsRequested.getLimit();
                Sort sort = null;
                if (freeSearchInjectedSort != null) {
                    // we already have a sort from the xpath or sql free search. Use this one
                    sort = freeSearchInjectedSort;
                } else if (hitsRequested.getOrderByList().size() > 0) {
                    List<Path> orderPropertiesList = new ArrayList<Path>();
                    List<Boolean> ascSpecsList = new ArrayList<Boolean>();
                    for (OrderBy orderBy : hitsRequested.getOrderByList()) {
                        try {
                            Name orderByProp = NameFactoryImpl.getInstance().create(orderBy.getName());
                            boolean isAscending = !orderBy.isDescending();
                            orderPropertiesList.add(createPath(orderByProp));
                            ascSpecsList.add(isAscending);
                        } catch (IllegalArgumentException e) {
                            log.warn("Skip property '{}' because cannot create a Name for it: {}",
                                    orderBy.getName(), e.toString());
                        }
                    }
                    if (orderPropertiesList.size() > 0) {
                        Path[] orderProperties = orderPropertiesList
                                .toArray(new Path[orderPropertiesList.size()]);
                        boolean[] ascSpecs = new boolean[ascSpecsList.size()];
                        int i = 0;
                        for (Boolean b : ascSpecsList) {
                            ascSpecs[i] = b;
                            i++;
                        }
                        sort = new Sort(createSortFields(orderProperties, ascSpecs,
                                new String[orderProperties.length]));
                    }
                }

                boolean sortScoreAscending = false;
                // if the sort is on score descending, we can set it to null as this is the default and more efficient                  
                if (sort != null && sort.getSort().length == 1
                        && sort.getSort()[0].getType() == SortField.SCORE) {

                    if (sort.getSort()[0].getReverse()) {
                        sortScoreAscending = true;
                    } else {
                        // we can skip sort as it is on score descending
                        sort = null;
                    }
                }

                TopDocs tfDocs;
                org.apache.lucene.search.Query query = searchQuery;
                if (searchQuery.clauses().size() == 0) {
                    // add a match all query
                    // searchQuery.add(new MatchAllDocsQuery(), Occur.MUST);
                    query = new MatchAllDocsQuery();
                }

                if (sort == null) {
                    // when sort == null, use this search without search as is more efficient
                    Filter filterToApply = new DocIdSetFilter(matchingDocsSetBuilder.toBitSet());
                    tfDocs = searcher.search(query, filterToApply, fetchTotal);
                } else {
                    if (sortScoreAscending) {
                        // we need the entire searchQuery because scoring is involved
                        Filter filterToApply = new DocIdSetFilter(matchingDocsSetBuilder.toBitSet());
                        tfDocs = searcher.search(query, filterToApply, fetchTotal, sort);
                    } else {
                        // because we have at least one explicit sort, scoring can be skipped. We can use cached bitsets combined with a match all query
                        if (facetFiltersQuery != null) {
                            matchingDocsSetBuilder.add(
                                    filterDocIdSetPlainLuceneQuery(facetFiltersQuery.getQuery(), indexReader));
                        }
                        if (openQuery != null) {
                            QueryAndSort queryAndSort = openQuery.getLuceneQueryAndSort(contextImpl);
                            matchingDocsSetBuilder
                                    .add(filterDocIdSetJackRabbitQuery(queryAndSort.query, indexReader));
                        }

                        Filter filterToApply = new DocIdSetFilter(matchingDocsSetBuilder.toBitSet());
                        // set query to MatchAllDocsQuery because we have everything as filter now
                        query = new MatchAllDocsQuery();
                        tfDocs = searcher.search(query, filterToApply, fetchTotal, sort);
                    }

                }

                ScoreDoc[] hits = tfDocs.scoreDocs;
                int position = hitsRequested.getOffset();

                // LinkedHashSet because ordering should be kept!
                Set<NodeId> nodeIdHits = new LinkedHashSet<NodeId>();
                while (position < hits.length) {
                    Document d = indexReader.document(hits[position].doc, fieldSelector);
                    Field uuidField = d.getField(FieldNames.UUID);
                    if (uuidField != null) {
                        nodeIdHits.add(NodeId.valueOf(uuidField.stringValue()));
                    }
                    position++;
                }
                return new ResultImpl(nodeIdHits.size(), nodeIdHits);
            }
        }

    } catch (IllegalNameException e) {
        log.error("Error during creating view: ", e);
    } catch (IOException e) {
        log.error("Error during creating view: ", e);
    } finally {

        if (indexReader != null) {
            try {
                // do not call indexReader.close() as ref counting is taken care of by  
                // org.apache.jackrabbit.core.query.lucene.Util#closeOrRelease
                Util.closeOrRelease(indexReader);
            } catch (IOException e) {
                log.error("Exception while closing index reader", e);
            }
        }
    }
    return new ResultImpl(0, null);
}

From source file:org.hippoecm.repository.query.lucene.HippoIndexSearcher.java

License:Apache License

@Override
public QueryHits evaluate(Query query, final Sort sort, final long resultFetchHint) throws IOException {
    query = query.rewrite(reader);//w  ww  .j  ava  2 s  . c om
    QueryHits hits = null;
    if (query instanceof JackrabbitQuery) {
        hits = ((JackrabbitQuery) query).execute(this, getSession(), sort);
    }
    if (hits == null) {
        boolean noSort = sort.getSort().length == 0;
        if (noSort && authorizationFilter == null) {
            hits = new LuceneQueryHits(reader, this, query);
        } else if (noSort) {
            hits = new HippoLuceneQueryHits(reader, authorizationFilter, this, query);
        } else {
            hits = new HippoSortedLuceneQueryHits(reader, authorizationFilter, this, query, sort,
                    resultFetchHint);
        }
    }
    return hits;
}