Search in sources :

Example 21 with Sort

use of org.apache.lucene.search.Sort in project zm-mailbox by Zimbra.

the class LuceneIndex method warmup.

/**
     * Runs a common search query + common sort order (and throw away the result) to warm up the Lucene cache and OS
     * file system cache.
     */
@Override
public synchronized void warmup() {
    if (SEARCHER_CACHE.asMap().containsKey(mailbox.getId()) || GAL_SEARCHER_CACHE.containsKey(mailbox.getId())) {
        // already warmed up
        return;
    }
    long start = System.currentTimeMillis();
    IndexSearcher searcher = null;
    try {
        searcher = (IndexSearcher) openSearcher();
        searcher.search(new TermQuery(new Term(LuceneFields.L_CONTENT, "zimbra")), 1, new Sort(new SortField(LuceneFields.L_SORT_DATE, SortField.STRING, true)));
    } catch (IOException e) {
        ZimbraLog.search.warn("Failed to warm up", e);
    } finally {
        Closeables.closeQuietly(searcher);
    }
    ZimbraLog.search.debug("WarmUpLuceneSearcher elapsed=%d", System.currentTimeMillis() - start);
}
Also used : IndexSearcher(org.apache.lucene.search.IndexSearcher) TermQuery(org.apache.lucene.search.TermQuery) Sort(org.apache.lucene.search.Sort) SortField(org.apache.lucene.search.SortField) Term(org.apache.lucene.index.Term) IOException(java.io.IOException)

Example 22 with Sort

use of org.apache.lucene.search.Sort in project jackrabbit by apache.

the class QueryEngine method execute.

protected QueryResult execute(Column[] columns, Selector selector, Constraint constraint, Ordering[] orderings, long offset, long limit, int printIndentation) throws RepositoryException {
    long time = System.currentTimeMillis();
    Map<String, NodeType> selectorMap = getSelectorNames(selector);
    String[] selectorNames = selectorMap.keySet().toArray(new String[selectorMap.size()]);
    Map<String, PropertyValue> columnMap = getColumnMap(columns, selectorMap);
    String[] columnNames = columnMap.keySet().toArray(new String[columnMap.size()]);
    Sort sort = new Sort();
    if (NATIVE_SORT) {
        sort = new Sort(createSortFields(orderings, session));
    }
    // if true it means that the LuceneQueryFactory should just let the
    // QueryEngine take care of sorting and applying offset and limit
    // constraints
    boolean externalSort = !NATIVE_SORT;
    RowIterator rows = null;
    try {
        rows = new RowIteratorAdapter(lqf.execute(columnMap, selector, constraint, sort, externalSort, offset, limit));
    } catch (IOException e) {
        throw new RepositoryException("Failed to access the query index", e);
    } finally {
        log.debug("{}SQL2 SELECT took {} ms. selector: {}, columns: {}, constraint: {}, offset {}, limit {}", new Object[] { genString(printIndentation), System.currentTimeMillis() - time, selector, Arrays.toString(columnNames), constraint, offset, limit });
    }
    QueryResult result = new SimpleQueryResult(columnNames, selectorNames, rows);
    if (NATIVE_SORT) {
        return result;
    }
    long timeSort = System.currentTimeMillis();
    QueryResult sorted = sort(result, orderings, evaluator, offset, limit);
    log.debug("{}SQL2 SORT took {} ms.", genString(printIndentation), System.currentTimeMillis() - timeSort);
    return sorted;
}
Also used : PropertyValue(javax.jcr.query.qom.PropertyValue) RepositoryException(javax.jcr.RepositoryException) IOException(java.io.IOException) QueryResult(javax.jcr.query.QueryResult) RowIteratorAdapter(org.apache.jackrabbit.commons.iterator.RowIteratorAdapter) NodeType(javax.jcr.nodetype.NodeType) RowIterator(javax.jcr.query.RowIterator) Sort(org.apache.lucene.search.Sort)

Example 23 with Sort

use of org.apache.lucene.search.Sort in project jackrabbit by apache.

the class SearchIndex method executeQuery.

