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

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

Introduction

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

Prototype

public Sort() 

Source Link

Document

Sorts by computed relevance.

Usage

From source file:org.apache.james.mailbox.lucene.search.LuceneMessageSearchIndex.java

License:Apache License

private Sort createSort(List<SearchQuery.Sort> sorts) {
    Sort sort = new Sort();
    List<SortField> fields = new ArrayList<SortField>();

    for (SearchQuery.Sort s : sorts) {
        boolean reverse = s.isReverse();
        SortField sf = null;/*from   w  w  w .  j  a va2  s  . c  o  m*/

        switch (s.getSortClause()) {
        case Arrival:
            if (reverse) {
                sf = ARRIVAL_MAILBOX_SORT_REVERSE;
            } else {
                sf = ARRIVAL_MAILBOX_SORT;
            }
            break;
        case SentDate:
            if (reverse) {
                sf = SENT_DATE_SORT_REVERSE;
            } else {
                sf = SENT_DATE_SORT;
            }
            break;
        case MailboxCc:
            if (reverse) {
                sf = FIRST_CC_MAILBOX_SORT_REVERSE;
            } else {
                sf = FIRST_CC_MAILBOX_SORT;
            }
            break;
        case MailboxFrom:
            if (reverse) {
                sf = FIRST_FROM_MAILBOX_SORT_REVERSE;
            } else {
                sf = FIRST_FROM_MAILBOX_SORT;
            }
            break;
        case Size:
            if (reverse) {
                sf = SIZE_SORT_REVERSE;
            } else {
                sf = SIZE_SORT;
            }
            break;
        case BaseSubject:
            if (reverse) {
                sf = BASE_SUBJECT_SORT_REVERSE;
            } else {
                sf = BASE_SUBJECT_SORT;
            }
            break;
        case MailboxTo:
            if (reverse) {
                sf = FIRST_TO_MAILBOX_SORT_REVERSE;
            } else {
                sf = FIRST_TO_MAILBOX_SORT;
            }
            break;

        case Uid:
            if (reverse) {
                sf = UID_SORT_REVERSE;
            } else {
                sf = UID_SORT;
            }
            break;
        case DisplayFrom:
            if (reverse) {
                sf = FIRST_FROM_MAILBOX_DISPLAY_SORT_REVERSE;
            } else {
                sf = FIRST_FROM_MAILBOX_DISPLAY_SORT;
            }
            break;
        case DisplayTo:
            if (reverse) {
                sf = FIRST_TO_MAILBOX_DISPLAY_SORT_REVERSE;
            } else {
                sf = FIRST_TO_MAILBOX_DISPLAY_SORT;
            }
            break;
        default:
            break;
        }
        if (sf != null) {

            fields.add(sf);

            // Add the uid sort as tie-breaker
            if (sf == SENT_DATE_SORT) {
                fields.add(UID_SORT);
            } else if (sf == SENT_DATE_SORT_REVERSE) {
                fields.add(UID_SORT_REVERSE);
            }
        }
    }
    // add the uid sorting as last so if no other sorting was able todo the job it will get sorted by the uid
    fields.add(UID_SORT);
    sort.setSort(fields.toArray(new SortField[0]));
    return sort;
}

From source file:org.apache.solr.handler.clustering.carrot2.CarrotClusteringEngineTest.java

License:Apache License

private List<NamedList<Object>> checkEngine(CarrotClusteringEngine engine, int expectedNumDocs,
        int expectedNumClusters, Query query, SolrParams clusteringParams) throws IOException {
    // Get all documents to cluster
    RefCounted<SolrIndexSearcher> ref = h.getCore().getSearcher();

    DocList docList;//from  ww  w.ja  v  a 2s . c om
    try {
        SolrIndexSearcher searcher = ref.get();
        docList = searcher.getDocList(query, (Query) null, new Sort(), 0, numberOfDocs);
        assertEquals("docList size", expectedNumDocs, docList.matches());

        ModifiableSolrParams solrParams = new ModifiableSolrParams();
        solrParams.add(clusteringParams);

        // Perform clustering
        LocalSolrQueryRequest req = new LocalSolrQueryRequest(h.getCore(), solrParams);
        Map<SolrDocument, Integer> docIds = new HashMap<SolrDocument, Integer>(docList.size());
        SolrDocumentList solrDocList = SolrPluginUtils.docListToSolrDocumentList(docList, searcher,
                engine.getFieldsToLoad(req), docIds);

        @SuppressWarnings("unchecked")
        List<NamedList<Object>> results = (List<NamedList<Object>>) engine.cluster(query, solrDocList, docIds,
                req);
        req.close();
        assertEquals("number of clusters: " + results, expectedNumClusters, results.size());
        checkClusters(results, false);
        return results;
    } finally {
        ref.decref();
    }
}

