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:org.apache.solr.handler.component.HelloHandlerComponent.java

License:Apache License

@Override
public void prepare(ResponseBuilder rb) throws IOException {

    SolrQueryRequest req = rb.req;//from  w ww.j a  v  a2  s  . c o  m
    SolrParams params = req.getParams();
    if (!params.getBool(COMPONENT_NAME, true)) {
        return;
    }
    SolrQueryResponse rsp = rb.rsp;

    // Set field flags    
    ReturnFields returnFields = new ReturnFields(req);
    rsp.setReturnFields(returnFields);
    int flags = 0;
    if (returnFields.wantsScore()) {
        flags |= SolrIndexSearcher.GET_SCORES;
    }
    rb.setFieldFlags(flags);

    String defType = params.get(QueryParsing.DEFTYPE, QParserPlugin.DEFAULT_QTYPE);

    // get it from the response builder to give a different component a chance
    // to set it.
    String queryString = rb.getQueryString();
    if (queryString == null) {
        // this is the normal way it's set.
        queryString = params.get(CommonParams.Q);
        rb.setQueryString(queryString);
    }

    try {
        QParser parser = QParser.getParser(rb.getQueryString(), defType, req);
        Query q = parser.getQuery();
        if (q == null) {
            // normalize a null query to a query that matches nothing
            q = new BooleanQuery();
        }
        rb.setQuery(q);
        rb.setSortSpec(parser.getSort(true));
        rb.setQparser(parser);
        rb.setScoreDoc(parser.getPaging());

        String[] fqs = req.getParams().getParams(CommonParams.FQ);
        if (fqs != null && fqs.length != 0) {
            List<Query> filters = rb.getFilters();
            if (filters == null) {
                filters = new ArrayList<Query>(fqs.length);
            }
            for (String fq : fqs) {
                if (fq != null && fq.trim().length() != 0) {
                    QParser fqp = QParser.getParser(fq, null, req);
                    filters.add(fqp.getQuery());
                }
            }
            // only set the filters if they are not empty otherwise
            // fq=&someotherParam= will trigger all docs filter for every request 
            // if filter cache is disabled
            if (!filters.isEmpty()) {
                rb.setFilters(filters);
            }
        }
    } catch (ParseException e) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);
    }

    boolean grouping = params.getBool(GroupParams.GROUP, false);
    if (!grouping) {
        return;
    }

    SolrIndexSearcher.QueryCommand cmd = rb.getQueryCommand();
    SolrIndexSearcher searcher = rb.req.getSearcher();
    GroupingSpecification groupingSpec = new GroupingSpecification();
    rb.setGroupingSpec(groupingSpec);

    //TODO: move weighting of sort
    Sort groupSort = searcher.weightSort(cmd.getSort());
    if (groupSort == null) {
        groupSort = Sort.RELEVANCE;
    }

    // groupSort defaults to sort
    String groupSortStr = params.get(GroupParams.GROUP_SORT);
    //TODO: move weighting of sort
    Sort sortWithinGroup = groupSortStr == null ? groupSort
            : searcher.weightSort(QueryParsing.parseSort(groupSortStr, req));
    if (sortWithinGroup == null) {
        sortWithinGroup = Sort.RELEVANCE;
    }

    groupingSpec.setSortWithinGroup(sortWithinGroup);
    groupingSpec.setGroupSort(groupSort);

    String formatStr = params.get(GroupParams.GROUP_FORMAT, Grouping.Format.grouped.name());
    Grouping.Format responseFormat;
    try {
        responseFormat = Grouping.Format.valueOf(formatStr);
    } catch (IllegalArgumentException e) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                String.format(Locale.ROOT, "Illegal %s parameter", GroupParams.GROUP_FORMAT));
    }
    groupingSpec.setResponseFormat(responseFormat);

    groupingSpec.setFields(params.getParams(GroupParams.GROUP_FIELD));
    groupingSpec.setQueries(params.getParams(GroupParams.GROUP_QUERY));
    groupingSpec.setFunctions(params.getParams(GroupParams.GROUP_FUNC));
    groupingSpec.setGroupOffset(params.getInt(GroupParams.GROUP_OFFSET, 0));
    groupingSpec.setGroupLimit(params.getInt(GroupParams.GROUP_LIMIT, 1));
    groupingSpec.setOffset(rb.getSortSpec().getOffset());
    groupingSpec.setLimit(rb.getSortSpec().getCount());
    groupingSpec.setIncludeGroupCount(params.getBool(GroupParams.GROUP_TOTAL_COUNT, false));
    groupingSpec.setMain(params.getBool(GroupParams.GROUP_MAIN, false));
    groupingSpec.setNeedScore((cmd.getFlags() & SolrIndexSearcher.GET_SCORES) != 0);
    groupingSpec.setTruncateGroups(params.getBool(GroupParams.GROUP_TRUNCATE, false));
}

