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

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

Introduction

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

Prototype

Sort RELEVANCE

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

Click Source Link

Document

Represents sorting by computed relevance.

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,/* ww  w  .ja v  a 2  s  . co  m*/
            new Sort(new SortField[] { SortField.FIELD_SCORE, new SortField("category", SortField.STRING) }));
    directory.close();
}

From source file:br.ufba.dcc.mestrado.computacao.repository.impl.ProjectRepositoryImpl.java

private void configureRelevanceSort(FullTextQuery fullTextQuery) {
    boolean reverse = true;
    SortField userContSortField = new SortField(SearchFieldsEnum.projectUserCount.fieldName(),
            SortField.Type.LONG, reverse);
    SortField ratingContSortField = new SortField(SearchFieldsEnum.projectRatingCount.fieldName(),
            SortField.Type.LONG, reverse);
    SortField reviewContSortField = new SortField(SearchFieldsEnum.projectReviewCount.fieldName(),
            SortField.Type.LONG, reverse);

    List<SortField> sortFieldList = new LinkedList<>();
    sortFieldList.addAll(Arrays.asList(Sort.RELEVANCE.getSort()));
    sortFieldList.add(userContSortField);
    sortFieldList.add(reviewContSortField);
    sortFieldList.add(ratingContSortField);

    Sort sort = new Sort(userContSortField);
    fullTextQuery.setSort(sort);//from  ww  w  .j a  v  a  2  s .  c o m
}

From source file:com.amalto.core.storage.hibernate.FullTextQueryHandler.java

License:Open Source License

@Override
public StorageResults visit(Select select) {
    // TMDM-4654: Checks if entity has a composite PK.
    Set<ComplexTypeMetadata> compositeKeyTypes = new HashSet<ComplexTypeMetadata>();
    // TMDM-7496: Search should include references to reused types
    Collection<ComplexTypeMetadata> types = new HashSet<ComplexTypeMetadata>(
            select.accept(new SearchTransitiveClosure(storage)));
    for (ComplexTypeMetadata type : types) {
        if (type.getKeyFields().size() > 1) {
            compositeKeyTypes.add(type);
        }/*  w w  w.  j  a v  a 2s .c  o  m*/
    }
    if (!compositeKeyTypes.isEmpty()) {
        StringBuilder message = new StringBuilder();
        Iterator it = compositeKeyTypes.iterator();
        while (it.hasNext()) {
            ComplexTypeMetadata compositeKeyType = (ComplexTypeMetadata) it.next();
            message.append(compositeKeyType.getName());
            if (it.hasNext()) {
                message.append(',');
            }
        }
        throw new FullTextQueryCompositeKeyException(message.toString());
    }
    // Removes Joins and joined fields.
    List<Join> joins = select.getJoins();
    if (!joins.isEmpty()) {
        Set<ComplexTypeMetadata> joinedTypes = new HashSet<ComplexTypeMetadata>();
        for (Join join : joins) {
            joinedTypes.add(join.getRightField().getFieldMetadata().getContainingType());
        }
        for (ComplexTypeMetadata joinedType : joinedTypes) {
            types.remove(joinedType);
        }
        List<TypedExpression> filteredFields = new LinkedList<TypedExpression>();
        for (TypedExpression expression : select.getSelectedFields()) {
            if (expression instanceof Field) {
                FieldMetadata fieldMetadata = ((Field) expression).getFieldMetadata();
                if (joinedTypes.contains(fieldMetadata.getContainingType())) {
                    TypeMapping mapping = mappings.getMappingFromDatabase(fieldMetadata.getContainingType());
                    filteredFields.add(new Alias(new StringConstant(StringUtils.EMPTY),
                            mapping.getUser(fieldMetadata).getName()));
                } else {
                    filteredFields.add(expression);
                }
            } else {
                filteredFields.add(expression);
            }
        }
        selectedFields.clear();
        selectedFields.addAll(filteredFields);
    }
    // Handle condition
    Condition condition = select.getCondition();
    if (condition == null) {
        throw new IllegalArgumentException("Expected a condition in select clause but got 0.");
    }
    // Create Lucene query (concatenates all sub queries together).
    FullTextSession fullTextSession = Search.getFullTextSession(session);
    Query parsedQuery = select.getCondition().accept(new LuceneQueryGenerator(types));
    // Create Hibernate Search query
    Set<Class> classes = new HashSet<Class>();
    for (ComplexTypeMetadata type : types) {
        String className = ClassCreator.getClassName(type.getName());
        try {
            ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
            classes.add(contextClassLoader.loadClass(className));
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Could not find class '" + className + "'.", e);
        }
    }
    FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(parsedQuery,
            classes.toArray(new Class<?>[classes.size()]));
    // Very important to leave this null (would disable ability to search across different types)
    fullTextQuery.setCriteriaQuery(null);
    fullTextQuery.setSort(Sort.RELEVANCE); // Default sort (if no order by specified).
    query = EntityFinder.wrap(fullTextQuery, (HibernateStorage) storage, session, select.getTypes()); // ensures only MDM entity objects are returned.
    // Order by
    for (OrderBy current : select.getOrderBy()) {
        current.accept(this);
    }
    // Paging
    Paging paging = select.getPaging();
    paging.accept(this);
    pageSize = paging.getLimit();
    boolean hasPaging = pageSize < Integer.MAX_VALUE;
    if (!hasPaging) {
        return createResults(query.scroll(ScrollMode.FORWARD_ONLY));
    } else {
        return createResults(query.list());
    }
}