From source file:org.apache.solr.response.transform.ChildDocTransformerFactory.java

License:Apache License

@Override
public void transform(SolrDocument doc, int docid) {

    FieldType idFt = idField.getType();/*from  ww w . j ava2  s.co  m*/
    Object parentIdField = doc.getFirstValue(idField.getName());

    String parentIdExt = parentIdField instanceof IndexableField
            ? idFt.toExternal((IndexableField) parentIdField)
            : parentIdField.toString();

    try {
        Query parentQuery = idFt.getFieldQuery(null, idField, parentIdExt);
        Query query = new ToChildBlockJoinQuery(parentQuery, parentsFilter, false);
        DocList children = context.searcher.getDocList(query, childFilterQuery, new Sort(), 0, limit);
        if (children.matches() > 0) {
            DocIterator i = children.iterator();
            while (i.hasNext()) {
                Integer childDocNum = i.next();
                Document childDoc = context.searcher.doc(childDocNum);
                SolrDocument solrChildDoc = ResponseWriterUtil.toSolrDocument(childDoc, schema);

                // TODO: future enhancement...
                // support an fl local param in the transformer, which is used to build
                // a private ReturnFields instance that we use to prune unwanted field 
                // names from solrChildDoc
                doc.addChildDocument(solrChildDoc);
            }
        }

    } catch (IOException e) {
        doc.put(name, "Could not fetch child Documents");
    }
}

From source file:org.apache.solr.uninverting.TestFieldCacheSort.java

License:Apache License

/** Tests default sort (by score) */
public void testFieldScore() throws Exception {
    Directory dir = newDirectory();/*from www .ja v  a 2 s  .co  m*/
    RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
    Document doc = new Document();
    doc.add(newTextField("value", "foo bar bar bar bar", Field.Store.NO));
    writer.addDocument(doc);
    doc = new Document();
    doc.add(newTextField("value", "foo foo foo foo foo", Field.Store.NO));
    writer.addDocument(doc);
    IndexReader ir = writer.getReader();
    writer.close();

    IndexSearcher searcher = newSearcher(ir);
    Sort sort = new Sort();

    TopDocs actual = searcher.search(new TermQuery(new Term("value", "foo")), 10, sort);
    assertEquals(2, actual.totalHits);

    TopDocs expected = searcher.search(new TermQuery(new Term("value", "foo")), 10);
    // the two topdocs should be the same
    assertEquals(expected.totalHits, actual.totalHits);
    for (int i = 0; i < actual.scoreDocs.length; i++) {
        assertEquals(actual.scoreDocs[i].doc, expected.scoreDocs[i].doc);
    }
    TestUtil.checkReader(ir);
    ir.close();
    dir.close();
}

From source file:org.apache.solr.uninverting.TestFieldCacheSort.java

License:Apache License

/** test sorts when there's nothing in the index */
public void testEmptyIndex() throws Exception {
    IndexSearcher empty = newSearcher(new MultiReader());
    Query query = new TermQuery(new Term("contents", "foo"));

    Sort sort = new Sort();
    TopDocs td = empty.search(query, 10, sort, true, true);
    assertEquals(0, td.totalHits);/*from   www .j  a  v  a 2 s . co m*/

    sort.setSort(SortField.FIELD_DOC);
    td = empty.search(query, 10, sort, true, true);
    assertEquals(0, td.totalHits);

    sort.setSort(new SortField("int", SortField.Type.INT), SortField.FIELD_DOC);
    td = empty.search(query, 10, sort, true, true);
    assertEquals(0, td.totalHits);

    sort.setSort(new SortField("string", SortField.Type.STRING, true), SortField.FIELD_DOC);
    td = empty.search(query, 10, sort, true, true);
    assertEquals(0, td.totalHits);

    sort.setSort(new SortField("string_val", SortField.Type.STRING_VAL, true), SortField.FIELD_DOC);
    td = empty.search(query, 10, sort, true, true);
    assertEquals(0, td.totalHits);

    sort.setSort(new SortField("float", SortField.Type.FLOAT), new SortField("string", SortField.Type.STRING));
    td = empty.search(query, 10, sort, true, true);
    assertEquals(0, td.totalHits);
}

From source file:org.capelin.mvc.utils.LuceneBuilder.java

License:GNU General Public License