From source file:org.apache.solr.handler.component.QueryComponent.java

License:Apache License

@Override
public void prepare(ResponseBuilder rb) throws IOException {

    SolrQueryRequest req = rb.req;/*from w  w w .  j  av a2 s .c  o  m*/
    SolrParams params = req.getParams();
    if (!params.getBool(COMPONENT_NAME, true)) {
        return;
    }
    SolrQueryResponse rsp = rb.rsp;

    // Set field flags    
    ReturnFields returnFields = new SolrReturnFields(req);
    rsp.setReturnFields(returnFields);
    int flags = 0;
    if (returnFields.wantsScore()) {
        flags |= SolrIndexSearcher.GET_SCORES;
    }
    rb.setFieldFlags(flags);

    String defType = params.get(QueryParsing.DEFTYPE, QParserPlugin.DEFAULT_QTYPE);

    // get it from the response builder to give a different component a chance
    // to set it.
    String queryString = rb.getQueryString();
    if (queryString == null) {
        // this is the normal way it's set.
        queryString = params.get(CommonParams.Q);
        rb.setQueryString(queryString);
    }

    try {
        QParser parser = QParser.getParser(rb.getQueryString(), defType, req);
        Query q = parser.getQuery();
        if (q == null) {
            // normalize a null query to a query that matches nothing
            q = new BooleanQuery();
        }
        rb.setQuery(q);
        rb.setSortSpec(parser.getSort(true));
        rb.setQparser(parser);
        rb.setScoreDoc(parser.getPaging());

        String[] fqs = req.getParams().getParams(CommonParams.FQ);
        if (fqs != null && fqs.length != 0) {
            List<Query> filters = rb.getFilters();
            // if filters already exists, make a copy instead of modifying the original
            filters = filters == null ? new ArrayList<Query>(fqs.length) : new ArrayList<Query>(filters);
            for (String fq : fqs) {
                if (fq != null && fq.trim().length() != 0) {
                    QParser fqp = QParser.getParser(fq, null, req);
                    filters.add(fqp.getQuery());
                }
            }
            // only set the filters if they are not empty otherwise
            // fq=&someotherParam= will trigger all docs filter for every request 
            // if filter cache is disabled
            if (!filters.isEmpty()) {
                rb.setFilters(filters);
            }
        }
    } catch (SyntaxError e) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);
    }

    boolean grouping = params.getBool(GroupParams.GROUP, false);
    if (!grouping) {
        return;
    }

    SolrIndexSearcher.QueryCommand cmd = rb.getQueryCommand();
    SolrIndexSearcher searcher = rb.req.getSearcher();
    GroupingSpecification groupingSpec = new GroupingSpecification();
    rb.setGroupingSpec(groupingSpec);

    //TODO: move weighting of sort
    Sort groupSort = searcher.weightSort(cmd.getSort());
    if (groupSort == null) {
        groupSort = Sort.RELEVANCE;
    }

    // groupSort defaults to sort
    String groupSortStr = params.get(GroupParams.GROUP_SORT);
    //TODO: move weighting of sort
    Sort sortWithinGroup = groupSortStr == null ? groupSort
            : searcher.weightSort(QueryParsing.parseSort(groupSortStr, req));
    if (sortWithinGroup == null) {
        sortWithinGroup = Sort.RELEVANCE;
    }

    groupingSpec.setSortWithinGroup(sortWithinGroup);
    groupingSpec.setGroupSort(groupSort);

    String formatStr = params.get(GroupParams.GROUP_FORMAT, Grouping.Format.grouped.name());
    Grouping.Format responseFormat;
    try {
        responseFormat = Grouping.Format.valueOf(formatStr);
    } catch (IllegalArgumentException e) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                String.format(Locale.ROOT, "Illegal %s parameter", GroupParams.GROUP_FORMAT));
    }
    groupingSpec.setResponseFormat(responseFormat);

    groupingSpec.setFields(params.getParams(GroupParams.GROUP_FIELD));
    groupingSpec.setQueries(params.getParams(GroupParams.GROUP_QUERY));
    groupingSpec.setFunctions(params.getParams(GroupParams.GROUP_FUNC));
    groupingSpec.setGroupOffset(params.getInt(GroupParams.GROUP_OFFSET, 0));
    groupingSpec.setGroupLimit(params.getInt(GroupParams.GROUP_LIMIT, 1));
    groupingSpec.setOffset(rb.getSortSpec().getOffset());
    groupingSpec.setLimit(rb.getSortSpec().getCount());
    groupingSpec.setIncludeGroupCount(params.getBool(GroupParams.GROUP_TOTAL_COUNT, false));
    groupingSpec.setMain(params.getBool(GroupParams.GROUP_MAIN, false));
    groupingSpec.setNeedScore((cmd.getFlags() & SolrIndexSearcher.GET_SCORES) != 0);
    groupingSpec.setTruncateGroups(params.getBool(GroupParams.GROUP_TRUNCATE, false));
}

