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:com.mathworks.xzheng.extsearch.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); // #1

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

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

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

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

    //dumpDocs(sort, docs);
}

From source file:com.mathworks.xzheng.tools.SpatialLuceneExample.java

License:Apache License

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

    DistanceQueryBuilder dq;/*w w w  . j a  v a2  s.c  o  m*/
    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

    System.out.println("Number of results: " + hits.totalHits);
    System.out.println("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);
        System.out.println("\t\t(" + rsLat + "," + rsLng + ")");
    }
}

From source file:com.mothsoft.alexis.dao.DocumentDaoImpl.java

License:Apache License

@Override
public ScrollableResults scrollableSearch(Long userId, DocumentState state, String queryString,
        SortOrder sortOrder, Date startDate, Date endDate) {
    final StopWatch stopWatch = new StopWatch();
    stopWatch.start();/*  w w  w. j  a v a 2  s.co m*/

    final FullTextQuery fullTextQuery = this.buildFullTextQuery(queryString, userId, startDate, endDate, false,
            state, FullTextQuery.THIS, FullTextQuery.SCORE);

    final Sort sort;
    switch (sortOrder) {
    case DATE_ASC:
        sort = new Sort(new SortField("id", SortField.LONG));
        break;
    case DATE_DESC:
        sort = new Sort(new SortField("id", SortField.LONG, true));
        break;
    case RELEVANCE:
        sort = new Sort(SortField.FIELD_SCORE, new SortField("id", SortField.LONG, true));
        break;
    default:
        throw new IllegalArgumentException("Unexpected SortOrder: " + sortOrder.name());
    }
    fullTextQuery.setSort(sort);

    fullTextQuery.setFetchSize(50);
    fullTextQuery.setReadOnly(true);
    fullTextQuery.setCacheable(false);
    fullTextQuery.setCacheMode(CacheMode.IGNORE);

    final ScrollableResults result = fullTextQuery.scroll(ScrollMode.FORWARD_ONLY);

    stopWatch.stop();
    logger.debug(stopWatch.toString());

    return result;
}

From source file:com.mothsoft.alexis.dao.DocumentDaoImpl.java

License:Apache License

