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

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

Introduction

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

Prototype

Sort INDEXORDER

To view the source code for org.apache.lucene.search Sort INDEXORDER.

Click Source Link

Document

Represents sorting by index order.

Usage

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

License:Apache License

public void testMaxScore() throws Exception {
    Directory d = newDirectory();//  w  w  w .ja v a 2 s. c o m
    // Not RIW because we need exactly 2 segs:
    IndexWriter w = new IndexWriter(d, new IndexWriterConfig(new MockAnalyzer(random())));
    int id = 0;
    for (int seg = 0; seg < 2; seg++) {
        for (int docIDX = 0; docIDX < 10; docIDX++) {
            Document doc = new Document();
            doc.add(new LegacyIntField("id", docIDX, Field.Store.YES));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < id; i++) {
                sb.append(' ');
                sb.append("text");
            }
            doc.add(newTextField("body", sb.toString(), Field.Store.NO));
            w.addDocument(doc);
            id++;
        }
        w.commit();
    }

    IndexReader r = UninvertingReader.wrap(DirectoryReader.open(w),
            Collections.singletonMap("id", Type.LEGACY_INTEGER));
    w.close();
    Query q = new TermQuery(new Term("body", "text"));
    IndexSearcher s = newSearcher(r);
    float maxScore = s.search(q, 10).getMaxScore();
    assertEquals(maxScore, s.search(q, 3, Sort.INDEXORDER, random().nextBoolean(), true).getMaxScore(), 0.0);
    assertEquals(maxScore, s.search(q, 3, Sort.RELEVANCE, random().nextBoolean(), true).getMaxScore(), 0.0);
    assertEquals(maxScore,
            s.search(q, 3, new Sort(new SortField[] { new SortField("id", SortField.Type.INT, false) }),
                    random().nextBoolean(), true).getMaxScore(),
            0.0);
    assertEquals(maxScore,
            s.search(q, 3, new Sort(new SortField[] { new SortField("id", SortField.Type.INT, true) }),
                    random().nextBoolean(), true).getMaxScore(),
            0.0);
    TestUtil.checkReader(r);
    r.close();
    d.close();
}

From source file:org.azrul.langkuik.dao.HibernateGenericDAO.java

public Collection<T> search(Collection<SearchTerm> searchTerms, Class<T> daoClass, String orderBy, boolean asc,
        int startIndex, int offset) {
    if (searchTerms == null || searchTerms.isEmpty()) {
        return getAll(daoClass, orderBy, asc, startIndex, offset);
    }// w ww  .j av a  2s  .  c  o m
    try {
        EntityManager em = emf.createEntityManager();

        FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search
                .getFullTextEntityManager(em);

        //Session session = (Session) em.getDelegate();
        //String currentIdField = session.getSessionFactory().getClassMetadata(daoClass).getIdentifierPropertyName();
        String currentIdField = this.getIdentifierFieldName();
        org.apache.lucene.search.Query luceneQuery = buildSearchQuery(fullTextEntityManager, daoClass,
                searchTerms);
        Sort sort = Sort.INDEXORDER;
        if (orderBy == null) {
            if (Long.TYPE.equals(daoClass.getDeclaredField(currentIdField).getType())) {
                sort = new Sort(new SortField(currentIdField, SortField.LONG, asc));
            } else if (Integer.TYPE.equals(daoClass.getDeclaredField(currentIdField).getType())) {
                sort = new Sort(new SortField(currentIdField, SortField.INT, asc));
            } else if (String.class.equals(daoClass.getDeclaredField(currentIdField).getType())) {
                sort = new Sort(new SortField(currentIdField, SortField.STRING, asc));
            }
        } else {
            if (Long.TYPE.equals(daoClass.getDeclaredField(orderBy).getType())) {
                sort = new Sort(new SortField(orderBy, SortField.LONG, asc));
            } else if (Integer.TYPE.equals(daoClass.getDeclaredField(orderBy).getType())) {
                sort = new Sort(new SortField(orderBy, SortField.INT, asc));
            } else { //all else fail, sort as string
                sort = new Sort(new SortField(orderBy, SortField.STRING, asc));
            }
        }

        Query jpaQuery = fullTextEntityManager.createFullTextQuery(luceneQuery, daoClass).setSort(sort)
                .setFirstResult(startIndex).setMaxResults(offset);

        List<T> results = jpaQuery.getResultList();
        fullTextEntityManager.close();

        return results;
    } catch (NoSuchFieldException ex) {
        Logger.getLogger(HibernateGenericDAO.class.getName()).log(Level.SEVERE, null, ex);
    }
    return new ArrayList<T>();
}

