Example usage for org.apache.lucene.search SortedNumericSortField SortedNumericSortField

List of usage examples for org.apache.lucene.search SortedNumericSortField SortedNumericSortField

Introduction

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

Prototype

public SortedNumericSortField(String field, SortField.Type type, boolean reverse) 

Source Link

Document

Creates a sort, possibly in reverse, by the minimum value in the set for the document.

Usage

From source file:com.querydsl.lucene5.LuceneSerializer.java

License:Apache License

public Sort toSort(List<? extends OrderSpecifier<?>> orderBys) {
    List<SortField> sorts = new ArrayList<SortField>(orderBys.size());
    for (OrderSpecifier<?> order : orderBys) {
        if (!(order.getTarget() instanceof Path<?>)) {
            throw new IllegalArgumentException("argument was not of type Path.");
        }/*from www  . j  av a 2  s  . c  o m*/
        Class<?> type = order.getTarget().getType();
        boolean reverse = !order.isAscending();
        Path<?> path = getPath(order.getTarget());
        if (Number.class.isAssignableFrom(type)) {
            sorts.add(new SortedNumericSortField(toField(path), sortFields.get(type), reverse));
        } else {
            sorts.add(new SortField(toField(path), SortField.Type.STRING, reverse));
        }
    }
    Sort sort = new Sort();
    sort.setSort(sorts.toArray(new SortField[sorts.size()]));
    return sort;
}

From source file:com.qwazr.search.field.SortedDoubleDocValuesType.java

License:Apache License

@Override
final public SortField getSortField(final QueryDefinition.SortEnum sortEnum) {
    final SortField sortField = new SortedNumericSortField(fieldName, SortField.Type.DOUBLE,
            SortUtils.sortReverse(sortEnum));
    SortUtils.sortDoubleMissingValue(sortEnum, sortField);
    return sortField;
}

From source file:com.qwazr.search.field.SortedFloatDocValuesType.java

License:Apache License

@Override
final public SortField getSortField(final QueryDefinition.SortEnum sortEnum) {
    final SortField sortField = new SortedNumericSortField(fieldName, SortField.Type.FLOAT,
            SortUtils.sortReverse(sortEnum));
    SortUtils.sortFloatMissingValue(sortEnum, sortField);
    return sortField;
}

From source file:com.qwazr.search.field.SortedIntDocValuesType.java

License:Apache License

@Override
final public SortField getSortField(final QueryDefinition.SortEnum sortEnum) {
    final SortField sortField = new SortedNumericSortField(fieldName, SortField.Type.INT,
            SortUtils.sortReverse(sortEnum));
    SortUtils.sortIntMissingValue(sortEnum, sortField);
    return sortField;
}

From source file:com.qwazr.search.field.SortedLongDocValuesType.java

License:Apache License

@Override
final public SortField getSortField(final QueryDefinition.SortEnum sortEnum) {
    final SortField sortField = new SortedNumericSortField(fieldName, SortField.Type.LONG,
            SortUtils.sortReverse(sortEnum));
    SortUtils.sortLongMissingValue(sortEnum, sortField);
    return sortField;
}

From source file:com.vmware.xenon.services.common.LuceneDocumentIndexBackupService.java

License:Open Source License

private void updateCurrentAttributeForSelfLink(IndexSearcher searcher, long timeSnapshotBoundaryMicros,
        String selfLink, IndexWriter newWriter) throws IOException {

    Query selfLinkClause = new TermQuery(new Term(ServiceDocument.FIELD_NAME_SELF_LINK, selfLink));
    Query updateTimeClause = LongPoint.newRangeQuery(ServiceDocument.FIELD_NAME_UPDATE_TIME_MICROS, 0,
            timeSnapshotBoundaryMicros);
    Query booleanQuery = new BooleanQuery.Builder().add(selfLinkClause, Occur.MUST)
            .add(updateTimeClause, Occur.MUST).build();

    Sort versionSort = new Sort(
            new SortedNumericSortField(ServiceDocument.FIELD_NAME_VERSION, SortField.Type.LONG, true));

    TopDocs results = searcher.search(booleanQuery, 1, versionSort, false, false);
    if (results == null || results.scoreDocs == null || results.scoreDocs.length == 0) {
        return;//from   w ww . jav  a  2  s. c  o m
    }

    DocumentStoredFieldVisitor visitor = new DocumentStoredFieldVisitor();
    visitor.reset(LuceneIndexDocumentHelper.FIELD_NAME_INDEXING_ID);
    searcher.doc(results.scoreDocs[0].doc, visitor);
    if (visitor.documentIndexingId == null) {
        return;
    }

    Term indexingIdTerm = new Term(LuceneIndexDocumentHelper.FIELD_NAME_INDEXING_ID,
            visitor.documentIndexingId);
    newWriter.updateNumericDocValue(indexingIdTerm,
            LuceneIndexDocumentHelper.FIELD_NAME_INDEXING_METADATA_VALUE_TOMBSTONE_TIME,
            LuceneIndexDocumentHelper.ACTIVE_DOCUMENT_TOMBSTONE_TIME);
}