@SuppressWarnings("unchecked")
public Graph getRelatedTerms(final String queryString, final Long userId, final int howMany) {
    final StopWatch stopWatch = new StopWatch();
    stopWatch.start();/*from   w  w  w  . j a  v a2 s .c o m*/

    final FullTextQuery fullTextQuery = this.buildFullTextQuery(queryString, userId, NO_DATE, NO_DATE, false,
            DocumentState.MATCHED_TO_TOPICS, FullTextQuery.ID);

    // find the specified number of terms from the most recent 100 documents
    // that match the query
    final Sort sort = new Sort(new SortField("creationDate", SortField.LONG, true));
    fullTextQuery.setSort(sort);
    fullTextQuery.setFirstResult(0);
    fullTextQuery.setMaxResults(100);

    final List<Long> documentIds = new ArrayList<Long>(100);
    final List<Long> termIds = new ArrayList<Long>(100);

    final List<Object[]> results = fullTextQuery.list();

    for (final Object[] ith : results) {
        final Long id = (Long) ith[0];
        documentIds.add(id);
    }

    final Map<String, Node> nodes = new LinkedHashMap<String, Node>();
    final Node root = new Node(queryString, Boolean.TRUE);
    nodes.put(queryString, root);

    final Map<String, Edge> edges = new HashMap<String, Edge>();

    if (!documentIds.isEmpty()) {
        final Session session = (Session) this.em.getDelegate();
        final org.hibernate.SQLQuery termsQuery = session.createSQLQuery("SELECT term.id "
                + "        FROM document_term dt INNER JOIN term on term.id = dt.term_id "
                + "        WHERE dt.document_id IN (:documentIds) GROUP BY term.id ORDER BY SUM(dt.tf_idf) DESC");
        termsQuery.setParameterList("documentIds", documentIds);
        termsQuery.setMaxResults(100);
        termIds.addAll((List<Long>) termsQuery.list());
    }

    if (!documentIds.isEmpty() && !termIds.isEmpty()) {

        final Session session = (Session) this.em.getDelegate();
        final org.hibernate.SQLQuery associationsQuery = session.createSQLQuery(
                "SELECT CONCAT(a.term_value) term_a_value, CONCAT(b.term_value) term_b_value, SUM(da.association_weight) sum_weight "
                        + "      FROM document_association da "
                        + "      INNER JOIN term a ON da.term_a_id = a.id "
                        + "        AND a.part_of_speech NOT IN (1, 3, 18, 19, 25, 39, 40) "
                        + "        AND length(a.term_value) > 2 "
                        + "      INNER JOIN term b ON da.term_b_id = b.id "
                        + "        AND b.part_of_speech NOT IN (1, 3, 18, 19, 25, 39, 40) "
                        + "        AND length(b.term_value) > 2 "
                        + "      WHERE da.document_id IN (:documentIds) AND (da.term_a_id IN (:termIds) OR da.term_b_id IN (:termIds)) "
                        + "      GROUP BY a.id, b.id ORDER BY sum_weight DESC");
        associationsQuery.setParameterList("documentIds", documentIds);
        associationsQuery.setParameterList("termIds", termIds);
        associationsQuery.setMaxResults(howMany);

        final List<Object[]> relatedTermsResults = associationsQuery.list();

        final Set<String> aNodeKeys = new HashSet<String>();
        final Set<String> bNodeKeys = new HashSet<String>();

        for (final Object[] ith : relatedTermsResults) {
            final String a = (String) ith[0];
            final String b = (String) ith[1];

            if (!nodes.containsKey(a)) {
                final Node node = new Node(a);
                nodes.put(a, node);
            }

            if (!nodes.containsKey(b)) {
                final Node node = new Node(b);
                nodes.put(b, node);
            }

            if (a.equals(b)) {
                continue;
            }

            final String edgeKey = a + "||" + b;
            final String edgeKeyInverse = b + "||" + a;
            if (!edges.containsKey(edgeKey) && !edges.containsKey(edgeKeyInverse)) {
                final Node nodeA = nodes.get(a);
                final Node nodeB = nodes.get(b);

                aNodeKeys.add(a);
                bNodeKeys.add(b);

                final Edge edge = new Edge(nodeA, nodeB);
                edges.put(edgeKey, edge);
            }
        }

        // "orphan" handling, any b that is not also an a needs an edge from
        // root
        final Set<String> orphanKeys = new HashSet<String>();
        orphanKeys.addAll(bNodeKeys);
        orphanKeys.removeAll(aNodeKeys);

        for (final String orphanKey : orphanKeys) {
            final Node orphan = nodes.get(orphanKey);
            final Edge orphanToParent = new Edge(root, orphan);
            edges.put(root.getName() + "||" + orphan.getName(), orphanToParent);
        }
    }

    final List<Node> nodeList = new ArrayList<Node>(nodes.size());
    // keep root as first element
    nodes.remove(root.getName());
    nodeList.add(root);
    nodeList.addAll(nodes.values());

    final Graph graph = new Graph(nodeList, new ArrayList<Edge>(edges.values()));

    stopWatch.stop();
    logger.info("Related terms search took: " + stopWatch.toString());

    return graph;
}

From source file:com.netflix.exhibitor.core.index.LogSearch.java

License:Apache License

public TopDocs search(Query query, int maxResults) throws IOException {
    Sort sort = new Sort(new SortField(FieldNames.DATE, SortField.LONG, true));
    return searcher.search(query, maxResults, sort);
}

From source file:com.opensource.roomate.service.RoomateServiceImpl.java

License:Open Source License

private ResultDto executeLuceneQuery(Query query, int currentPage, int pageSize) {
    EntityManager em = emf.createEntityManager();
    FullTextEntityManager fullTextEntityManager = org.hibernate.search.jpa.Search.getFullTextEntityManager(em);
    FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(query, Post.class);
    org.apache.lucene.search.Sort sort = new Sort(new SortField("postDate", true));
    fullTextQuery.setSort(sort);//from  ww w .  j a  v a 2 s  .  c o  m
    fullTextQuery.setFirstResult(currentPage);
    fullTextQuery.setMaxResults(pageSize);
    List<Post> result = fullTextQuery.getResultList();
    int total = fullTextQuery.getResultSize();
    return new ResultDto(result, currentPage, pageSize, total);
}

From source file:com.orientechnologies.lucene.manager.OLuceneSpatialIndexManager.java