From source file:org.brutusin.fleadb.pagination.PaginatorImpl.java

License:Apache License

public PaginatorImpl(IndexSearcher searcher, DocTransformer<E> transformer, Query q, Sort sort) {
    if (sort == null) {
        sort = Sort.INDEXORDER;
    }/*from   w  w w . j  a  v  a2 s. com*/
    this.searcher = searcher;
    this.q = q;
    this.sort = sort;
    this.transformer = transformer;
}

From source file:org.elasticsearch.search.profile.ProfileTests.java

License:Apache License

public void testNoScoring() throws IOException {
    Profiler profiler = new Profiler();
    searcher.setProfiler(profiler);//from   w  ww.j  a va  2  s .c  o  m
    Query query = new TermQuery(new Term("foo", "bar"));
    searcher.search(query, 1, Sort.INDEXORDER); // scores are not needed
    List<ProfileResult> results = profiler.getQueryTree();
    assertEquals(1, results.size());
    Map<String, Long> breakdown = results.get(0).getTimeBreakdown();
    assertThat(breakdown.get(ProfileBreakdown.TimingType.CREATE_WEIGHT.toString()).longValue(),
            greaterThan(0L));
    assertThat(breakdown.get(ProfileBreakdown.TimingType.BUILD_SCORER.toString()).longValue(), greaterThan(0L));
    assertThat(breakdown.get(ProfileBreakdown.TimingType.NEXT_DOC.toString()).longValue(), greaterThan(0L));
    assertThat(breakdown.get(ProfileBreakdown.TimingType.ADVANCE.toString()).longValue(), equalTo(0L));
    assertThat(breakdown.get(ProfileBreakdown.TimingType.SCORE.toString()).longValue(), equalTo(0L));
    assertThat(breakdown.get(ProfileBreakdown.TimingType.MATCH.toString()).longValue(), equalTo(0L));

    long rewriteTime = profiler.getRewriteTime();
    assertThat(rewriteTime, greaterThan(0L));
}

From source file:org.elasticsearch.search.profile.query.ProfileTests.java

License:Apache License

public void testNoScoring() throws IOException {
    QueryProfiler profiler = new QueryProfiler();
    searcher.setProfiler(profiler);//from w ww .  j  a v  a2s .c  o m
    Query query = new TermQuery(new Term("foo", "bar"));
    searcher.search(query, 1, Sort.INDEXORDER); // scores are not needed
    List<ProfileResult> results = profiler.getQueryTree();
    assertEquals(1, results.size());
    Map<String, Long> breakdown = results.get(0).getTimeBreakdown();
    assertThat(breakdown.get(QueryTimingType.CREATE_WEIGHT.toString()).longValue(), greaterThan(0L));
    assertThat(breakdown.get(QueryTimingType.BUILD_SCORER.toString()).longValue(), greaterThan(0L));
    assertThat(breakdown.get(QueryTimingType.NEXT_DOC.toString()).longValue(), greaterThan(0L));
    assertThat(breakdown.get(QueryTimingType.ADVANCE.toString()).longValue(), equalTo(0L));
    assertThat(breakdown.get(QueryTimingType.SCORE.toString()).longValue(), equalTo(0L));
    assertThat(breakdown.get(QueryTimingType.MATCH.toString()).longValue(), equalTo(0L));

    long rewriteTime = profiler.getRewriteTime();
    assertThat(rewriteTime, greaterThan(0L));
}

From source file:org.elasticsearch.search.profile.query.QueryProfilerTests.java

License:Apache License

