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(SortField... fields) 

Source Link

Document

Sets the sort to the given criteria in succession: the first SortField is checked first, but if it produces a tie, then the second SortField is used to break the tie, etc.

Usage

From source file:syslogSearch.java

License:Open Source License

public void run() {

    try {/*from w  w  w.  j  a  v  a 2 s. c o m*/

        String searchQuery = (new BufferedReader(new InputStreamReader(searchSocket.getInputStream())))
                .readLine().trim();

        IndexReader reader = writer.getReader();
        Searcher searcher = new IndexSearcher(reader);

        QueryParser indexParser = new QueryParser(Version.LUCENE_30, "data", analyzer);

        SortField hitSortField = new SortField("date", SortField.LONG);
        Sort hitSort = new Sort(hitSortField);

        TopFieldDocs hits = searcher.search(indexParser.parse(searchQuery), null, 1000, hitSort);

        PrintWriter searchReply = new PrintWriter(searchSocket.getOutputStream(), true);

        searchReply.println(hits.totalHits + " Hits for " + searchQuery);

        for (int i = 0; i < hits.totalHits; i++) {
            Document document = searcher.doc(hits.scoreDocs[i].doc);

            String host = document.get("hostname");
            String date = document.get("date");
            String data = document.get("data");

            searchReply.print("host: " + host + ", date: " + date + ", data: " + data + "\n\n");
        }

        searchReply.close();
        searcher.close();
        reader.close();
        searchSocket.close();
    } catch (Exception ex) {
        System.out.print("Exception: " + ex + "\n");
    }

}

From source file:DVBench.java

License:Apache License

static long search(String description, IndexSearcher searcher, String field, int iters, boolean quiet)
        throws Exception {
    int count = 0;
    Query query = new MatchAllDocsQuery();
    Sort sort = new Sort(new SortField(field, SortField.Type.LONG));
    long startTime = System.currentTimeMillis();
    for (int i = 0; i < iters; i++) {
        TopDocs td = searcher.search(query, 20, sort);
        count += td.totalHits;//  www.j a  va2 s . co  m
    }
    long endTime = System.currentTimeMillis();
    if (!quiet) {
        double delta = endTime - startTime;
        double avg = delta / iters;
        double QPS = 1000d / avg;
        System.out.println(description + ": " + QPS);
    }
    return count;
}

From source file:am.ik.categolj2.domain.repository.entry.EntryRepositoryImpl.java

License:Apache License

Page<Entry> searchTemplate(Pageable pageable,
        Function<QueryBuilder, org.apache.lucene.search.Query> queryCreator) {
    try {/*from w w  w.j a  v  a 2s. c  om*/
        creatingIndex.get();
    } catch (InterruptedException e) {
        logger.warn("Interrupted!", e);
        Thread.currentThread().interrupt();
    } catch (ExecutionException e) {
        logger.error("Index creation failed!!", e);
    }
    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
    QueryBuilder queryBuilder = fullTextEntityManager.getSearchFactory().buildQueryBuilder()
            .forEntity(Entry.class).get();

    org.apache.lucene.search.Query query = queryCreator.apply(queryBuilder);
    org.apache.lucene.search.Sort sort = new Sort(
            new SortField("lastModifiedDate", SortField.Type.STRING_VAL, true));
    Query jpaQuery = fullTextEntityManager.createFullTextQuery(query, Entry.class).setSort(sort)
            .setFirstResult(pageable.getOffset()).setMaxResults(pageable.getPageSize());
    int count = fullTextEntityManager.createFullTextQuery(query, Entry.class).getResultSize();
    @SuppressWarnings("unchecked")
    List<Entry> content = jpaQuery.getResultList();
    return new PageImpl<>(content, pageable, count);
}

From source file:aos.lucene.search.advanced.FunctionQueryTest.java

License:Apache License

public void testRecency() throws Throwable {
    Directory dir = TestUtil.getBookIndexDirectory();
    IndexReader r = DirectoryReader.open(dir);
    IndexSearcher s = new IndexSearcher(r);
    s.setDefaultFieldSortScoring(true, true);

    QueryParser parser = new QueryParser(Version.LUCENE_46, "contents",
            new StandardAnalyzer(Version.LUCENE_46));
    Query q = parser.parse("java in action"); // #A
    Query q2 = new RecencyBoostingQuery(q, // #B
            2.0, 2 * 365, "pubmonthAsDay");
    Sort sort = new Sort(new SortField[] { SortField.FIELD_SCORE, new SortField("title2", SortField.STRING) });
    TopDocs hits = s.search(q2, null, 5, sort);

    for (int i = 0; i < hits.scoreDocs.length; i++) {
        Document doc = r.document(hits.scoreDocs[i].doc);
        LOGGER.info((1 + i) + ": " + doc.get("title") + ": pubmonth=" + doc.get("pubmonth") + " score="
                + hits.scoreDocs[i].score);
    }/*from   w w  w  . ja  v a 2  s  . co m*/
    s.close();
    r.close();
    dir.close();
}

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,//from  w w w . j  a va2s.  com
            new Sort(new SortField[] { SortField.FIELD_SCORE, new SortField("category", SortField.STRING) }));
    directory.close();
}

From source file:aos.lucene.search.ext.sorting.DistanceSortingTest.java

License:Apache License