/**
     * Executes the query on the search index.
     *
     * @param session         the session that executes the query.
     * @param queryImpl       the query impl.
     * @param query           the lucene query.
     * @param orderProps      name of the properties for sort order.
     * @param orderSpecs      the order specs for the sort order properties.
     *                        <code>true</code> indicates ascending order,
     *                        <code>false</code> indicates descending.
     * @param orderFuncs      functions for the properties for sort order. 
     * @param resultFetchHint a hint on how many results should be fetched.  @return the query hits.
     * @throws IOException if an error occurs while searching the index.
     */
public MultiColumnQueryHits executeQuery(SessionImpl session, AbstractQueryImpl queryImpl, Query query, Path[] orderProps, boolean[] orderSpecs, String[] orderFuncs, long resultFetchHint) throws IOException {
    checkOpen();
    Sort sort = new Sort(createSortFields(orderProps, orderSpecs, orderFuncs));
    final IndexReader reader = getIndexReader(queryImpl.needsSystemTree());
    JackrabbitIndexSearcher searcher = new JackrabbitIndexSearcher(session, reader, getContext().getItemStateManager());
    searcher.setSimilarity(getSimilarity());
    return new FilterMultiColumnQueryHits(searcher.execute(query, sort, resultFetchHint, QueryImpl.DEFAULT_SELECTOR_NAME)) {

        public void close() throws IOException {
            try {
                super.close();
            } finally {
                Util.closeOrRelease(reader);
            }
        }
    };
}
Also used : IndexReader(org.apache.lucene.index.IndexReader) Sort(org.apache.lucene.search.Sort)

Example 24 with Sort

use of org.apache.lucene.search.Sort in project lucene-solr by apache.

the class TestBackwardsCompatibility method testCreateSortedIndex.

// ant test -Dtestcase=TestBackwardsCompatibility -Dtestmethod=testCreateSortedIndex -Dtests.codec=default -Dtests.useSecurityManager=false -Dtests.bwcdir=/tmp/sorted
public void testCreateSortedIndex() throws Exception {
    Path indexDir = getIndexDir().resolve("sorted");
    Files.deleteIfExists(indexDir);
    Directory dir = newFSDirectory(indexDir);
    LogByteSizeMergePolicy mp = new LogByteSizeMergePolicy();
    mp.setNoCFSRatio(1.0);
    mp.setMaxCFSSegmentSizeMB(Double.POSITIVE_INFINITY);
    MockAnalyzer analyzer = new MockAnalyzer(random());
    analyzer.setMaxTokenLength(TestUtil.nextInt(random(), 1, IndexWriter.MAX_TERM_LENGTH));
    // TODO: remove randomness
    IndexWriterConfig conf = new IndexWriterConfig(analyzer);
    conf.setMergePolicy(mp);
    conf.setUseCompoundFile(false);
    conf.setIndexSort(new Sort(new SortField("dateDV", SortField.Type.LONG, true)));
    IndexWriter writer = new IndexWriter(dir, conf);
    LineFileDocs docs = new LineFileDocs(random());
    SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd", Locale.ROOT);
    parser.setTimeZone(TimeZone.getTimeZone("UTC"));
    ParsePosition position = new ParsePosition(0);
    Field dateDVField = null;
    for (int i = 0; i < 50; i++) {
        Document doc = docs.nextDoc();
        String dateString = doc.get("date");
        position.setIndex(0);
        Date date = parser.parse(dateString, position);
        if (position.getErrorIndex() != -1) {
            throw new AssertionError("failed to parse \"" + dateString + "\" as date");
        }
        if (position.getIndex() != dateString.length()) {
            throw new AssertionError("failed to parse \"" + dateString + "\" as date");
        }
        if (dateDVField == null) {
            dateDVField = new NumericDocValuesField("dateDV", 0l);
            doc.add(dateDVField);
        }
        dateDVField.setLongValue(date.getTime());
        if (i == 250) {
            writer.commit();
        }
        writer.addDocument(doc);
    }
    writer.forceMerge(1);
    writer.close();
    dir.close();
}
Also used : Path(java.nio.file.Path) SortField(org.apache.lucene.search.SortField) Document(org.apache.lucene.document.Document) BinaryPoint(org.apache.lucene.document.BinaryPoint) DoublePoint(org.apache.lucene.document.DoublePoint) LongPoint(org.apache.lucene.document.LongPoint) IntPoint(org.apache.lucene.document.IntPoint) FloatPoint(org.apache.lucene.document.FloatPoint) Date(java.util.Date) SortedNumericDocValuesField(org.apache.lucene.document.SortedNumericDocValuesField) SortField(org.apache.lucene.search.SortField) NumericDocValuesField(org.apache.lucene.document.NumericDocValuesField) SortedSetDocValuesField(org.apache.lucene.document.SortedSetDocValuesField) BinaryDocValuesField(org.apache.lucene.document.BinaryDocValuesField) SortedDocValuesField(org.apache.lucene.document.SortedDocValuesField) StringField(org.apache.lucene.document.StringField) DoubleDocValuesField(org.apache.lucene.document.DoubleDocValuesField) FloatDocValuesField(org.apache.lucene.document.FloatDocValuesField) Field(org.apache.lucene.document.Field) TextField(org.apache.lucene.document.TextField) MockAnalyzer(org.apache.lucene.analysis.MockAnalyzer) SortedNumericDocValuesField(org.apache.lucene.document.SortedNumericDocValuesField) NumericDocValuesField(org.apache.lucene.document.NumericDocValuesField) Sort(org.apache.lucene.search.Sort) SimpleDateFormat(java.text.SimpleDateFormat) Directory(org.apache.lucene.store.Directory) RAMDirectory(org.apache.lucene.store.RAMDirectory) FSDirectory(org.apache.lucene.store.FSDirectory) SimpleFSDirectory(org.apache.lucene.store.SimpleFSDirectory) NIOFSDirectory(org.apache.lucene.store.NIOFSDirectory) LineFileDocs(org.apache.lucene.util.LineFileDocs) ParsePosition(java.text.ParsePosition)