From source file:com.bdaum.zoom.lal.internal.lucene.Lucene.java

License:Open Source License

@Override
public ISearchHits search(File indexPath, TextSearchOptions_type options) throws IOException, ParseException {
    Object readerToken = null;/*from  w ww. j ava  2 s . c o  m*/
    try {
        if (indexPath != null) {
            readerToken = getIndexReaderToken(indexPath);
            if (readerToken != null) {
                IndexReader indexReader = readerMap.get(readerToken);
                if (indexReader != null) {
                    IndexSearcher searcher = searcherMap.get(readerToken);
                    if (searcher == null)
                        searcherMap.put(readerToken, searcher = new IndexSearcher(indexReader));
                    return new SearchHits(indexReader,
                            performSearch(searcher,
                                    LireActivator.getDefault().parseQuery(options.getQueryString()),
                                    options.getMaxResults(), Sort.RELEVANCE, true, true));
                }
            }
        }
        return null;
    } finally {
        if (readerToken != null)
            releaseIndexReader(indexPath, readerToken);
    }
}

From source file:com.codeReading.core.opengrok.SearchHelper.java

License:Open Source License

/**
 * Create the searcher to use wrt. to currently set parameters and the given
 * projects. Does not produce any {@link #redirect} link. It also does
 * nothing if {@link #redirect} or {@link #errorMsg} have a
 * none-{@code null} value. <p> Parameters which should be populated/set at
 * this time: <ul> <li>{@link #builder}</li> <li>{@link #dataRoot}</li>
 * <li>{@link #order} (falls back to relevance if unset)</li>
 * <li>{@link #parallel} (default: false)</li> </ul> Populates/sets: <ul>
 * <li>{@link #query}</li> <li>{@link #searcher}</li> <li>{@link #sort}</li>
 * <li>{@link #projects}</li> <li>{@link #errorMsg} if an error occurs</li>
 * </ul>/*from  w  w w .j  av  a2  s  . c o  m*/
 *
 * @param projects project to use query. If empty, a none-project opengrok
 * setup is assumed (i.e. DATA_ROOT/index will be used instead of possible
 * multiple DATA_ROOT/$project/index).
 * @return this instance
 */
