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:aos.lucene.search.advanced.SortingExample.java

License:Apache License

public static void main(String[] args) throws Exception {
    Query allBooks = new MatchAllDocsQuery();

    QueryParser parser = new QueryParser(Version.LUCENE_46, //
            "contents", //
            new StandardAnalyzer( //
                    Version.LUCENE_46)); //
    BooleanQuery query = new BooleanQuery(); //
    query.add(allBooks, BooleanClause.Occur.SHOULD); //
    query.add(parser.parse("java OR action"), BooleanClause.Occur.SHOULD); //

    Directory directory = TestUtil.getBookIndexDirectory(); //
    SortingExample example = new SortingExample(directory); //

    example.displayResults(query, Sort.RELEVANCE);

    example.displayResults(query, Sort.INDEXORDER);

    example.displayResults(query, new Sort(new SortField("category", SortField.STRING)));

    example.displayResults(query, new Sort(new SortField("pubmonth", SortField.INT, true)));

    example.displayResults(query, new Sort(new SortField("category", SortField.STRING), SortField.FIELD_SCORE,
            new SortField("pubmonth", SortField.INT, true)));

    example.displayResults(query,//www  .java2 s  .  c  o  m
            new Sort(new SortField[] { SortField.FIELD_SCORE, new SortField("category", SortField.STRING) }));
    directory.close();
}

From source file:com.b2international.snowowl.snomed.api.impl.ClassificationRunIndex.java

License:Apache License

public void invalidateClassificationRuns() throws IOException {

    final Query statusQuery = Fields.newQuery().field(FIELD_STATUS, ClassificationStatus.COMPLETED.name())
            .field(FIELD_STATUS, ClassificationStatus.RUNNING.name())
            .field(FIELD_STATUS, ClassificationStatus.SAVING_IN_PROGRESS.name())
            .field(FIELD_STATUS, ClassificationStatus.SCHEDULED.name()).matchAny();

    final Query query = Fields.newQuery().field(FIELD_CLASS, ClassificationRun.class.getSimpleName())
            .and(statusQuery).matchAll();

    IndexSearcher searcher = null;//from  www.  j ava 2s  . c  o  m

    try {

        searcher = manager.acquire();

        final TotalHitCountCollector collector = new TotalHitCountCollector();
        searcher.search(query, collector);
        final int totalHits = collector.getTotalHits();

        final int docsToRetrieve = Ints.min(searcher.getIndexReader().maxDoc(), totalHits);
        if (docsToRetrieve < 1) {
            return;
        }

        final TopDocs docs = searcher.search(query, docsToRetrieve, Sort.INDEXORDER, false, false);
        final ScoreDoc[] scoreDocs = docs.scoreDocs;

        final ObjectReader reader = objectMapper.reader(ClassificationRun.class);
        for (int i = 0; i < scoreDocs.length; i++) {
            final Document sourceDocument = searcher.doc(scoreDocs[i].doc,
                    ImmutableSet.of(FIELD_BRANCH_PATH, FIELD_SOURCE));

            final String branchPath = sourceDocument.get(FIELD_BRANCH_PATH);
            final String source = sourceDocument.get(FIELD_SOURCE);
            final ClassificationRun run = reader.readValue(source);

            run.setStatus(ClassificationStatus.STALE);

            upsertClassificationRunNoCommit(branchPath, run);
        }

        commit();

    } finally {
        if (null != searcher) {
            manager.release(searcher);
        }
    }
}

From source file:com.b2international.snowowl.snomed.api.impl.ClassificationRunIndex.java

License:Apache License

private <T> List<T> search(final Query query, final Class<? extends T> sourceClass, final int offset,
        final int limit) throws IOException {
    return search(query, sourceClass, Sort.INDEXORDER, offset, limit);
}

From source file:com.b2international.snowowl.snomed.api.impl.ClassificationRunIndex.java

License:Apache License

private List<Document> search(final Query query, final int limit) throws IOException {
    IndexSearcher searcher = null;/* www .ja v  a2s  .  c  o m*/

    try {

        searcher = manager.acquire();
        final TopDocs docs = searcher.search(query, limit, Sort.INDEXORDER, false, false);
        final ImmutableList.Builder<Document> resultBuilder = ImmutableList.builder();

        for (final ScoreDoc scoreDoc : docs.scoreDocs) {
            resultBuilder.add(searcher.doc(scoreDoc.doc));
        }

        return resultBuilder.build();

    } finally {

        if (null != searcher) {
            manager.release(searcher);
        }
    }
}

