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.apache.solr.search.SortSpec.java

License:Apache License

public static boolean includesScore(Sort sort) {
    if (sort == null)
        return true;
    for (SortField sf : sort.getSort()) {
        if (sf.getType() == SortField.Type.SCORE)
            return true;
    }/*from  w  w  w . j a  v  a2 s. co m*/
    return false;
}

From source file:org.apache.solr.search.SortSpecParsingTest.java

License:Apache License

@Test
public void testSort() throws Exception {
    Sort sort;
    SortSpec spec;//  w  w w .  ja  va 2 s.  c om
    SolrQueryRequest req = req();

    sort = doParseSortSpec("score desc", req).getSort();
    assertNull("sort", sort);//only 1 thing in the list, no Sort specified

    spec = doParseSortSpec("score desc", req);
    assertNotNull("spec", spec);
    assertNull(spec.getSort());
    assertNotNull(spec.getSchemaFields());
    assertEquals(0, spec.getSchemaFields().size());

    // SOLR-4458 - using different case variations of asc and desc
    sort = doParseSortSpec("score aSc", req).getSort();
    SortField[] flds = sort.getSort();
    assertEquals(flds[0].getType(), SortField.Type.SCORE);
    assertTrue(flds[0].getReverse());

    spec = doParseSortSpec("score aSc", req);
    flds = spec.getSort().getSort();
    assertEquals(1, flds.length);
    assertEquals(flds[0].getType(), SortField.Type.SCORE);
    assertTrue(flds[0].getReverse());
    assertEquals(1, spec.getSchemaFields().size());
    assertNull(spec.getSchemaFields().get(0));

    sort = doParseSortSpec("weight dEsC", req).getSort();
    flds = sort.getSort();
    assertEquals(flds[0].getType(), SortField.Type.FLOAT);
    assertEquals(flds[0].getField(), "weight");
    assertEquals(flds[0].getReverse(), true);

    spec = doParseSortSpec("weight dEsC", req);
    flds = spec.getSort().getSort();
    assertEquals(1, flds.length);
    assertEquals(flds[0].getType(), SortField.Type.FLOAT);
    assertEquals(flds[0].getField(), "weight");
    assertEquals(flds[0].getReverse(), true);
    assertEquals(1, spec.getSchemaFields().size());
    assertNotNull(spec.getSchemaFields().get(0));
    assertEquals("weight", spec.getSchemaFields().get(0).getName());

    sort = doParseSortSpec("weight desc,bday ASC", req).getSort();
    flds = sort.getSort();
    assertEquals(flds[0].getType(), SortField.Type.FLOAT);
    assertEquals(flds[0].getField(), "weight");
    assertEquals(flds[0].getReverse(), true);
    assertEquals(flds[1].getType(), SortField.Type.LONG);
    assertEquals(flds[1].getField(), "bday");
    assertEquals(flds[1].getReverse(), false);
    //order aliases
    sort = doParseSortSpec("weight top,bday asc", req).getSort();
    flds = sort.getSort();
    assertEquals(flds[0].getType(), SortField.Type.FLOAT);
    assertEquals(flds[0].getField(), "weight");
    assertEquals(flds[0].getReverse(), true);
    assertEquals(flds[1].getType(), SortField.Type.LONG);
    assertEquals(flds[1].getField(), "bday");
    assertEquals(flds[1].getReverse(), false);
    sort = doParseSortSpec("weight top,bday bottom", req).getSort();
    flds = sort.getSort();
    assertEquals(flds[0].getType(), SortField.Type.FLOAT);
    assertEquals(flds[0].getField(), "weight");
    assertEquals(flds[0].getReverse(), true);
    assertEquals(flds[1].getType(), SortField.Type.LONG);
    assertEquals(flds[1].getField(), "bday");
    assertEquals(flds[1].getReverse(), false);

    //test weird spacing
    sort = doParseSortSpec("weight         DESC,            bday         asc", req).getSort();
    flds = sort.getSort();
    assertEquals(flds[0].getType(), SortField.Type.FLOAT);
    assertEquals(flds[0].getField(), "weight");
    assertEquals(flds[1].getField(), "bday");
    assertEquals(flds[1].getType(), SortField.Type.LONG);
    //handles trailing commas
    sort = doParseSortSpec("weight desc,", req).getSort();
    flds = sort.getSort();
    assertEquals(flds[0].getType(), SortField.Type.FLOAT);
    assertEquals(flds[0].getField(), "weight");

    //test functions
    sort = SortSpecParsing.parseSortSpec("pow(weight, 2) desc", req).getSort();
    flds = sort.getSort();
    assertEquals(flds[0].getType(), SortField.Type.REWRITEABLE);
    //Not thrilled about the fragility of string matching here, but...
    //the value sources get wrapped, so the out field is different than the input
    assertEquals(flds[0].getField(), "pow(float(weight),const(2))");

    //test functions (more deep)
    sort = SortSpecParsing.parseSortSpec("sum(product(r_f1,sum(d_f1,t_f1,1.0)),a_f1) asc", req).getSort();
    flds = sort.getSort();
    assertEquals(flds[0].getType(), SortField.Type.REWRITEABLE);
    assertEquals(flds[0].getField(),
            "sum(product(float(r_f1),sum(float(d_f1),float(t_f1),const(1.0))),float(a_f1))");

    sort = SortSpecParsing.parseSortSpec("pow(weight,                 2.0)         desc", req).getSort();
    flds = sort.getSort();
    assertEquals(flds[0].getType(), SortField.Type.REWRITEABLE);
    //Not thrilled about the fragility of string matching here, but...
    //the value sources get wrapped, so the out field is different than the input
    assertEquals(flds[0].getField(), "pow(float(weight),const(2.0))");

    spec = SortSpecParsing.parseSortSpec("pow(weight, 2.0) desc, weight    desc,   bday    asc", req);
    flds = spec.getSort().getSort();
    List<SchemaField> schemaFlds = spec.getSchemaFields();
    assertEquals(3, flds.length);
    assertEquals(3, schemaFlds.size());

    assertEquals(flds[0].getType(), SortField.Type.REWRITEABLE);
    //Not thrilled about the fragility of string matching here, but...
    //the value sources get wrapped, so the out field is different than the input
    assertEquals(flds[0].getField(), "pow(float(weight),const(2.0))");
    assertNull(schemaFlds.get(0));

    assertEquals(flds[1].getType(), SortField.Type.FLOAT);
    assertEquals(flds[1].getField(), "weight");
    assertNotNull(schemaFlds.get(1));
    assertEquals("weight", schemaFlds.get(1).getName());

    assertEquals(flds[2].getField(), "bday");
    assertEquals(flds[2].getType(), SortField.Type.LONG);
    assertNotNull(schemaFlds.get(2));
    assertEquals("bday", schemaFlds.get(2).getName());

    //handles trailing commas
    sort = doParseSortSpec("weight desc,", req).getSort();
    flds = sort.getSort();
    assertEquals(flds[0].getType(), SortField.Type.FLOAT);
    assertEquals(flds[0].getField(), "weight");

    //Test literals in functions
    sort = SortSpecParsing.parseSortSpec("strdist(foo_s1, \"junk\", jw) desc", req).getSort();
    flds = sort.getSort();
    assertEquals(flds[0].getType(), SortField.Type.REWRITEABLE);
    //the value sources get wrapped, so the out field is different than the input
    assertEquals(flds[0].getField(),
            "strdist(str(foo_s1),literal(junk), dist=org.apache.lucene.search.spell.JaroWinklerDistance)");

    sort = doParseSortSpec("", req).getSort();
    assertNull(sort);

    spec = doParseSortSpec("", req);
    assertNotNull(spec);
    assertNull(spec.getSort());

    req.close();
}