public SearchHelper prepareExec(SortedSet<String> projects) {
    if (redirect != null || errorMsg != null) {
        return this;
    }
    // the Query created by the QueryBuilder
    try {
        indexDir = new File(dataRoot, "index");
        query = builder.build();
        if (projects == null) {
            errorMsg = "No project selected!";
            return this;
        }
        this.projects = projects;
        if (projects.isEmpty()) {
            //no project setup
            FSDirectory dir = FSDirectory.open(indexDir);
            searcher = new IndexSearcher(DirectoryReader.open(dir));
        } else if (projects.size() == 1) {
            // just 1 project selected
            FSDirectory dir = FSDirectory.open(new File(indexDir, projects.first()));
            searcher = new IndexSearcher(DirectoryReader.open(dir));
        } else {
            //more projects                                
            IndexReader[] subreaders = new IndexReader[projects.size()];
            int ii = 0;
            //TODO might need to rewrite to Project instead of
            // String , need changes in projects.jspf too
            for (String proj : projects) {
                FSDirectory dir = FSDirectory.open(new File(indexDir, proj));
                subreaders[ii++] = DirectoryReader.open(dir);
            }
            MultiReader searchables = new MultiReader(subreaders, true);
            if (parallel) {
                int noThreads = 2 + (2 * Runtime.getRuntime().availableProcessors()); //TODO there might be a better way for counting this
                executor = Executors.newFixedThreadPool(noThreads);
            }
            searcher = parallel ? new IndexSearcher(searchables, executor) : new IndexSearcher(searchables);
        }
        // TODO check if below is somehow reusing sessions so we don't
        // requery again and again, I guess 2min timeout sessions could be
        // usefull, since you click on the next page within 2mins, if not,
        // then wait ;)
        switch (order) {
        case LASTMODIFIED:
            sort = new Sort(new SortField("date", SortField.Type.STRING, true));
            break;
        case BY_PATH:
            sort = new Sort(new SortField("fullpath", SortField.Type.STRING));
            break;
        default:
            sort = Sort.RELEVANCE;
            break;
        }
        checker = new DirectSpellChecker();
    } catch (ParseException e) {
        errorMsg = PARSE_ERROR_MSG + e.getMessage();
    } catch (FileNotFoundException e) {
        //          errorMsg = "Index database(s) not found: " + e.getMessage();
        errorMsg = "Index database(s) not found.";
    } catch (Exception e) {
        errorMsg = e.getMessage();
    }
    return this;
}

From source file:com.fuerve.villageelder.actions.results.SearchResultItemTest.java

License:Apache License

private TopFieldCollector getDummyCollector() throws Exception {
    TopFieldCollector collector = TopFieldCollector.create(Sort.RELEVANCE, 100, true, false, false, false);

    return collector;
}

From source file:com.fuerve.villageelder.search.SearchTest.java

License:Apache License

/**
 * Test method for {@link com.fuerve.villageelder.search.Search#Search(org.apache.lucene.search.Query, org.apache.lucene.search.Sort)}.
 *///from  w w w  .j av a 2 s  .com
@Test
@SuppressWarnings({ "unchecked", "unused" })
public final void testSearchQuerySort() throws Exception {
    // Constants
    Field defaultSortField = Search.class.getDeclaredField("DEFAULT_SORT");
    Field defaultFacetsField = Search.class.getDeclaredField("DEFAULT_FACETS");
    Field defaultFacetStringsField = Search.class.getDeclaredField("DEFAULT_FACET_STRINGS");
    Field defaultAnalyzerField = Search.class.getDeclaredField("DEFAULT_ANALYZER");
    Field defaultHitsField = Search.class.getDeclaredField("DEFAULT_HITS");

    defaultSortField.setAccessible(true);
    defaultFacetsField.setAccessible(true);
    defaultFacetStringsField.setAccessible(true);
    defaultAnalyzerField.setAccessible(true);
    defaultHitsField.setAccessible(true);

    final Sort defaultSort = (Sort) defaultSortField.get(null);
    final List<FacetRequest> defaultFacets = (List<FacetRequest>) defaultFacetsField.get(null);
    final Map<String, Integer> defaultFacetStrings = (Map<String, Integer>) defaultFacetStringsField.get(null);
    final Analyzer defaultAnalyzer = (Analyzer) defaultAnalyzerField.get(null);
    final int defaultHits = defaultHitsField.getInt(null);

    // Private members
    Field queryField = Search.class.getDeclaredField("query");
    Field sortField = Search.class.getDeclaredField("sort");
    Field facetsField = Search.class.getDeclaredField("facets");

    queryField.setAccessible(true);
    sortField.setAccessible(true);
    facetsField.setAccessible(true);

    // Test setup
    QueryParser parser = getQueryParser();
    Query queryExpected = parser.parse("test:foo");
    Sort sortExpected = Sort.RELEVANCE;

    Search target = new Search(queryExpected, sortExpected);

    // Gather fields
    Query queryActual = (Query) queryField.get(target);
    Sort sortActual = (Sort) sortField.get(target);
    List<FacetRequest> facetsActual = (List<FacetRequest>) facetsField.get(target);

    // Test
    assertEquals(queryExpected, queryActual);
    assertEquals(sortExpected, sortActual);
    assertEquals(defaultFacets, facetsActual);
}