From source file:com.github.msarhan.lucene.ArabicRootExtractorAnalyzerTests.java

License:Open Source License

@Test
public void testInlineStemmer() throws IOException, ParseException {

    //Initialize the index
    Directory index = new RAMDirectory();
    Analyzer analyzer = new ArabicRootExtractorAnalyzer();
    IndexWriterConfig config = new IndexWriterConfig(analyzer);
    IndexWriter writer = new IndexWriter(index, config);

    Document doc = new Document();
    doc.add(new StringField("number", "1", Field.Store.YES));
    doc.add(new TextField("title", "?? ? ? ??",
            Field.Store.YES));/*from   ww w. ja va2 s .co m*/
    writer.addDocument(doc);

    doc = new Document();
    doc.add(new StringField("number", "2", Field.Store.YES));
    doc.add(new TextField("title", "? ?? ? ?",
            Field.Store.YES));
    writer.addDocument(doc);

    doc = new Document();
    doc.add(new StringField("number", "3", Field.Store.YES));
    doc.add(new TextField("title", "? ??", Field.Store.YES));
    writer.addDocument(doc);
    writer.close();
    //~

    //Query the index
    String queryStr = "";
    Query query = new QueryParser("title", analyzer).parse(queryStr);

    int hitsPerPage = 5;
    IndexReader reader = DirectoryReader.open(index);
    IndexSearcher searcher = new IndexSearcher(reader);
    TopDocs docs = searcher.search(query, hitsPerPage, Sort.INDEXORDER);

    ScoreDoc[] hits = docs.scoreDocs;
    //~

    //Print results
    /*
    System.out.println("Found " + hits.length + " hits:");
    for (ScoreDoc hit : hits) {
       int docId = hit.doc;
       Document d = searcher.doc(docId);
       System.out.printf("\t(%s): %s\n", d.get("number"), d.get("title"));
    }
    */
    //~

}

From source file:com.ideabase.repository.core.search.impl.RepositoryItemSearchImpl.java

License:Open Source License

private void applySortingFilter(final Query pQuery,
        final RepositoryItemSearchImpl.RepositoryHitCollectorImpl pHitCollector, final LuceneSearcher pSearcher)
        throws IOException {
    Sort sort = new Sort();
    final List<SortField> sortFields = new ArrayList<SortField>();
    for (final Map.Entry<String, Boolean> entry : pQuery.getSortableFields().entrySet()) {
        // verify special field like relevant and indexoredered
        final String key = entry.getKey();
        final Boolean decending = entry.getValue();
        if (SORT_RELEVANT.equalsIgnoreCase(key)) {
            LOG.debug("Applying relevance sorting.");
            sort = Sort.RELEVANCE;/*from w  ww . java  2  s  .  co m*/
            break;
        } else if (SORT_INDEXORDERED.equalsIgnoreCase(key)) {
            LOG.debug("Applying Index ordered sorting.");
            sort = Sort.INDEXORDER;
            break;
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Applying sort field - " + key);
            }
            if (key.startsWith(CommonConstants.FIELD_PREFIX_PRICE)
                    || key.endsWith(CommonConstants.FIELD_SUFFIX_ID)
                    || key.endsWith(CommonConstants.FIELD_SUFFIX_DATE)) {
                sortFields.add(new SortField(key, mNumberSortComparator, decending.booleanValue()));
            } else {
                sortFields.add(new SortField(key, decending.booleanValue()));
            }
        }
    }
    if (!sortFields.isEmpty()) {
        sort.setSort(sortFields.toArray(new SortField[] {}));
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Sortable fields - " + sort);
    }

    // perform lucene search and collect the search hits.
    populateHitCollector(pHitCollector, pSearcher.search(pQuery.buildQuery(), sort));
}

From source file:com.leavesfly.lia.advsearching.SortingExample.java

License:Apache License

public static void main(String[] args) throws Exception {
    Query allBooks = new MatchAllDocsQuery();

    QueryParser parser = new QueryParser(Version.LUCENE_30, // #1
            "contents", // #1
            new StandardAnalyzer( // #1
                    Version.LUCENE_30)); // #1
    BooleanQuery query = new BooleanQuery(); // #1
    query.add(allBooks, BooleanClause.Occur.SHOULD); // #1
    query.add(parser.parse("java OR action"), BooleanClause.Occur.SHOULD); // #1

    Directory directory = TestUtil.getBookIndexDirectory(); // #2
    SortingExample example = new SortingExample(directory); // #2

    example.displayResults(query, Sort.RELEVANCE);

    example.displayResults(query, Sort.INDEXORDER);

    example.displayResults(query, new Sort(new SortField("category", SortField.STRING)));

    example.displayResults(query, new Sort(new SortField("pubmonth", SortField.INT, true)));

    example.displayResults(query, new Sort(new SortField("category", SortField.STRING), SortField.FIELD_SCORE,
            new SortField("pubmonth", SortField.INT, true)));

    example.displayResults(query,//from   ww  w  .j  a v  a 2  s  .  co  m
            new Sort(new SortField[] { SortField.FIELD_SCORE, new SortField("category", SortField.STRING) }));
    directory.close();
}