From source file:org.codelibs.elasticsearch.search.sort.SortAndFormats.java

License:Apache License

public SortAndFormats(Sort sort, DocValueFormat[] formats) {
    if (sort.getSort().length != formats.length) {
        throw new IllegalArgumentException(
                "Number of sort field mismatch: " + sort.getSort().length + " != " + formats.length);
    }//from ww  w. j  a v a 2 s .co m
    this.sort = sort;
    this.formats = formats;
}

From source file:org.elasticsearch.action.search.SearchPhaseController.java

License:Apache License

/**
 * Returns a score doc array of top N search docs across all shards, followed by top suggest docs for each
 * named completion suggestion across all shards. If more than one named completion suggestion is specified in the
 * request, the suggest docs for a named suggestion are ordered by the suggestion name.
 *
 * Note: The order of the sorted score docs depends on the shard index in the result array if the merge process needs to disambiguate
 * the result. In oder to obtain stable results the shard index (index of the result in the result array) must be the same.
 *
 * @param ignoreFrom Whether to ignore the from and sort all hits in each shard result.
 *                   Enabled only for scroll search, because that only retrieves hits of length 'size' in the query phase.
 * @param resultsArr Shard result holder
 *///  w  w  w.  java  2s. co  m
public ScoreDoc[] sortDocs(boolean ignoreFrom, AtomicArray<? extends QuerySearchResultProvider> resultsArr)
        throws IOException {
    List<? extends AtomicArray.Entry<? extends QuerySearchResultProvider>> results = resultsArr.asList();
    if (results.isEmpty()) {
        return EMPTY_DOCS;
    }

    final QuerySearchResult result;
    boolean canOptimize = false;
    int shardIndex = -1;
    if (results.size() == 1) {
        canOptimize = true;
        result = results.get(0).value.queryResult();
        shardIndex = results.get(0).index;
    } else {
        boolean hasResult = false;
        QuerySearchResult resultToOptimize = null;
        // lets see if we only got hits from a single shard, if so, we can optimize...
        for (AtomicArray.Entry<? extends QuerySearchResultProvider> entry : results) {
            if (entry.value.queryResult().hasHits()) {
                if (hasResult) { // we already have one, can't really optimize
                    canOptimize = false;
                    break;
                }
                canOptimize = true;
                hasResult = true;
                resultToOptimize = entry.value.queryResult();
                shardIndex = entry.index;
            }
        }
        result = canOptimize ? resultToOptimize : results.get(0).value.queryResult();
        assert result != null;
    }
    if (canOptimize) {
        int offset = result.from();
        if (ignoreFrom) {
            offset = 0;
        }
        ScoreDoc[] scoreDocs = result.topDocs().scoreDocs;
        ScoreDoc[] docs;
        int numSuggestDocs = 0;
        final Suggest suggest = result.queryResult().suggest();
        final List<CompletionSuggestion> completionSuggestions;
        if (suggest != null) {
            completionSuggestions = suggest.filter(CompletionSuggestion.class);
            for (CompletionSuggestion suggestion : completionSuggestions) {
                numSuggestDocs += suggestion.getOptions().size();
            }
        } else {
            completionSuggestions = Collections.emptyList();
        }
        int docsOffset = 0;
        if (scoreDocs.length == 0 || scoreDocs.length < offset) {
            docs = new ScoreDoc[numSuggestDocs];
        } else {
            int resultDocsSize = result.size();
            if ((scoreDocs.length - offset) < resultDocsSize) {
                resultDocsSize = scoreDocs.length - offset;
            }
            docs = new ScoreDoc[resultDocsSize + numSuggestDocs];
            for (int i = 0; i < resultDocsSize; i++) {
                ScoreDoc scoreDoc = scoreDocs[offset + i];
                scoreDoc.shardIndex = shardIndex;
                docs[i] = scoreDoc;
                docsOffset++;
            }
        }
        for (CompletionSuggestion suggestion : completionSuggestions) {
            for (CompletionSuggestion.Entry.Option option : suggestion.getOptions()) {
                ScoreDoc doc = option.getDoc();
                doc.shardIndex = shardIndex;
                docs[docsOffset++] = doc;
            }
        }
        return docs;
    }

    final int topN = result.queryResult().size();
    final int from = ignoreFrom ? 0 : result.queryResult().from();

    final TopDocs mergedTopDocs;
    final int numShards = resultsArr.length();
    if (result.queryResult().topDocs() instanceof CollapseTopFieldDocs) {
        CollapseTopFieldDocs firstTopDocs = (CollapseTopFieldDocs) result.queryResult().topDocs();
        final Sort sort = new Sort(firstTopDocs.fields);
        final CollapseTopFieldDocs[] shardTopDocs = new CollapseTopFieldDocs[numShards];
        fillTopDocs(shardTopDocs, results, new CollapseTopFieldDocs(firstTopDocs.field, 0, new FieldDoc[0],
                sort.getSort(), new Object[0], Float.NaN));
        mergedTopDocs = CollapseTopFieldDocs.merge(sort, from, topN, shardTopDocs);
    } else if (result.queryResult().topDocs() instanceof TopFieldDocs) {
        TopFieldDocs firstTopDocs = (TopFieldDocs) result.queryResult().topDocs();
        final Sort sort = new Sort(firstTopDocs.fields);
        final TopFieldDocs[] shardTopDocs = new TopFieldDocs[resultsArr.length()];
        fillTopDocs(shardTopDocs, results, new TopFieldDocs(0, new FieldDoc[0], sort.getSort(), Float.NaN));
        mergedTopDocs = TopDocs.merge(sort, from, topN, shardTopDocs, true);
    } else {
        final TopDocs[] shardTopDocs = new TopDocs[resultsArr.length()];
        fillTopDocs(shardTopDocs, results, Lucene.EMPTY_TOP_DOCS);
        mergedTopDocs = TopDocs.merge(from, topN, shardTopDocs, true);
    }

    ScoreDoc[] scoreDocs = mergedTopDocs.scoreDocs;
    final Map<String, List<Suggestion<CompletionSuggestion.Entry>>> groupedCompletionSuggestions = new HashMap<>();
    // group suggestions and assign shard index
    for (AtomicArray.Entry<? extends QuerySearchResultProvider> sortedResult : results) {
        Suggest shardSuggest = sortedResult.value.queryResult().suggest();
        if (shardSuggest != null) {
            for (CompletionSuggestion suggestion : shardSuggest.filter(CompletionSuggestion.class)) {
                suggestion.setShardIndex(sortedResult.index);
                List<Suggestion<CompletionSuggestion.Entry>> suggestions = groupedCompletionSuggestions
                        .computeIfAbsent(suggestion.getName(), s -> new ArrayList<>());
                suggestions.add(suggestion);
            }
        }
    }
    if (groupedCompletionSuggestions.isEmpty() == false) {
        int numSuggestDocs = 0;
        List<Suggestion<? extends Entry<? extends Entry.Option>>> completionSuggestions = new ArrayList<>(
                groupedCompletionSuggestions.size());
        for (List<Suggestion<CompletionSuggestion.Entry>> groupedSuggestions : groupedCompletionSuggestions
                .values()) {
            final CompletionSuggestion completionSuggestion = CompletionSuggestion.reduceTo(groupedSuggestions);
            assert completionSuggestion != null;
            numSuggestDocs += completionSuggestion.getOptions().size();
            completionSuggestions.add(completionSuggestion);
        }
        scoreDocs = new ScoreDoc[mergedTopDocs.scoreDocs.length + numSuggestDocs];
        System.arraycopy(mergedTopDocs.scoreDocs, 0, scoreDocs, 0, mergedTopDocs.scoreDocs.length);
        int offset = mergedTopDocs.scoreDocs.length;
        Suggest suggestions = new Suggest(completionSuggestions);
        for (CompletionSuggestion completionSuggestion : suggestions.filter(CompletionSuggestion.class)) {
            for (CompletionSuggestion.Entry.Option option : completionSuggestion.getOptions()) {
                scoreDocs[offset++] = option.getDoc();
            }
        }
    }
    return scoreDocs;
}