From source file:com.vmware.xenon.services.common.LuceneDocumentIndexService.java

License:Open Source License

private void initializeInstance() {
    this.searchSync = new Object();
    this.searcher = null;
    this.searchersForPaginatedQueries.clear();
    this.searchersPendingClose.clear();

    this.versionSort = new Sort(
            new SortedNumericSortField(ServiceDocument.FIELD_NAME_VERSION, SortField.Type.LONG, true));

    this.fieldsToLoadNoExpand = new HashSet<>();
    this.fieldsToLoadNoExpand.add(ServiceDocument.FIELD_NAME_SELF_LINK);
    this.fieldsToLoadNoExpand.add(ServiceDocument.FIELD_NAME_VERSION);
    this.fieldsToLoadNoExpand.add(ServiceDocument.FIELD_NAME_UPDATE_TIME_MICROS);
    this.fieldsToLoadNoExpand.add(ServiceDocument.FIELD_NAME_UPDATE_ACTION);
    this.fieldsToLoadNoExpand.add(ServiceDocument.FIELD_NAME_EXPIRATION_TIME_MICROS);
    this.fieldsToLoadWithExpand = new HashSet<>(this.fieldsToLoadNoExpand);
    this.fieldsToLoadWithExpand.add(LUCENE_FIELD_NAME_JSON_SERIALIZED_STATE);
    this.fieldsToLoadWithExpand.add(LUCENE_FIELD_NAME_BINARY_SERIALIZED_STATE);
}

From source file:com.vmware.xenon.services.common.LuceneQueryConverter.java

License:Open Source License

static Sort convertToLuceneSort(QueryTask.QuerySpecification querySpecification, boolean isGroupSort) {

    QueryTask.QueryTerm sortTerm = isGroupSort ? querySpecification.groupSortTerm : querySpecification.sortTerm;

    QueryTask.QuerySpecification.SortOrder sortOrder = isGroupSort ? querySpecification.groupSortOrder
            : querySpecification.sortOrder;

    validateSortTerm(sortTerm);/*  w w  w.  j a  v  a  2s.  c o m*/

    if (querySpecification.options.contains(QueryOption.TOP_RESULTS)) {
        if (querySpecification.resultLimit <= 0 || querySpecification.resultLimit == Integer.MAX_VALUE) {
            throw new IllegalArgumentException("resultLimit should be a positive integer less than MAX_VALUE");
        }
    }

    if (sortOrder == null) {
        if (isGroupSort) {
            querySpecification.groupSortOrder = QueryTask.QuerySpecification.SortOrder.ASC;
        } else {
            querySpecification.sortOrder = QueryTask.QuerySpecification.SortOrder.ASC;
        }
    }

    boolean order = sortOrder != QueryTask.QuerySpecification.SortOrder.ASC;

    SortField sortField = null;
    SortField.Type type = convertToLuceneType(sortTerm.propertyType);

    switch (type) {
    case LONG:
    case DOUBLE:
        sortField = new SortedNumericSortField(sortTerm.propertyName, type, order);
        break;
    default:
        sortField = new SortField(sortTerm.propertyName, type, order);
        break;
    }
    return new Sort(sortField);
}

From source file:edu.usc.ir.geo.gazetteer.GeoNameResolver.java

License:Apache License