public void testNoScoring() throws IOException {
    QueryProfiler profiler = new QueryProfiler();
    searcher.setProfiler(profiler);// ww w  .j  a  va  2  s. c  o m
    Query query = new TermQuery(new Term("foo", "bar"));
    searcher.search(query, 1, Sort.INDEXORDER); // scores are not needed
    List<ProfileResult> results = profiler.getTree();
    assertEquals(1, results.size());
    Map<String, Long> breakdown = results.get(0).getTimeBreakdown();
    assertThat(breakdown.get(QueryTimingType.CREATE_WEIGHT.toString()).longValue(), greaterThan(0L));
    assertThat(breakdown.get(QueryTimingType.BUILD_SCORER.toString()).longValue(), greaterThan(0L));
    assertThat(breakdown.get(QueryTimingType.NEXT_DOC.toString()).longValue(), greaterThan(0L));
    assertThat(breakdown.get(QueryTimingType.ADVANCE.toString()).longValue(), equalTo(0L));
    assertThat(breakdown.get(QueryTimingType.SCORE.toString()).longValue(), equalTo(0L));
    assertThat(breakdown.get(QueryTimingType.MATCH.toString()).longValue(), equalTo(0L));

    assertThat(breakdown.get(QueryTimingType.CREATE_WEIGHT.toString() + "_count").longValue(), greaterThan(0L));
    assertThat(breakdown.get(QueryTimingType.BUILD_SCORER.toString() + "_count").longValue(), greaterThan(0L));
    assertThat(breakdown.get(QueryTimingType.NEXT_DOC.toString() + "_count").longValue(), greaterThan(0L));
    assertThat(breakdown.get(QueryTimingType.ADVANCE.toString() + "_count").longValue(), equalTo(0L));
    assertThat(breakdown.get(QueryTimingType.SCORE.toString() + "_count").longValue(), equalTo(0L));
    assertThat(breakdown.get(QueryTimingType.MATCH.toString() + "_count").longValue(), equalTo(0L));

    long rewriteTime = profiler.getRewriteTime();
    assertThat(rewriteTime, greaterThan(0L));
}

From source file:org.elasticsearch.search.scan.ScanContextTests.java

License:Apache License

public void testRandom() throws Exception {
    final int numDocs = randomIntBetween(10, 200);
    final Document doc1 = new Document();
    doc1.add(new StringField("foo", "bar", Store.NO));
    final Document doc2 = new Document();
    final Directory dir = newDirectory();
    final RandomIndexWriter w = new RandomIndexWriter(getRandom(), dir);
    for (int i = 0; i < numDocs; ++i) {
        w.addDocument(randomBoolean() ? doc1 : doc2);
    }// w  w w.  j  a  v  a2s  .  c  om
    final IndexReader reader = w.getReader();
    final IndexSearcher searcher = newSearcher(reader);

    final boolean trackScores = randomBoolean();
    final int pageSize = randomIntBetween(1, numDocs / 2);
    Query query = new TermQuery(new Term("foo", "bar"));
    if (trackScores == false) {
        query.setBoost(0f);
    }
    final ScoreDoc[] expected = searcher.search(query, numDocs, Sort.INDEXORDER, true, true).scoreDocs;

    final List<ScoreDoc> actual = new ArrayList<>();
    ScanContext context = new ScanContext();
    while (true) {
        final ScoreDoc[] page = execute(searcher, context, query, pageSize, trackScores).scoreDocs;
        assertTrue(page.length <= pageSize);
        if (page.length == 0) {
            assertEquals(0, execute(searcher, context, query, pageSize, trackScores).scoreDocs.length);
            break;
        }
        actual.addAll(Arrays.asList(page));
    }
    assertEquals(expected.length, actual.size());
    for (int i = 0; i < expected.length; ++i) {
        ScoreDoc sd1 = expected[i];
        ScoreDoc sd2 = actual.get(i);
        assertEquals(sd1.doc, sd2.doc);
        assertEquals(sd1.score, sd2.score, 0.001f);
    }
    w.close();
    reader.close();
    dir.close();
}

From source file:org.fao.geonet.kernel.search.LuceneSearcherPresentTest.java

License:Open Source License