From source file:com.mathworks.xzheng.advsearching.SortingExample.java

License:Apache License

public static void main(String[] args) throws Exception {
    Query allBooks = new MatchAllDocsQuery();

    QueryParser parser = new QueryParser(Version.LUCENE_46, // #1
            "contents", // #1
            new StandardAnalyzer( // #1
                    Version.LUCENE_46)); // #1
    BooleanQuery query = new BooleanQuery(); // #1
    query.add(allBooks, BooleanClause.Occur.SHOULD); // #1
    query.add(parser.parse("java OR action"), BooleanClause.Occur.SHOULD); // #1

    Directory directory = TestUtil.getBookIndexDirectory(); // #2
    SortingExample example = new SortingExample(directory); // #2

    example.displayResults(query, Sort.RELEVANCE);

    example.displayResults(query, Sort.INDEXORDER);

    example.displayResults(query, new Sort(new SortField("category", SortField.STRING)));

    example.displayResults(query, new Sort(new SortField("pubmonth", SortField.INT, true)));

    example.displayResults(query, new Sort(new SortField("category", SortField.STRING), SortField.FIELD_SCORE,
            new SortField("pubmonth", SortField.INT, true)));

    example.displayResults(query,// w  w  w. jav a 2  s  . co m
            new Sort(new SortField[] { SortField.FIELD_SCORE, new SortField("category", SortField.STRING) }));
    directory.close();
}

From source file:com.querydsl.lucene4.AbstractLuceneQuery.java

License:Apache License

private long innerCount() {
    try {//from   w  ww .  j  a  v a2s .c o  m
        final int maxDoc = searcher.getIndexReader().maxDoc();
        if (maxDoc == 0) {
            return 0;
        }
        return searcher.search(createQuery(), getFilter(), maxDoc, Sort.INDEXORDER, false, false).totalHits;
    } catch (IOException e) {
        throw new QueryException(e);
    } catch (IllegalArgumentException e) {
        throw new QueryException(e);
    }
}

From source file:com.querydsl.lucene4.AbstractLuceneQuery.java

License:Apache License

@Override
public CloseableIterator<T> iterate() {
    final QueryMetadata metadata = queryMixin.getMetadata();
    final List<OrderSpecifier<?>> orderBys = metadata.getOrderBy();
    final Integer queryLimit = metadata.getModifiers().getLimitAsInteger();
    final Integer queryOffset = metadata.getModifiers().getOffsetAsInteger();
    Sort sort = querySort;//from  w  ww .j a va2 s .com
    int limit;
    final int offset = queryOffset != null ? queryOffset : 0;
    try {
        limit = maxDoc();
        if (limit == 0) {
            return new EmptyCloseableIterator<T>();
        }
    } catch (IOException e) {
        throw new QueryException(e);
    } catch (IllegalArgumentException e) {
        throw new QueryException(e);
    }
    if (queryLimit != null && queryLimit < limit) {
        limit = queryLimit;
    }
    if (sort == null && !orderBys.isEmpty()) {
        sort = serializer.toSort(orderBys);
    }

    try {
        ScoreDoc[] scoreDocs;
        int sumOfLimitAndOffset = limit + offset;
        if (sumOfLimitAndOffset < 1) {
            throw new QueryException(
                    "The given limit (" + limit + ") and offset (" + offset + ") cause an integer overflow.");
        }
        if (sort != null) {
            scoreDocs = searcher.search(createQuery(), getFilter(), sumOfLimitAndOffset, sort, false,
                    false).scoreDocs;
        } else {
            scoreDocs = searcher.search(createQuery(), getFilter(), sumOfLimitAndOffset, Sort.INDEXORDER, false,
                    false).scoreDocs;
        }
        if (offset < scoreDocs.length) {
            return new ResultIterator<T>(scoreDocs, offset, searcher, fieldsToLoad, transformer);
        }
        return new EmptyCloseableIterator<T>();
    } catch (final IOException e) {
        throw new QueryException(e);
    }
}