public Sort buildSort(SearchFormObject form) {
    if (null == form.getSortTerm() || StaticStrings.EMPLTY.equals(form.getSortTerm()))
        return null;
    SortField sf;/*w  ww.  j a va  2s . co m*/
    if (WebViewUtils.YEAR.equals(form.getSortTerm())) {
        sf = new SortField(form.getSortTerm(), SortField.STRING, true);
    } else if (WebViewUtils.ID.equals(form.getSortTerm())) {
        sf = new SortField(form.getSortTerm(), SortField.INT, true);
    } else {
        sf = new SortField(form.getSortTerm(), SortField.STRING);
    }
    Sort sort = new Sort();
    sort.setSort(sf);
    return sort;
}

From source file:org.elasticsearch.search.DefaultSearchContextTests.java

License:Apache License

public void testPreProcess() throws Exception {
    TimeValue timeout = new TimeValue(randomIntBetween(1, 100));
    ShardSearchRequest shardSearchRequest = mock(ShardSearchRequest.class);
    when(shardSearchRequest.searchType()).thenReturn(SearchType.DEFAULT);
    ShardId shardId = new ShardId("index", UUID.randomUUID().toString(), 1);
    when(shardSearchRequest.shardId()).thenReturn(shardId);
    when(shardSearchRequest.types()).thenReturn(new String[] {});

    IndexShard indexShard = mock(IndexShard.class);
    QueryCachingPolicy queryCachingPolicy = mock(QueryCachingPolicy.class);
    when(indexShard.getQueryCachingPolicy()).thenReturn(queryCachingPolicy);

    int maxResultWindow = randomIntBetween(50, 100);
    int maxRescoreWindow = randomIntBetween(50, 100);
    int maxSlicesPerScroll = randomIntBetween(50, 100);
    Settings settings = Settings.builder().put("index.max_result_window", maxResultWindow)
            .put("index.max_slices_per_scroll", maxSlicesPerScroll)
            .put("index.max_rescore_window", maxRescoreWindow)
            .put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT)
            .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1).put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 2)
            .build();/* ww w .  ja  v  a2s  .  c om*/

    IndexService indexService = mock(IndexService.class);
    IndexCache indexCache = mock(IndexCache.class);
    QueryCache queryCache = mock(QueryCache.class);
    when(indexCache.query()).thenReturn(queryCache);
    when(indexService.cache()).thenReturn(indexCache);
    QueryShardContext queryShardContext = mock(QueryShardContext.class);
    when(indexService.newQueryShardContext(eq(shardId.id()), anyObject(), anyObject(), anyString()))
            .thenReturn(queryShardContext);
    MapperService mapperService = mock(MapperService.class);
    when(mapperService.hasNested()).thenReturn(randomBoolean());
    when(indexService.mapperService()).thenReturn(mapperService);

    IndexMetaData indexMetaData = IndexMetaData.builder("index").settings(settings).build();
    IndexSettings indexSettings = new IndexSettings(indexMetaData, Settings.EMPTY);
    when(indexService.getIndexSettings()).thenReturn(indexSettings);
    when(mapperService.getIndexSettings()).thenReturn(indexSettings);

    BigArrays bigArrays = new MockBigArrays(new MockPageCacheRecycler(Settings.EMPTY),
            new NoneCircuitBreakerService());

    try (Directory dir = newDirectory();
            RandomIndexWriter w = new RandomIndexWriter(random(), dir);
            IndexReader reader = w.getReader();
            Engine.Searcher searcher = new Engine.Searcher("test", new IndexSearcher(reader))) {

        DefaultSearchContext context1 = new DefaultSearchContext(1L, shardSearchRequest, null, searcher,
                indexService, indexShard, bigArrays, null, timeout, null, null);
        context1.from(300);

        // resultWindow greater than maxResultWindow and scrollContext is null
        IllegalArgumentException exception = expectThrows(IllegalArgumentException.class,
                () -> context1.preProcess(false));
        assertThat(exception.getMessage(),
                equalTo("Result window is too large, from + size must be less than or equal to:" + " ["
                        + maxResultWindow
                        + "] but was [310]. See the scroll api for a more efficient way to request large data sets. "
                        + "This limit can be set by changing the ["
                        + IndexSettings.MAX_RESULT_WINDOW_SETTING.getKey() + "] index level setting."));

        // resultWindow greater than maxResultWindow and scrollContext isn't null
        context1.scrollContext(new ScrollContext());
        exception = expectThrows(IllegalArgumentException.class, () -> context1.preProcess(false));
        assertThat(exception.getMessage(),
                equalTo("Batch size is too large, size must be less than or equal to: [" + maxResultWindow
                        + "] but was [310]. Scroll batch sizes cost as much memory as result windows so they are "
                        + "controlled by the [" + IndexSettings.MAX_RESULT_WINDOW_SETTING.getKey()
                        + "] index level setting."));

        // resultWindow not greater than maxResultWindow and both rescore and sort are not null
        context1.from(0);
        DocValueFormat docValueFormat = mock(DocValueFormat.class);
        SortAndFormats sortAndFormats = new SortAndFormats(new Sort(), new DocValueFormat[] { docValueFormat });
        context1.sort(sortAndFormats);

        RescoreContext rescoreContext = mock(RescoreContext.class);
        when(rescoreContext.getWindowSize()).thenReturn(500);
        context1.addRescore(rescoreContext);

        exception = expectThrows(IllegalArgumentException.class, () -> context1.preProcess(false));
        assertThat(exception.getMessage(), equalTo("Cannot use [sort] option in conjunction with [rescore]."));

        // rescore is null but sort is not null and rescoreContext.getWindowSize() exceeds maxResultWindow
        context1.sort(null);
        exception = expectThrows(IllegalArgumentException.class, () -> context1.preProcess(false));

        assertThat(exception.getMessage(),
                equalTo("Rescore window [" + rescoreContext.getWindowSize() + "] is too large. "
                        + "It must be less than [" + maxRescoreWindow
                        + "]. This prevents allocating massive heaps for storing the results "
                        + "to be rescored. This limit can be set by changing the ["
                        + IndexSettings.MAX_RESCORE_WINDOW_SETTING.getKey() + "] index level setting."));

        // rescore is null but sliceBuilder is not null
        DefaultSearchContext context2 = new DefaultSearchContext(2L, shardSearchRequest, null, searcher,
                indexService, indexShard, bigArrays, null, timeout, null, null);

        SliceBuilder sliceBuilder = mock(SliceBuilder.class);
        int numSlices = maxSlicesPerScroll + randomIntBetween(1, 100);
        when(sliceBuilder.getMax()).thenReturn(numSlices);
        context2.sliceBuilder(sliceBuilder);

        exception = expectThrows(IllegalArgumentException.class, () -> context2.preProcess(false));
        assertThat(exception.getMessage(),
                equalTo("The number of slices [" + numSlices + "] is too large. It must " + "be less than ["
                        + maxSlicesPerScroll + "]. This limit can be set by changing the ["
                        + IndexSettings.MAX_SLICES_PER_SCROLL.getKey() + "] index level setting."));

        // No exceptions should be thrown
        when(shardSearchRequest.getAliasFilter()).thenReturn(AliasFilter.EMPTY);
        when(shardSearchRequest.indexBoost()).thenReturn(AbstractQueryBuilder.DEFAULT_BOOST);

        DefaultSearchContext context3 = new DefaultSearchContext(3L, shardSearchRequest, null, searcher,
                indexService, indexShard, bigArrays, null, timeout, null, null);
        ParsedQuery parsedQuery = ParsedQuery.parsedMatchAllQuery();
        context3.sliceBuilder(null).parsedQuery(parsedQuery).preProcess(false);
        assertEquals(context3.query(), context3.buildFilteredQuery(parsedQuery.query()));
    }
}