From source file:org.elasticsearch.search.aggregations.bucket.composite.CompositeAggregationBuilder.java

License:Apache License

@Override
protected AggregatorFactory<?> doBuild(SearchContext context, AggregatorFactory<?> parent,
        AggregatorFactories.Builder subfactoriesBuilder) throws IOException {
    if (parent != null) {
        throw new IllegalArgumentException("[composite] aggregation cannot be used with a parent aggregation");
    }//from  www.  j  a  v  a  2s. com
    final QueryShardContext shardContext = context.getQueryShardContext();
    CompositeValuesSourceConfig[] configs = new CompositeValuesSourceConfig[sources.size()];
    SortField[] sortFields = new SortField[configs.length];
    IndexSortConfig indexSortConfig = shardContext.getIndexSettings().getIndexSortConfig();
    if (indexSortConfig.hasIndexSort()) {
        Sort sort = indexSortConfig.buildIndexSort(shardContext::fieldMapper, shardContext::getForField);
        System.arraycopy(sort.getSort(), 0, sortFields, 0, sortFields.length);
    }
    List<String> sourceNames = new ArrayList<>();
    for (int i = 0; i < configs.length; i++) {
        configs[i] = sources.get(i).build(context, i, configs.length, sortFields[i]);
        sourceNames.add(sources.get(i).name());
        if (configs[i].valuesSource().needsScores()) {
            throw new IllegalArgumentException("[sources] cannot access _score");
        }
    }
    final CompositeKey afterKey;
    if (after != null) {
        if (after.size() != sources.size()) {
            throw new IllegalArgumentException(
                    "[after] has " + after.size() + " value(s) but [sources] has " + sources.size());
        }
        Comparable<?>[] values = new Comparable<?>[sources.size()];
        for (int i = 0; i < sources.size(); i++) {
            String sourceName = sources.get(i).name();
            if (after.containsKey(sourceName) == false) {
                throw new IllegalArgumentException("Missing value for [after." + sources.get(i).name() + "]");
            }
            Object obj = after.get(sourceName);
            if (obj instanceof Comparable) {
                values[i] = (Comparable<?>) obj;
            } else {
                throw new IllegalArgumentException(
                        "Invalid value for [after." + sources.get(i).name() + "], expected comparable, got ["
                                + (obj == null ? "null" : obj.getClass().getSimpleName()) + "]");
            }
        }
        afterKey = new CompositeKey(values);
    } else {
        afterKey = null;
    }
    return new CompositeAggregationFactory(name, context, parent, subfactoriesBuilder, metaData, size, configs,
            sourceNames, afterKey);
}