From source file:com.fuerve.villageelder.search.SearchTest.java

License:Apache License

/**
 * Test method for {@link com.fuerve.villageelder.search.Search#Search(org.apache.lucene.search.Query, java.util.List, org.apache.lucene.search.Sort)}.
 *//*from  w ww  .  j a v  a2 s.c o  m*/
@Test
@SuppressWarnings({ "unchecked", "unused" })
public final void testSearchQueryListOfFacetRequestSort() throws Exception {
    // Constants
    Field defaultSortField = Search.class.getDeclaredField("DEFAULT_SORT");
    Field defaultFacetsField = Search.class.getDeclaredField("DEFAULT_FACETS");
    Field defaultFacetStringsField = Search.class.getDeclaredField("DEFAULT_FACET_STRINGS");
    Field defaultAnalyzerField = Search.class.getDeclaredField("DEFAULT_ANALYZER");
    Field defaultHitsField = Search.class.getDeclaredField("DEFAULT_HITS");

    defaultSortField.setAccessible(true);
    defaultFacetsField.setAccessible(true);
    defaultFacetStringsField.setAccessible(true);
    defaultAnalyzerField.setAccessible(true);
    defaultHitsField.setAccessible(true);

    final Sort defaultSort = (Sort) defaultSortField.get(null);
    final List<FacetRequest> defaultFacets = (List<FacetRequest>) defaultFacetsField.get(null);
    final Map<String, Integer> defaultFacetStrings = (Map<String, Integer>) defaultFacetStringsField.get(null);
    final Analyzer defaultAnalyzer = (Analyzer) defaultAnalyzerField.get(null);
    final int defaultHits = defaultHitsField.getInt(null);

    // Private members
    Field queryField = Search.class.getDeclaredField("query");
    Field sortField = Search.class.getDeclaredField("sort");
    Field facetsField = Search.class.getDeclaredField("facets");

    queryField.setAccessible(true);
    sortField.setAccessible(true);
    facetsField.setAccessible(true);

    // Test setup
    QueryParser parser = getQueryParser();
    Query queryExpected = parser.parse("test:foo");
    List<FacetRequest> facetsExpected = new ArrayList<FacetRequest>();
    Sort sortExpected = Sort.RELEVANCE;

    Search target = new Search(queryExpected, facetsExpected, sortExpected);

    // Gather fields
    Query queryActual = (Query) queryField.get(target);
    Sort sortActual = (Sort) sortField.get(target);
    List<FacetRequest> facetsActual = (List<FacetRequest>) facetsField.get(target);

    // Test
    assertEquals(queryExpected, queryActual);
    assertEquals(sortExpected, sortActual);
    assertEquals(facetsExpected, facetsActual);
}

From source file:com.fuerve.villageelder.search.SearchTest.java

License:Apache License

/**
 * Test method for {@link com.fuerve.villageelder.search.Search#Search(java.lang.String, org.apache.lucene.search.Sort)}.
 *//* w  ww.  j  av  a  2 s .  c o m*/