From source file:org.janusgraph.diskstorage.lucene.LuceneIndex.java

License:Apache License

private static Sort getSortOrder(List<IndexQuery.OrderEntry> orders) {
    final Sort sort = new Sort();
    if (!orders.isEmpty()) {
        final SortField[] fields = new SortField[orders.size()];
        for (int i = 0; i < orders.size(); i++) {
            final IndexQuery.OrderEntry order = orders.get(i);
            SortField.Type sortType = null;
            final Class dataType = order.getDatatype();
            if (AttributeUtil.isString(dataType))
                sortType = SortField.Type.STRING;
            else if (AttributeUtil.isWholeNumber(dataType))
                sortType = SortField.Type.LONG;
            else if (AttributeUtil.isDecimal(dataType))
                sortType = SortField.Type.DOUBLE;
            else if (dataType.equals(Instant.class) || dataType.equals(Date.class))
                sortType = SortField.Type.LONG;
            else/*w  w  w .j ava 2s .c  o m*/
                Preconditions.checkArgument(false,
                        "Unsupported order specified on field [%s] with datatype [%s]", order.getKey(),
                        dataType);

            fields[i] = new SortField(order.getKey(), sortType, order.getOrder() == Order.DESC);
        }
        sort.setSort(fields);
    }
    return sort;
}