From source file:org.eurekastreams.server.service.actions.strategies.directory.SortFieldBuilderTest.java

License:Apache License

/**
 * Test getSort() by date added, ascending.
 *//*from  w w  w.j  a va  2s  .  c  om*/
@Test
public void testGetSortByDateAdded() {
    List<ResourceSortCriterion> sortCrit = new ArrayList<ResourceSortCriterion>();
    sortCrit.add(new ResourceSortCriterion(SortField.DATE_ADDED, SortDirection.ASCENDING));
    ResourceSortCriteria criteria = new ResourceSortCriteria(sortCrit);

    Sort sort = sut.getSort(criteria);
    assertEquals(1, sort.getSort().length);
    assertEquals("dateAdded", sort.getSort()[0].getField());
    assertEquals(false, sort.getSort()[0].getReverse());
}

From source file:org.eurekastreams.server.service.actions.strategies.directory.SortFieldBuilderTest.java

License:Apache License

/**
 * Test getSort() by date added, descending.
 *//*from  w ww  . j  a v  a2s  . c o  m*/
@Test
public void testGetSortByDateAddedDescending() {
    List<ResourceSortCriterion> sortCrit = new ArrayList<ResourceSortCriterion>();
    sortCrit.add(new ResourceSortCriterion(SortField.DATE_ADDED, SortDirection.DESCENDING));
    ResourceSortCriteria criteria = new ResourceSortCriteria(sortCrit);

    Sort sort = sut.getSort(criteria);
    assertEquals(1, sort.getSort().length);
    assertEquals("dateAdded", sort.getSort()[0].getField());
    assertEquals(true, sort.getSort()[0].getReverse());
}