Example 25 with Sort

use of org.apache.lucene.search.Sort in project lucene-solr by apache.

the class DefaultIndexingChain method maybeSortSegment.

private Sorter.DocMap maybeSortSegment(SegmentWriteState state) throws IOException {
    Sort indexSort = state.segmentInfo.getIndexSort();
    if (indexSort == null) {
        return null;
    }
    List<Sorter.DocComparator> comparators = new ArrayList<>();
    for (int i = 0; i < indexSort.getSort().length; i++) {
        SortField sortField = indexSort.getSort()[i];
        PerField perField = getPerField(sortField.getField());
        if (perField != null && perField.docValuesWriter != null && finishedDocValues.contains(perField.fieldInfo.name) == false) {
            perField.docValuesWriter.finish(state.segmentInfo.maxDoc());
            Sorter.DocComparator cmp = perField.docValuesWriter.getDocComparator(state.segmentInfo.maxDoc(), sortField);
            comparators.add(cmp);
            finishedDocValues.add(perField.fieldInfo.name);
        } else {
        // safe to ignore, sort field with no values or already seen before
        }
    }
    Sorter sorter = new Sorter(indexSort);
    // returns null if the documents are already sorted
    return sorter.sort(state.segmentInfo.maxDoc(), comparators.toArray(new Sorter.DocComparator[comparators.size()]));
}
Also used : ArrayList(java.util.ArrayList) Sort(org.apache.lucene.search.Sort) SortField(org.apache.lucene.search.SortField)

Aggregations

Sort (org.apache.lucene.search.Sort)242 SortField (org.apache.lucene.search.SortField)180 Document (org.apache.lucene.document.Document)139 Directory (org.apache.lucene.store.Directory)129 IndexSearcher (org.apache.lucene.search.IndexSearcher)108 TopDocs (org.apache.lucene.search.TopDocs)92 MatchAllDocsQuery (org.apache.lucene.search.MatchAllDocsQuery)85 IndexReader (org.apache.lucene.index.IndexReader)72 RandomIndexWriter (org.apache.lucene.index.RandomIndexWriter)72 MockAnalyzer (org.apache.lucene.analysis.MockAnalyzer)61 SortedNumericSortField (org.apache.lucene.search.SortedNumericSortField)56 SortedSetSortField (org.apache.lucene.search.SortedSetSortField)51 TermQuery (org.apache.lucene.search.TermQuery)49 NumericDocValuesField (org.apache.lucene.document.NumericDocValuesField)42 Query (org.apache.lucene.search.Query)40 ArrayList (java.util.ArrayList)37 Term (org.apache.lucene.index.Term)36 SortedNumericDocValuesField (org.apache.lucene.document.SortedNumericDocValuesField)35 BytesRef (org.apache.lucene.util.BytesRef)32 TopFieldDocs (org.apache.lucene.search.TopFieldDocs)30