public void testNearestRestaurantToHome() throws Exception {
    Sort sort = new Sort(new SortField("unused", new DistanceComparatorSource(0, 0)));

    TopDocs hits = searcher.search(query, null, 10, sort);

    assertEquals("closest", "El Charro", searcher.doc(hits.scoreDocs[0].doc).get("name"));
    assertEquals("furthest", "Los Betos", searcher.doc(hits.scoreDocs[3].doc).get("name"));
}

From source file:aos.lucene.search.ext.sorting.DistanceSortingTest.java

License:Apache License

public void testNeareastRestaurantToWork() throws Exception {
    Sort sort = new Sort(new SortField("unused", new DistanceComparatorSource(10, 10)));

    TopFieldDocs docs = searcher.search(query, null, 3, sort); //

    assertEquals(4, docs.totalHits); //
    assertEquals(3, docs.scoreDocs.length); //

    FieldDoc fieldDoc = (FieldDoc) docs.scoreDocs[0]; //

    assertEquals("(10,10) -> (9,6) = sqrt(17)", new Float(Math.sqrt(17)), fieldDoc.fields[0]); //

    Document document = searcher.doc(fieldDoc.doc); //
    assertEquals("Los Betos", document.get("name"));

    //dumpDocs(sort, docs);
}

From source file:aos.lucene.tools.SpatialLuceneExample.java

License:Apache License

public void findNear(String what, double latitude, double longitude, double radius)
        throws CorruptIndexException, IOException {
    IndexSearcher searcher = new IndexSearcher(directory);

    DistanceQueryBuilder dq;/*from   w  ww  .  j av a2s  .c  om*/
    dq = new DistanceQueryBuilder(latitude, // #A
            longitude, // #A
            radius, // #A
            latField, // #A
            lngField, // #A
            tierPrefix, // #A
            true); // #A

    Query tq;
    if (what == null)
        tq = new TermQuery(new Term("metafile", "doc")); // #B
    else
        tq = new TermQuery(new Term("name", what));

    DistanceFieldComparatorSource dsort; // #C
    dsort = new DistanceFieldComparatorSource( // #C
            dq.getDistanceFilter()); // #C
    Sort sort = new Sort(new SortField("foo", dsort)); // #C

    TopDocs hits = searcher.search(tq, dq.getFilter(), 10, sort);

    Map<Integer, Double> distances = // #D
            dq.getDistanceFilter().getDistances(); // #D

    LOGGER.info("Number of results: " + hits.totalHits);
    LOGGER.info("Found:");
    for (ScoreDoc sd : hits.scoreDocs) {
        int docID = sd.doc;
        Document d = searcher.doc(docID);

        String name = d.get("name");
        double rsLat = NumericUtils.prefixCodedToDouble(d.get(latField));
        double rsLng = NumericUtils.prefixCodedToDouble(d.get(lngField));
        Double geo_distance = distances.get(docID);

        System.out.printf(name + ": %.2f Miles\n", geo_distance);
        LOGGER.info("\t\t(" + rsLat + "," + rsLng + ")");
    }
}

From source file:at.itbh.bev.apibeans.BevFinderBean.java

License:Open Source License

@Override
public GeocodingResult<BevQueryResult> reverseGeocode(Double latitude, Double longitude, Float radius)
        throws InvalidApiUsageException {
    if (latitude == null && longitude == null && radius == null) {
        throw new InvalidApiUsageException("Latitude, longitude and radius must be provided.");
    }/*w w w. j a  va  2s  . com*/

    FullTextEntityManager fullTextEm = Search.getFullTextEntityManager(em);
    QueryBuilder b = fullTextEm.getSearchFactory().buildQueryBuilder().forEntity(AdresseDenormalized.class)
            .get();
    Query query = b.spatial().onField("location").within(radius, Unit.KM).ofLatitude(latitude)
            .andLongitude(longitude).createQuery();

    FullTextQuery fullTextQuery = fullTextEm.createFullTextQuery(query, AdresseDenormalized.class);
    Sort distanceSort = new Sort(new DistanceSortField(latitude, longitude, "location"));
    fullTextQuery.setSort(distanceSort);

    try {
        return finder.queryIndex(BevQueryResult.class, fullTextQuery, maxResults, prune, null, null, null, null,
                latitude, longitude, radius);
    } catch (Exception e) {
        throw new EJBException(e);
    }
}

From source file:at.itbh.bev.apibeans.CommonBevFinderBean.java

License:Open Source License

@Override
public GeocodingResult<AustrianCommonQueryResult> reverseGeocode(Double latitude, Double longitude,
        Float radius) throws InvalidApiUsageException {
    if (latitude == null && longitude == null && radius == null) {
        throw new InvalidApiUsageException("Latitude, longitude and radius must be provided.");
    }/*  www  . j  a v a  2 s.com*/

    FullTextEntityManager fullTextEm = Search.getFullTextEntityManager(em);
    QueryBuilder b = fullTextEm.getSearchFactory().buildQueryBuilder().forEntity(AdresseDenormalized.class)
            .get();
    Query query = b.spatial().onField("location").within(radius, Unit.KM).ofLatitude(latitude)
            .andLongitude(longitude).createQuery();

    FullTextQuery fullTextQuery = fullTextEm.createFullTextQuery(query, AdresseDenormalized.class);
    Sort distanceSort = new Sort(new DistanceSortField(latitude, longitude, "location"));
    fullTextQuery.setSort(distanceSort);

    try {
        return finder.queryIndex(AustrianCommonQueryResult.class, fullTextQuery, maxResults, prune, null, null,
                null, null, latitude, longitude, radius);
    } catch (Exception e) {
        throw new EJBException(e);
    }
}