@Ignore
public void testBuildPrivilegesMetadataInfo() throws Exception {
    final ServiceContext serviceContext = createServiceContext();
    loginAsAdmin(serviceContext);/*from  w  ww .  j a va  2s.com*/
    final MEFLibIntegrationTest.ImportMetadata importMetadata = new MEFLibIntegrationTest.ImportMetadata(this,
            serviceContext);
    importMetadata.invoke();

    Element info = new Element("info", Geonet.Namespaces.GEONET);
    IndexAndTaxonomy indexAndTaxonomy = searchManager.getNewIndexReader("eng");

    try {
        TopFieldCollector tfc = TopFieldCollector.create(Sort.INDEXORDER, 1000, true, false, false, true);
        IndexSearcher searcher = new IndexSearcher(indexAndTaxonomy.indexReader);
        searcher.search(new MatchAllDocsQuery(), tfc);

        final Document doc = indexAndTaxonomy.indexReader.document(tfc.topDocs().scoreDocs[0].doc);
        LuceneSearcher.buildPrivilegesMetadataInfo(serviceContext, doc, info);

        assertEqualsText("true", info, "edit");
        assertEqualsText("true", info, "owner");
        assertNotNull("Expected ownerId to be one of the elements in : " + Xml.getString(info),
                info.getChild("ownerId"));
        assertEqualsText("true", info, "view");
        assertEqualsText("true", info, "notify");
        assertEqualsText("true", info, "download");
        assertEqualsText("true", info, "dynamic");
        assertEqualsText("true", info, "featured");
    } finally {
        searchManager.releaseIndexReader(indexAndTaxonomy);
    }

    final String mdId = importMetadata.getMetadataIds().get(0);
    dataManager.unsetOperation(serviceContext, mdId, "" + ReservedGroup.all.getId(), ReservedOperation.editing);
    dataManager.indexMetadata(mdId, true, null);

    indexAndTaxonomy = searchManager.getNewIndexReader("eng");
    try {
        TopFieldCollector tfc = TopFieldCollector.create(Sort.INDEXORDER, 1000, true, false, false, true);
        IndexSearcher searcher = new IndexSearcher(indexAndTaxonomy.indexReader);
        searcher.search(new MatchAllDocsQuery(), tfc);

        final Document doc = indexAndTaxonomy.indexReader.document(tfc.topDocs().scoreDocs[0].doc);

        serviceContext.setUserSession(new UserSession());
        SecurityContextHolder.clearContext();
        info.removeContent();
        LuceneSearcher.buildPrivilegesMetadataInfo(serviceContext, doc, info);

        assertNull(Xml.selectElement(info, "edit"));
        assertNull(Xml.selectElement(info, "owner"));
        //TODO: Check why guestdownload is no longer part of info.
        //assertEqualsText("false", info, "guestdownload");
        assertEqualsText("true", info, "isPublishedToAll");
        assertEqualsText("true", info, "view");
        assertEqualsText("false", info, "notify");
        //TODO: inverted three assertions, Check why download, dynamic and featured are no longer false.
        assertEqualsText("true", info, "download");
        assertEqualsText("true", info, "dynamic");
        assertEqualsText("true", info, "featured");
    } finally {
        searchManager.releaseIndexReader(indexAndTaxonomy);
    }
}

From source file:org.kie.workbench.common.services.refactoring.backend.server.query.IndexQuery.java

License:Apache License

default Sort getSortOrder() {
    return Sort.INDEXORDER;
}

From source file:org.neo4j.kernel.api.impl.index.collector.DocValuesCollector.java

License:Open Source License

/**
 * @param field the field that contains the values
 * @param sort how the results should be sorted
 * @return an iterator over all NumericDocValues from the given field with respect to the given sort
 * @throws IOException// w  w w .  java2s  . c  om
 */
public PrimitiveLongIterator getSortedValuesIterator(String field, Sort sort) throws IOException {
    if (sort == null || sort == Sort.INDEXORDER) {
        return getValuesIterator(field);
    }
    int size = getTotalHits();
    if (size == 0) {
        return PrimitiveLongCollections.emptyIterator();
    }
    TopDocs topDocs = getTopDocs(sort, size);
    LeafReaderContext[] contexts = getLeafReaderContexts(getMatchingDocs());
    return new TopDocsValuesIterator(topDocs, contexts, field);
}