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:com.stratio.cassandra.lucene.index.DocumentIteratorTest.java

License:Apache License

@Test
public void testConstructorWithPageEqualsZero() throws IOException {
    IndexWriterConfig iwConfig = new IndexWriterConfig(new AnalyzerMock());
    SearcherManager searcherManager = new SearcherManager(new IndexWriterMock(new DirectoryMock(), iwConfig),
            true, null);/*from  w  ww .  j a v  a  2  s .c o m*/
    DocumentIterator docIterator = new DocumentIterator(searcherManager, new Sort(), null, new QueryMock(),
            new Sort(), 0, new HashSet<>());

    assertEquals("document Iterator page is invalid", 1, docIterator.page);
}

From source file:com.stratio.cassandra.lucene.index.DocumentIteratorTest.java

License:Apache License

@Test
public void testConstructorWithPageEqualsOne() throws IOException {
    IndexWriterConfig iwConfig = new IndexWriterConfig(new AnalyzerMock());
    SearcherManager searcherManager = new SearcherManager(new IndexWriterMock(new DirectoryMock(), iwConfig),
            true, null);/*from   w  w w  .  j  a v  a  2  s . com*/
    DocumentIterator docIterator = new DocumentIterator(searcherManager, new Sort(), null, new QueryMock(),
            new Sort(), 1, new HashSet<>());

    assertEquals("document Iterator page is invalid", 2, docIterator.page);
}

From source file:com.stratio.cassandra.lucene.index.DocumentIteratorTest.java

License:Apache License

@Test
public void testConstructorWithPageEqualsMaxValue() throws IOException {
    IndexWriterConfig iwConfig = new IndexWriterConfig(new AnalyzerMock());
    SearcherManager searcherManager = new SearcherManager(new IndexWriterMock(new DirectoryMock(), iwConfig),
            true, null);//from  w  w  w .  j  a  v  a  2s  . c o m
    DocumentIterator docIterator = new DocumentIterator(searcherManager, new Sort(), null, new QueryMock(),
            new Sort(), DocumentIterator.MAX_PAGE_SIZE, new HashSet<>());

    assertEquals("document Iterator page is invalid", DocumentIterator.MAX_PAGE_SIZE + 1, docIterator.page);
}

From source file:com.stratio.cassandra.lucene.index.DocumentIteratorTest.java

License:Apache License

@Test
public void testConstructorWithPageOverMaxValue() throws IOException {
    IndexWriterConfig iwConfig = new IndexWriterConfig(new AnalyzerMock());
    SearcherManager searcherManager = new SearcherManager(new IndexWriterMock(new DirectoryMock(), iwConfig),
            true, null);// ww w .j  a  va 2s  .c o m
    DocumentIterator docIterator = new DocumentIterator(searcherManager, new Sort(), null, new QueryMock(),
            new Sort(), 10000000, new HashSet<>());

    assertEquals("document Iterator page is invalid", DocumentIterator.MAX_PAGE_SIZE + 1, docIterator.page);
}

From source file:de.uni_koeln.spinfo.maalr.lucene.core.Dictionary.java

License:Apache License

public QueryResult query(MaalrQuery maalrQuery) throws InvalidQueryException, NoIndexAvailableException,
        BrokenIndexException, IOException, InvalidTokenOffsetsException {
    long start = System.nanoTime();
    validateQuery(maalrQuery);/*  w ww . ja va 2  s .  c  o m*/
    int pageSize = maalrQuery.getPageSize();
    long s1 = System.nanoTime();
    Query query = indexManager.buildQuery(maalrQuery);
    TopDocs docs = null;
    // TODO: Make this configurable!
    Sort sort = new Sort();
    String[] items = null;
    if (maalrQuery.getValue("language") != null
            && maalrQuery.getValue("language").equals(description.getLanguageName(false))) {
        items = description.getSortList(false);
    } else {
        items = description.getSortList(true);
    }
    SortField[] fields = new SortField[items.length + 1];
    fields[0] = SortField.FIELD_SCORE;
    for (int i = 0; i < items.length; i++) {
        String item = items[i];
        fields[i + 1] = new SortField(item, sortTypes.get(item));
    }
    sort.setSort(fields);
    QueryResult result = null;
    int pageNr = maalrQuery.getPageNr();
    long e1 = System.nanoTime();
    try {
        long s2 = System.nanoTime();
        docs = indexProvider.getSearcher().search(query, pageSize * (pageNr + 1), sort);
        long e2 = System.nanoTime();
        result = toQueryResult(docs, pageSize * pageNr, maalrQuery.getPageSize());
        if (logger.isDebugEnabled()) {
            logger.debug("Time to build query: " + (e1 - s1) / 1000000 + ", Time to execute query: "
                    + ((e2 - s2) / 1000000));
        }
    } catch (IOException e) {
        throw new BrokenIndexException("Failed to access index", e);
    }
    long end = System.nanoTime();
    double time = (end - start) / 1000000D;
    // Warn if query takes more than 100 ms.
    if (time > 100) {
        logger.warn("Slow query: " + formatter.format(time) + " ms for " + maalrQuery);
    } else if (logger.isDebugEnabled()) {
        logger.debug("Processed query in " + formatter.format(time) + " ms :" + maalrQuery);
    }
    return result;
}