@Test
@SuppressWarnings({ "unchecked", "unused" })
public final void testSearchStringSort() throws Exception {
    // Constants
    Field defaultSortField = Search.class.getDeclaredField("DEFAULT_SORT");
    Field defaultFacetsField = Search.class.getDeclaredField("DEFAULT_FACETS");
    Field defaultFacetStringsField = Search.class.getDeclaredField("DEFAULT_FACET_STRINGS");
    Field defaultAnalyzerField = Search.class.getDeclaredField("DEFAULT_ANALYZER");
    Field defaultHitsField = Search.class.getDeclaredField("DEFAULT_HITS");

    defaultSortField.setAccessible(true);
    defaultFacetsField.setAccessible(true);
    defaultFacetStringsField.setAccessible(true);
    defaultAnalyzerField.setAccessible(true);
    defaultHitsField.setAccessible(true);

    final Sort defaultSort = (Sort) defaultSortField.get(null);
    final List<FacetRequest> defaultFacets = (List<FacetRequest>) defaultFacetsField.get(null);
    final Map<String, Integer> defaultFacetStrings = (Map<String, Integer>) defaultFacetStringsField.get(null);
    final Analyzer defaultAnalyzer = (Analyzer) defaultAnalyzerField.get(null);
    final int defaultHits = defaultHitsField.getInt(null);

    // Private members
    Field queryField = Search.class.getDeclaredField("query");
    Field sortField = Search.class.getDeclaredField("sort");
    Field facetsField = Search.class.getDeclaredField("facets");

    queryField.setAccessible(true);
    sortField.setAccessible(true);
    facetsField.setAccessible(true);

    // Test setup
    QueryParser parser = getQueryParser();
    String queryExpected = "test:foo";
    Sort sortExpected = Sort.RELEVANCE;

    Search target = new Search(queryExpected, sortExpected);

    // Gather fields
    Query queryActual = (Query) queryField.get(target);
    Sort sortActual = (Sort) sortField.get(target);
    List<FacetRequest> facetsActual = (List<FacetRequest>) facetsField.get(target);

    // Test
    assertEquals(queryExpected, queryActual.toString());
    assertEquals(sortExpected, sortActual);
    assertEquals(defaultFacets, facetsActual);
}

From source file:com.fuerve.villageelder.search.SearchTest.java

License:Apache License

/**
 * Test method for {@link com.fuerve.villageelder.search.Search#Search(java.lang.String, java.util.Map, org.apache.lucene.search.Sort)}.
 *///w w w. j a v  a  2s  .c o  m
@Test
@SuppressWarnings({ "unchecked", "unused" })
public final void testSearchStringMapOfStringIntegerSort() throws Exception {
    // Constants
    Field defaultSortField = Search.class.getDeclaredField("DEFAULT_SORT");
    Field defaultFacetsField = Search.class.getDeclaredField("DEFAULT_FACETS");
    Field defaultFacetStringsField = Search.class.getDeclaredField("DEFAULT_FACET_STRINGS");
    Field defaultAnalyzerField = Search.class.getDeclaredField("DEFAULT_ANALYZER");
    Field defaultHitsField = Search.class.getDeclaredField("DEFAULT_HITS");

    defaultSortField.setAccessible(true);
    defaultFacetsField.setAccessible(true);
    defaultFacetStringsField.setAccessible(true);
    defaultAnalyzerField.setAccessible(true);
    defaultHitsField.setAccessible(true);

    final Sort defaultSort = (Sort) defaultSortField.get(null);
    final List<FacetRequest> defaultFacets = (List<FacetRequest>) defaultFacetsField.get(null);
    final Map<String, Integer> defaultFacetStrings = (Map<String, Integer>) defaultFacetStringsField.get(null);
    final Analyzer defaultAnalyzer = (Analyzer) defaultAnalyzerField.get(null);
    final int defaultHits = defaultHitsField.getInt(null);

    // Private members
    Field queryField = Search.class.getDeclaredField("query");
    Field sortField = Search.class.getDeclaredField("sort");
    Field facetsField = Search.class.getDeclaredField("facets");

    queryField.setAccessible(true);
    sortField.setAccessible(true);
    facetsField.setAccessible(true);

    // Test setup
    QueryParser parser = getQueryParser();
    String queryExpected = "test:foo";
    Map<String, Integer> facetsExpected = new HashMap<String, Integer>();
    Sort sortExpected = Sort.RELEVANCE;

    facetsExpected.put("testFacet", 99);

    Search target = new Search(queryExpected, facetsExpected, sortExpected);

    // Gather fields
    Query queryActual = (Query) queryField.get(target);
    Sort sortActual = (Sort) sortField.get(target);
    List<FacetRequest> facetsActual = (List<FacetRequest>) facetsField.get(target);

    // Test
    assertEquals(queryExpected, queryActual.toString());
    assertEquals(sortExpected, sortActual);
    assertEquals("testFacet", facetsActual.get(0).categoryPath.toString());
}