private HashMap<String, List<Location>> resolveEntities(List<String> locationNames, int count,
        IndexReader reader) throws IOException {
    if (locationNames.size() >= 200)
        hitsPerPage = 5; // avoid heavy computation
    IndexSearcher searcher = new IndexSearcher(reader);
    Query q = null;/*www. j ava2 s . c  o  m*/

    HashMap<String, List<Location>> allCandidates = new HashMap<String, List<Location>>();

    for (String name : locationNames) {

        if (!allCandidates.containsKey(name)) {
            try {
                //query is wrapped in additional quotes (") to avoid query tokenization on space
                q = new MultiFieldQueryParser(new String[] { FIELD_NAME_NAME, FIELD_NAME_ALTERNATE_NAMES },
                        analyzer).parse(String.format("\"%s\"", name));

                //sort descending on population
                SortField populationSort = new SortedNumericSortField(FIELD_NAME_POPULATION,
                        SortField.Type.LONG, true);

                Sort sort = new Sort(populationSort);
                //Fetch 3 times desired values, these will be sorted on code and only desired number will be kept
                ScoreDoc[] hits = searcher.search(q, hitsPerPage * 3, sort).scoreDocs;

                List<Location> topHits = new ArrayList<Location>();

                for (int i = 0; i < hits.length; ++i) {
                    Location tmpLocObj = new Location();

                    int docId = hits[i].doc;
                    Document d;
                    try {
                        d = searcher.doc(docId);
                        tmpLocObj.setName(d.get(FIELD_NAME_NAME));
                        tmpLocObj.setLongitude(d.get(FIELD_NAME_LONGITUDE));
                        tmpLocObj.setLatitude(d.get(FIELD_NAME_LATITUDE));
                        //If alternate names are empty put name as actual name
                        //This covers missing data and equals weight for later computation
                        if (d.get(FIELD_NAME_ALTERNATE_NAMES).isEmpty()) {
                            tmpLocObj.setAlternateNames(d.get(FIELD_NAME_NAME));
                        } else {
                            tmpLocObj.setAlternateNames(d.get(FIELD_NAME_ALTERNATE_NAMES));
                        }
                        tmpLocObj.setCountryCode(d.get(FIELD_NAME_COUNTRY_CODE));
                        tmpLocObj.setAdmin1Code(d.get(FIELD_NAME_ADMIN1_CODE));
                        tmpLocObj.setAdmin2Code(d.get(FIELD_NAME_ADMIN2_CODE));
                        tmpLocObj.setFeatureCode(d.get(FIELD_NAME_FEATURE_CODE));

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    topHits.add(tmpLocObj);
                }
                //Picking hitsPerPage number of locations from feature code sorted list 
                allCandidates.put(name, pickTopSortedByCode(topHits, hitsPerPage));
            } catch (org.apache.lucene.queryparser.classic.ParseException e) {
                e.printStackTrace();
            }
        }
    }

    HashMap<String, List<Location>> resolvedEntities = new HashMap<String, List<Location>>();
    pickBestCandidates(resolvedEntities, allCandidates, count);
    return resolvedEntities;
}

From source file:io.crate.execution.engine.collect.collectors.LuceneOrderedDocCollectorTest.java

License:Apache License

private Long[] nextPageQuery(IndexReader reader, FieldDoc lastCollected, boolean reverseFlag,
        @Nullable Boolean nullFirst) throws IOException {
    OrderBy orderBy = new OrderBy(ImmutableList.of(REFERENCE), new boolean[] { reverseFlag },
            new Boolean[] { nullFirst });

    SortField sortField = new SortedNumericSortField("value", SortField.Type.LONG, reverseFlag);
    Long missingValue = (Long) LuceneMissingValue.missingValue(orderBy, 0);
    sortField.setMissingValue(missingValue);
    Sort sort = new Sort(sortField);

    OptimizeQueryForSearchAfter queryForSearchAfter = new OptimizeQueryForSearchAfter(orderBy,
            mock(QueryShardContext.class), name -> valueFieldType);
    Query nextPageQuery = queryForSearchAfter.apply(lastCollected);
    TopFieldDocs result = search(reader, nextPageQuery, sort);
    Long results[] = new Long[result.scoreDocs.length];
    for (int i = 0; i < result.scoreDocs.length; i++) {
        Long value = (Long) ((FieldDoc) result.scoreDocs[i]).fields[0];
        results[i] = value.equals(missingValue) ? null : value;
    }//from  w  w  w  .j  av  a 2  s.co m
    return results;
}