License:Apache License

public Object searchIntersect(OCompositeKey key, double distance, OCommandContext context) throws IOException {

    double lat = ((Double) OType.convert(((OCompositeKey) key).getKeys().get(0), Double.class)).doubleValue();
    double lng = ((Double) OType.convert(((OCompositeKey) key).getKeys().get(1), Double.class)).doubleValue();
    SpatialOperation operation = SpatialOperation.Intersects;

    Point p = ctx.makePoint(lng, lat);
    SpatialArgs args = new SpatialArgs(operation,
            ctx.makeCircle(lng, lat, DistanceUtils.dist2Degrees(distance, DistanceUtils.EARTH_MEAN_RADIUS_KM)));
    Filter filter = strategy.makeFilter(args);
    IndexSearcher searcher = getSearcher();
    ValueSource valueSource = strategy.makeDistanceValueSource(p);
    Sort distSort = new Sort(valueSource.getSortField(false)).rewrite(searcher);

    return new LuceneResultSet(this,
            new SpatialQueryContext(context, searcher, new MatchAllDocsQuery(), filter, distSort)
                    .setSpatialArgs(args));
}

From source file:com.orientechnologies.lucene.OLuceneIndexType.java

License:Apache License

public static Sort sort(Query query, OIndexDefinition index, boolean ascSortOrder) {
    String key = index.getFields().iterator().next();
    Number number = ((NumericRangeQuery) query).getMin();
    number = number != null ? number : ((NumericRangeQuery) query).getMax();
    SortField.Type fieldType = SortField.Type.INT;
    if (number instanceof Long) {
        fieldType = SortField.Type.LONG;
    } else if (number instanceof Float) {
        fieldType = SortField.Type.FLOAT;
    } else if (number instanceof Double) {
        fieldType = SortField.Type.DOUBLE;
    }/*  w  w w .j a va  2s  . c  om*/

    return new Sort(new SortField(key, fieldType, ascSortOrder));
}

From source file:com.orientechnologies.spatial.engine.OLuceneLegacySpatialIndexEngine.java

License:Apache License

public Object searchIntersect(OCompositeKey key, double distance, OCommandContext context) throws IOException {

    double lat = ((Double) OType.convert(((OCompositeKey) key).getKeys().get(0), Double.class)).doubleValue();
    double lng = ((Double) OType.convert(((OCompositeKey) key).getKeys().get(1), Double.class)).doubleValue();
    SpatialOperation operation = SpatialOperation.Intersects;

    Point p = ctx.makePoint(lng, lat);
    SpatialArgs args = new SpatialArgs(operation,
            ctx.makeCircle(lng, lat, DistanceUtils.dist2Degrees(distance, DistanceUtils.EARTH_MEAN_RADIUS_KM)));
    Filter filter = strategy.makeFilter(args);
    IndexSearcher searcher = searcher();
    ValueSource valueSource = strategy.makeDistanceValueSource(p);
    Sort distSort = new Sort(valueSource.getSortField(false)).rewrite(searcher);

    return new LuceneResultSet(this,
            new SpatialQueryContext(context, searcher, new MatchAllDocsQuery(), filter, distSort)
                    .setSpatialArgs(args));
}

From source file:com.orientechnologies.spatial.strategy.SpatialQueryBuilderNear.java

License:Apache License

@Override
public SpatialQueryContext build(Map<String, Object> query) throws Exception {
    Shape shape = parseShape(query);

    double distance = 0;

    Number n = (Number) query.get(MAX_DISTANCE);
    if (n != null) {
        distance = n.doubleValue();/*  w  ww.j  a  v a 2s  . c  o m*/
    }

    Point p = (Point) shape;

    SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, factory.context().makeCircle(p.getX(),
            p.getY(), DistanceUtils.dist2Degrees(distance, DistanceUtils.EARTH_MEAN_RADIUS_KM)));
    Filter filter = manager.strategy().makeFilter(args);
    ValueSource valueSource = manager.strategy().makeDistanceValueSource(p);
    IndexSearcher searcher = manager.searcher();
    Sort distSort = new Sort(valueSource.getSortField(false)).rewrite(searcher);
    return new SpatialQueryContext(null, searcher, new MatchAllDocsQuery(), filter, distSort)
            .setSpatialArgs(args);
}