From source file:org.eurekastreams.server.service.actions.strategies.directory.SortFieldBuilderTest.java

License:Apache License

/**
 * Test getSort() by followers count, ascending.
 *//*from www  . j  a  v  a2 s.c  o  m*/
@Test
public void testGetSortByFollowersCount() {
    List<ResourceSortCriterion> sortCrit = new ArrayList<ResourceSortCriterion>();
    sortCrit.add(new ResourceSortCriterion(SortField.FOLLOWERS_COUNT, SortDirection.ASCENDING));
    ResourceSortCriteria criteria = new ResourceSortCriteria(sortCrit);

    Sort sort = sut.getSort(criteria);
    assertEquals(1, sort.getSort().length);
    assertEquals("followersCount", sort.getSort()[0].getField());
    assertEquals(false, sort.getSort()[0].getReverse());
}

From source file:org.eurekastreams.server.service.actions.strategies.directory.SortFieldBuilderTest.java

License:Apache License

/**
 * Test getSort() by followers count added.
 *//*from  w  w  w. j  ava2s. c  o m*/
@Test
public void testGetSortByFollowersCountDescending() {
    List<ResourceSortCriterion> sortCrit = new ArrayList<ResourceSortCriterion>();
    sortCrit.add(new ResourceSortCriterion(SortField.FOLLOWERS_COUNT, SortDirection.DESCENDING));
    ResourceSortCriteria criteria = new ResourceSortCriteria(sortCrit);

    Sort sort = sut.getSort(criteria);
    assertEquals(1, sort.getSort().length);
    assertEquals("followersCount", sort.getSort()[0].getField());
    assertEquals(true, sort.getSort()[0].getReverse());
}

From source file:org.eurekastreams.server.service.actions.strategies.directory.SortFieldBuilderTest.java

License:Apache License

/**
 * Test getSort() by name, ascending./*from   w w  w  .j  a  va  2s.  c  o m*/
 */
@Test
public void testGetSortByName() {
    List<ResourceSortCriterion> sortCrit = new ArrayList<ResourceSortCriterion>();
    sortCrit.add(new ResourceSortCriterion(SortField.NAME, SortDirection.ASCENDING));
    ResourceSortCriteria criteria = new ResourceSortCriteria(sortCrit);

    Sort sort = sut.getSort(criteria);
    assertEquals(1, sort.getSort().length);
    assertEquals("byName", sort.getSort()[0].getField());
    assertEquals(false, sort.getSort()[0].getReverse());
}