From source file:net.conquiris.lucene.search.SortBuilder.java

License:Apache License

/** Creates the sort specification. */
@Override//from   w w w.j ava2 s.c  om
public Sort build() {
    if (fields.isEmpty()) {
        return new Sort();
    } else {
        SortField[] array = new SortField[fields.size()];
        fields.toArray(array);
        return new Sort(array);
    }
}

From source file:org.ala.dao.TaxonConceptSHDaoImpl.java

License:Open Source License

/**
 * Perform Lucene search with params for sorting and paging
 * //from  w  w  w .  j a  v  a2s.c  o  m
 * @param searchQuery
 * @param startIndex
 * @param pageSize
 * @param sortDirection
 * @param sortField
 * @return
 * @throws IOException
 * @throws Exception
 */
private SearchResultsDTO sortPageSearch(Query searchQuery, Integer startIndex, Integer pageSize,
        String sortField, String sortDirection) throws IOException, Exception {
    boolean direction = false;

    if (sortDirection != null && !sortDirection.isEmpty() && sortDirection.equalsIgnoreCase("desc")) {
        direction = true;
    }

    Sort sort = new Sort();

    if (sortField != null && !sortField.isEmpty() && !sortField.equalsIgnoreCase("score")) {
        SortField sf = new SortField(sortField, SortField.Type.STRING, direction);
        sort.setSort(sf);
    } else {
        sort = Sort.RELEVANCE;
    }

    TopDocs topDocs = getTcIdxSearcher().search(searchQuery, null, startIndex + pageSize, sort); // TODO ues sortField here
    logger.debug("Total hits: " + topDocs.totalHits);
    List<SearchTaxonConceptDTO> tcs = new ArrayList<SearchTaxonConceptDTO>();

    for (int i = 0; i < topDocs.scoreDocs.length; i++) {
        if (i >= startIndex) {
            ScoreDoc scoreDoc = topDocs.scoreDocs[i];
            Document doc = getTcIdxSearcher().doc(scoreDoc.doc);
            tcs.add(createTaxonConceptFromIndex(doc, scoreDoc.score));
        }
    }

    SearchResultsDTO searchResults = new SearchResultsDTO(tcs);
    searchResults.setTotalRecords(topDocs.totalHits);
    searchResults.setStartIndex(startIndex);
    searchResults.setStatus("OK");
    searchResults.setSort(sortField);
    searchResults.setDir(sortDirection);
    searchResults.setQuery(searchQuery.toString());

    return searchResults;
}

From source file:org.apache.jackrabbit.core.query.lucene.JackrabbitIndexSearcher.java

License:Apache License

/**
 * Evaluates the query and returns the hits that match the query.
 *
 * @param query           the query to execute.
 * @return the query hits.//w w  w.ja v a 2  s  .c o m
 * @throws IOException if an error occurs while executing the query.
 */
public QueryHits evaluate(Query query) throws IOException {
    return evaluate(query, new Sort(), Integer.MAX_VALUE);
}

From source file:org.apache.jackrabbit.core.query.lucene.join.JahiaQueryEngine.java

License:Open Source License

/**
 * Override QueryEngine.execute()//from w w  w  . ja v  a 2  s .com
 */
@Override
protected QueryResult execute(Column[] columns, Selector selector, Constraint constraint, Ordering[] orderings,
        long offset, long limit, int printIndentation) throws RepositoryException {
    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 (nativeSort) {
        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 = !nativeSort && (orderings != null && orderings.length > 0);

    List<Row> rowsList = null;
    try {
        rowsList = lqf.execute(columnMap, selector, constraint, sort, externalSort, offset, limit);
    } catch (IOException e) {
        throw new RepositoryException("Failed to access the query index", e);
    }
    // Added by jahia
    QueryResult result;
    if (rowsList.size() > 0 && rowsList.get(0) instanceof FacetRow) {
        FacetRow facets = (FacetRow) rowsList.remove(0);
        RowIterator rows = new RowIteratorAdapter(rowsList);
        return new FacetedQueryResult(columnNames, selectorNames, rows, facets);
    } else {
        RowIterator rows = new RowIteratorAdapter(rowsList);
        result = new JahiaSimpleQueryResult(columnNames, selectorNames, rows);
        if (nativeSort) {
            return result;
        }
        long timeSort = System.currentTimeMillis();
        QueryResult r = sort(result, orderings, evaluator, offset, limit);
        if (log.isDebugEnabled()) {
            log.debug("{}SQL2 SORT took {} ms.", genString(printIndentation),
                    System.currentTimeMillis() - timeSort);
        }
        if (r != result) {
            return new JahiaSimpleQueryResult(columnNames, selectorNames, r.getRows(),
                    limit > 0 ? result.getRows().getSize() : 0);
        }
        return result;
    }
}

From source file:org.apache.jackrabbit.core.query.lucene.join.QueryEngine.java

License:Apache License

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));
    }//from w w w  .j a  v  a2s.  c om

    // 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;
}