From source file:org.apache.solr.search.grouping.distributed.command.QueryCommand.java

License:Apache License

@Override
public List<Collector> create() throws IOException {
    if (sort == null || sort == Sort.RELEVANCE) {
        collector = TopScoreDocCollector.create(docsToCollect, true);
    } else {/*from  w w w. ja  va  2s  .  c  om*/
        collector = TopFieldCollector.create(sort, docsToCollect, true, needScores, needScores, true);
    }
    filterCollector = new FilterCollector(docSet, collector);
    return Arrays.asList((Collector) filterCollector);
}

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

License:Apache License

public void testMaxScore() throws Exception {
    Directory d = newDirectory();/*ww  w  .j  a  v  a2 s  .c  om*/
    // 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.fao.geonet.api.records.formatters.groovy.EnvironmentImpl.java

License:Open Source License

@Override
public synchronized Map<String, Collection<String>> getIndexInfo() throws Exception {
    if (this.indexInfo == null) {
        final SearchManager searchManager = getBean(SearchManager.class);

        try (IndexAndTaxonomy newIndexReader = searchManager.getNewIndexReader(getLang3())) {
            TopFieldCollector collector = TopFieldCollector.create(Sort.RELEVANCE, 1, true, false, false,
                    false);//from  w  w w  .  j a v  a2  s .c  o m
            IndexSearcher searcher = new IndexSearcher(newIndexReader.indexReader);
            Query query = new TermQuery(new Term("_id", String.valueOf(getMetadataId())));
            searcher.search(query, collector);
            ScoreDoc[] topDocs = collector.topDocs().scoreDocs;

            Multimap<String, String> fields = HashMultimap.create();
            for (ScoreDoc scoreDoc : topDocs) {
                Document doc = searcher.doc(scoreDoc.doc);
                for (IndexableField field : doc) {
                    fields.put(field.name(), field.stringValue());
                }
            }
            this.indexInfo = fields;
        }

    }
    return Collections.unmodifiableMap(this.indexInfo.asMap());
}

From source file:org.grogshop.services.tests.SimpleLocalServiceTest.java

@Test
public void newUserAndLoginTest() throws ServiceException, NotSupportedException, SystemException,
        RollbackException, HeuristicMixedException, HeuristicRollbackException {
    ut.begin();/*from   w  w  w.j  ava  2 s  .  c om*/
    Long newUser = usersService.newUser(new User("grogdj@gmail.com", "asdasd"));

    ut.commit();
    Assert.assertNotNull(newUser);
    ut.begin();
    interestService.newInterest("sports");
    interestService.newInterest("food");
    ut.commit();
    List<String> tags = new ArrayList<String>();

    tags.add("sports");
    ut.begin();
    clubsService.newClub("My First Sports Club", "This is my sports first club description", "sports", tags,
            newUser, "imagePathHere", 51.5033630, -0.1276250);

    clubsService.newClub("My First food Club", "This is my first food club description", "food", tags, newUser,
            "imagePathHere", 51.5033630, -0.1276250);
    ut.commit();

    String userInput = "food";

    FullTextEntityManager fullTextEm = Search.getFullTextEntityManager(em);
    Assert.assertNotNull(fullTextEm);

    QueryBuilder qb = fullTextEm.getSearchFactory().buildQueryBuilder().forEntity(Club.class).get();
    Query query = qb.phrase().onField("name").andField("description").sentence(userInput).createQuery();

    FullTextQuery fullTextQuery = fullTextEm.createFullTextQuery(query, Club.class);
    fullTextQuery.setSort(org.apache.lucene.search.Sort.RELEVANCE);
    List resultList = fullTextQuery.getResultList();

    Assert.assertNotEquals(0, resultList.size());
}

From source file:org.neo4j.index.impl.lucene.legacy.LuceneBatchInserterIndex.java

License:Open Source License

private IndexHits<Long> query(Query query, final String key, final Object value) {
    IndexSearcher searcher;/*from  www . j a  v  a2s .  c o m*/
    try {
        searcher = searcherManager.acquire();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    try {
        DocValuesCollector collector = new DocValuesCollector(true);
        searcher.search(query, collector);
        IndexHits<Document> result = collector.getIndexHits(Sort.RELEVANCE);
        LegacyIndexHits primitiveHits = null;
        if (key == null || this.cache == null || !this.cache.containsKey(key)) {
            primitiveHits = new DocToIdIterator(result, Collections.<EntityId>emptyList(), null,
                    PrimitiveLongCollections.emptySet());
        } else {
            primitiveHits = new DocToIdIterator(result, Collections.<EntityId>emptyList(), null,
                    PrimitiveLongCollections.emptySet()) {
                private final Collection<EntityId> ids = new ArrayList<>();

                @Override
                protected boolean fetchNext() {
                    if (super.fetchNext()) {
                        ids.add(new EntityId.IdData(next));
                        return true;
                    }
                    addToCache(ids, key, value);
                    return false;
                }
            };
        }
        return wrapIndexHits(primitiveHits);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            searcherManager.release(searcher);
        } catch (IOException ignore) {
        }
    }
}

From source file:org.neo4j.index.impl.lucene.legacy.TestLuceneIndex.java

License:Open Source License

@Test
public void testSortByRelevance() {
    Index<Node> index = nodeIndex(LuceneIndexImplementation.EXACT_CONFIG);

    Node node1 = graphDb.createNode();
    Node node2 = graphDb.createNode();
    Node node3 = graphDb.createNode();
    index.add(node1, "name", "something");
    index.add(node2, "name", "something");
    index.add(node2, "foo", "yes");
    index.add(node3, "name", "something");
    index.add(node3, "foo", "yes");
    index.add(node3, "bar", "yes");
    restartTx();//from   w  w  w . j  a v  a  2 s.  c o m

    IndexHits<Node> hits = index
            .query(new QueryContext("+name:something foo:yes bar:yes").sort(Sort.RELEVANCE));
    assertEquals(node3, hits.next());
    assertEquals(node2, hits.next());
    assertEquals(node1, hits.next());
    assertFalse(hits.hasNext());
    index.delete();
    node1.delete();
    node2.delete();
    node3.delete();
}

From source file:org.neo4j.index.impl.lucene.legacy.TestLuceneIndex.java

License:Open Source License

@Test
public void testScoring() {
    Index<Node> index = nodeIndex(LuceneIndexImplementation.FULLTEXT_CONFIG);
    Node node1 = graphDb.createNode();
    Node node2 = graphDb.createNode();
    String key = "text";
    // Where the heck did I get this sentence from?
    index.add(node1, key, "a time where no one was really awake");
    index.add(node2, key, "once upon a time there was");
    restartTx();/*  w  ww. j a v  a 2  s.c  o  m*/

    IndexHits<Node> hits = index.query(key, new QueryContext("once upon a time was").sort(Sort.RELEVANCE));
    Node hit1 = hits.next();
    float score1 = hits.currentScore();
    Node hit2 = hits.next();
    float score2 = hits.currentScore();
    assertEquals(node2, hit1);
    assertEquals(node1, hit2);
    assertTrue("Score 1 (" + score1 + ") should have been higher than score 2 (" + score2 + ")",
            score1 > score2);
}

From source file:org.neo4j.index.impl.lucene.legacy.TestLuceneIndex.java

License:Open Source License

@Test
public void testTopHits() {
    Index<Relationship> index = relationshipIndex(LuceneIndexImplementation.FULLTEXT_CONFIG);
    EntityCreator<Relationship> creator = RELATIONSHIP_CREATOR;
    String key = "text";
    Relationship rel1 = creator.create(key, "one two three four five six seven eight nine ten");
    Relationship rel2 = creator.create(key, "one two three four five six seven eight other things");
    Relationship rel3 = creator.create(key, "one two three four five six some thing else");
    Relationship rel4 = creator.create(key, "one two three four five what ever");
    Relationship rel5 = creator.create(key, "one two three four all that is good and bad");
    Relationship rel6 = creator.create(key, "one two three hill or something");
    Relationship rel7 = creator.create(key, "one two other time than this");
    index.add(rel2, key, rel2.getProperty(key));
    index.add(rel1, key, rel1.getProperty(key));
    index.add(rel3, key, rel3.getProperty(key));
    index.add(rel7, key, rel7.getProperty(key));
    index.add(rel5, key, rel5.getProperty(key));
    index.add(rel4, key, rel4.getProperty(key));
    index.add(rel6, key, rel6.getProperty(key));
    String query = "one two three four five six seven";

    for (int i = 0; i < 2; i++) {
        assertContainsInOrder(index.query(key, new QueryContext(query).top(3).sort(Sort.RELEVANCE)), rel1, rel2,
                rel3);// ww  w .  j  a  v  a2 s  . c om
        restartTx();
    }
}