Example usage for org.apache.lucene.document DoublePoint newRangeQuery

List of usage examples for org.apache.lucene.document DoublePoint newRangeQuery

Introduction

In this page you can find the example usage for org.apache.lucene.document DoublePoint newRangeQuery.

Prototype

public static Query newRangeQuery(String field, double[] lowerValue, double[] upperValue) 

Source Link

Document

Create a range query for n-dimensional double values.

Usage

From source file:com.czw.search.lucene.example.facet.DistanceFacetsExample.java

License:Apache License

/** Given a latitude and longitude (in degrees) and the
 *  maximum great circle (surface of the earth) distance,
 *  returns a simple Filter bounding box to "fast match"
 *  candidates. *//*from  ww  w.  jav a 2 s. c o  m*/
public static Query getBoundingBoxQuery(double originLat, double originLng, double maxDistanceKM) {

    // Basic bounding box geo math from
    // http://JanMatuschek.de/LatitudeLongitudeBoundingCoordinates,
    // licensed under creative commons 3.0:
    // http://creativecommons.org/licenses/by/3.0

    // TODO: maybe switch to recursive prefix tree instead
    // (in lucene/spatial)?  It should be more efficient
    // since it's a 2D trie...

    // Degrees -> Radians:
    double originLatRadians = SloppyMath.toRadians(originLat);
    double originLngRadians = SloppyMath.toRadians(originLng);

    double angle = maxDistanceKM / EARTH_RADIUS_KM;

    double minLat = originLatRadians - angle;
    double maxLat = originLatRadians + angle;

    double minLng;
    double maxLng;
    if (minLat > SloppyMath.toRadians(-90) && maxLat < SloppyMath.toRadians(90)) {
        double delta = Math.asin(Math.sin(angle) / Math.cos(originLatRadians));
        minLng = originLngRadians - delta;
        if (minLng < SloppyMath.toRadians(-180)) {
            minLng += 2 * Math.PI;
        }
        maxLng = originLngRadians + delta;
        if (maxLng > SloppyMath.toRadians(180)) {
            maxLng -= 2 * Math.PI;
        }
    } else {
        // The query includes a pole!
        minLat = Math.max(minLat, SloppyMath.toRadians(-90));
        maxLat = Math.min(maxLat, SloppyMath.toRadians(90));
        minLng = SloppyMath.toRadians(-180);
        maxLng = SloppyMath.toRadians(180);
    }

    BooleanQuery.Builder f = new BooleanQuery.Builder();

    // Add latitude range filter:
    f.add(DoublePoint.newRangeQuery("latitude", SloppyMath.toDegrees(minLat), SloppyMath.toDegrees(maxLat)),
            BooleanClause.Occur.FILTER);

    // Add longitude range filter:
    if (minLng > maxLng) {
        // The bounding box crosses the international date
        // line:
        BooleanQuery.Builder lonF = new BooleanQuery.Builder();
        lonF.add(DoublePoint.newRangeQuery("longitude", SloppyMath.toDegrees(minLng), Double.POSITIVE_INFINITY),
                BooleanClause.Occur.SHOULD);
        lonF.add(DoublePoint.newRangeQuery("longitude", Double.NEGATIVE_INFINITY, SloppyMath.toDegrees(maxLng)),
                BooleanClause.Occur.SHOULD);
        f.add(lonF.build(), BooleanClause.Occur.MUST);
    } else {
        f.add(DoublePoint.newRangeQuery("longitude", SloppyMath.toDegrees(minLng),
                SloppyMath.toDegrees(maxLng)), BooleanClause.Occur.FILTER);
    }

    return f.build();
}

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

License:Open Source License

private static Query createDoubleRangeQuery(String propertyName, QueryTask.NumericRange<?> range) {
    // The range query constructed below is based-off
    // lucene documentation as per the link:
    // https://lucene.apache.org/core/6_0_0/core/org/apache/lucene/document/DoublePoint.html
    Double min = range.min == null ? Double.NEGATIVE_INFINITY : range.min.doubleValue();
    Double max = range.max == null ? Double.POSITIVE_INFINITY : range.max.doubleValue();
    if (!range.isMinInclusive) {
        min = Math.nextUp(min);// w  ww  . j a v  a2  s.c  om
    }
    if (!range.isMaxInclusive) {
        max = Math.nextDown(max);
    }
    return DoublePoint.newRangeQuery(propertyName, min, max);
}

From source file:org.apache.solr.legacy.BBoxStrategy.java

License:Apache License

/**
 * Returns a numeric range query based on FieldType
 * {@link LegacyNumericRangeQuery} is used for indexes created using {@code FieldType.LegacyNumericType}
 * {@link DoublePoint#newRangeQuery} is used for indexes created using {@link DoublePoint} fields
 *
 * @param fieldname field name. must not be <code>null</code>.
 * @param min minimum value of the range.
 * @param max maximum value of the range.
 * @param minInclusive include the minimum value if <code>true</code>.
 * @param maxInclusive include the maximum value if <code>true</code>
 *///from   ww w. ja  va  2s. c o  m
private Query makeNumericRangeQuery(String fieldname, Double min, Double max, boolean minInclusive,
        boolean maxInclusive) {
    if (hasPointVals) {
        if (min == null) {
            min = Double.NEGATIVE_INFINITY;
        }

        if (max == null) {
            max = Double.POSITIVE_INFINITY;
        }

        if (minInclusive == false) {
            min = Math.nextUp(min);
        }

        if (maxInclusive == false) {
            max = Math.nextDown(max);
        }

        return DoublePoint.newRangeQuery(fieldname, min, max);
    } else if (legacyNumericFieldType != null) {// todo remove legacy numeric support in 7.0
        return LegacyNumericRangeQuery.newDoubleRange(fieldname, legacyNumericFieldType.numericPrecisionStep(),
                min, max, minInclusive, maxInclusive);
    }
    throw new UnsupportedOperationException("An index is required for this operation.");
}

From source file:org.apache.solr.legacy.PointVectorStrategy.java

License:Apache License

/**
 * Returns a numeric range query based on FieldType
 * {@link LegacyNumericRangeQuery} is used for indexes created using {@code FieldType.LegacyNumericType}
 * {@link DoublePoint#newRangeQuery} is used for indexes created using {@link DoublePoint} fields
 *//*from   ww w . java  2s  . co m*/
private Query rangeQuery(String fieldName, Double min, Double max) {
    if (hasPointVals) {
        if (min == null) {
            min = Double.NEGATIVE_INFINITY;
        }

        if (max == null) {
            max = Double.POSITIVE_INFINITY;
        }

        return DoublePoint.newRangeQuery(fieldName, min, max);

    } else if (legacyNumericFieldType != null) {// todo remove legacy numeric support in 7.0
        return LegacyNumericRangeQuery.newDoubleRange(fieldName, legacyNumericFieldType.numericPrecisionStep(),
                min, max, true, true);//inclusive
    }
    //TODO try doc-value range query?
    throw new UnsupportedOperationException("An index is required for this operation.");
}

From source file:org.apache.solr.schema.DoublePointField.java

License:Apache License

@Override
public Query getPointRangeQuery(QParser parser, SchemaField field, String min, String max, boolean minInclusive,
        boolean maxInclusive) {
    double actualMin, actualMax;
    if (min == null) {
        actualMin = Double.NEGATIVE_INFINITY;
    } else {/*from   ww w. j  a v a2  s . com*/
        actualMin = Double.parseDouble(min);
        if (!minInclusive) {
            actualMin = DoublePoint.nextUp(actualMin);
        }
    }
    if (max == null) {
        actualMax = Double.POSITIVE_INFINITY;
    } else {
        actualMax = Double.parseDouble(max);
        if (!maxInclusive) {
            actualMax = DoublePoint.nextDown(actualMax);
        }
    }
    return DoublePoint.newRangeQuery(field.getName(), actualMin, actualMax);
}

From source file:org.janusgraph.diskstorage.lucene.LuceneIndex.java

License:Apache License

private static Query numericQuery(String key, Cmp relation, Number value) {
    switch (relation) {
    case EQUAL:/*from  www .ja  va  2 s  .  c  o  m*/
        return AttributeUtil.isWholeNumber(value)
                ? LongPoint.newRangeQuery(key, value.longValue(), value.longValue())
                : DoublePoint.newRangeQuery(key, value.doubleValue(), value.doubleValue());
    case NOT_EQUAL:
        final BooleanQuery.Builder q = new BooleanQuery.Builder();
        if (AttributeUtil.isWholeNumber(value)) {
            q.add(LongPoint.newRangeQuery(key, Long.MIN_VALUE, Math.addExact(value.longValue(), -1)),
                    BooleanClause.Occur.SHOULD);
            q.add(LongPoint.newRangeQuery(key, Math.addExact(value.longValue(), 1), Long.MAX_VALUE),
                    BooleanClause.Occur.SHOULD);
        } else {
            q.add(DoublePoint.newRangeQuery(key, Double.MIN_VALUE, DoublePoint.nextDown(value.doubleValue())),
                    BooleanClause.Occur.SHOULD);
            q.add(DoublePoint.newRangeQuery(key, DoublePoint.nextUp(value.doubleValue()), Double.MAX_VALUE),
                    BooleanClause.Occur.SHOULD);
        }
        return q.build();
    case LESS_THAN:
        return (AttributeUtil.isWholeNumber(value))
                ? LongPoint.newRangeQuery(key, Long.MIN_VALUE, Math.addExact(value.longValue(), -1))
                : DoublePoint.newRangeQuery(key, Double.MIN_VALUE, DoublePoint.nextDown(value.doubleValue()));
    case LESS_THAN_EQUAL:
        return (AttributeUtil.isWholeNumber(value))
                ? LongPoint.newRangeQuery(key, Long.MIN_VALUE, value.longValue())
                : DoublePoint.newRangeQuery(key, Double.MIN_VALUE, value.doubleValue());
    case GREATER_THAN:
        return (AttributeUtil.isWholeNumber(value))
                ? LongPoint.newRangeQuery(key, Math.addExact(value.longValue(), 1), Long.MAX_VALUE)
                : DoublePoint.newRangeQuery(key, DoublePoint.nextUp(value.doubleValue()), Double.MAX_VALUE);
    case GREATER_THAN_EQUAL:
        return (AttributeUtil.isWholeNumber(value))
                ? LongPoint.newRangeQuery(key, value.longValue(), Long.MAX_VALUE)
                : DoublePoint.newRangeQuery(key, value.doubleValue(), Double.MAX_VALUE);
    default:
        throw new IllegalArgumentException("Unexpected relation: " + relation);
    }
}

From source file:org.janusgraph.diskstorage.lucene.NumericTranslationQueryParser.java

License:Apache License

private Query getNumericRangeQuery(final String field, final Class<?> type, String start, String end,
        final boolean includeLower, final boolean includeUpper) {
    if (AttributeUtil.isWholeNumber(type)) {
        long min = isMatchAll(start) ? Long.MIN_VALUE : Long.parseLong(start);
        long max = isMatchAll(end) ? Long.MAX_VALUE : Long.parseLong(end);
        if (!includeLower) {
            min = Math.addExact(min, 1);
        }/*w  w  w.  jav  a 2  s . com*/
        if (!includeUpper) {
            max = Math.addExact(max, -1);
        }
        return LongPoint.newRangeQuery(field, min, max);
    } else {
        double min = isMatchAll(start) ? Double.NEGATIVE_INFINITY : Double.parseDouble(start);
        double max = isMatchAll(end) ? Double.POSITIVE_INFINITY : Double.parseDouble(end);
        if (!includeLower) {
            min = DoublePoint.nextUp(min);
        }
        if (!includeUpper) {
            max = DoublePoint.nextDown(max);
        }
        return DoublePoint.newRangeQuery(field, min, max);
    }
}

From source file:org.janusgraph.diskstorage.lucene.NumericTranslationQueryParser.java

License:Apache License

private Query buildNumericQuery(final String field, final String value, Class<?> type) {
    if (AttributeUtil.isWholeNumber(type)) {
        if (isMatchAll(value)) {
            return LongPoint.newRangeQuery(field, Long.MIN_VALUE, Long.MAX_VALUE);
        } else {/*from w w w .  j  a v  a  2s . com*/
            return LongPoint.newExactQuery(field, Long.parseLong(value));
        }
    } else {
        if (isMatchAll(value)) {
            return DoublePoint.newRangeQuery(field, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
        } else {
            return DoublePoint.newExactQuery(field, Double.parseDouble(value));
        }
    }
}

From source file:sh.isaac.provider.query.lucene.indexers.SemanticIndexer.java

License:Apache License

/**
 * Builds the numeric query./*  w w w  .j  a  v  a2s . c  o  m*/
 *
 * @param queryDataLower the query data lower
 * @param queryDataLowerInclusive the query data lower inclusive
 * @param queryDataUpper the query data upper
 * @param queryDataUpperInclusive the query data upper inclusive
 * @param columnName the column name
 * @return the query
 */
private Query buildNumericQuery(DynamicData queryDataLower, DynamicData queryDataUpper, String columnName) {
    // Convert both to the same type (if they differ) - go largest data type to smallest, so we don't lose precision
    // Also - if they pass in longs that would fit in an int, also generate an int query.
    // likewise, with Double - if they pass in a double, that would fit in a float, also generate a float query.
    try {
        final BooleanQuery.Builder bqBuilder = new BooleanQuery.Builder();
        boolean fitsInFloat = false;
        boolean fitsInInt = false;

        if ((queryDataLower instanceof DynamicDouble) || (queryDataUpper instanceof DynamicDouble)) {
            final Double upperVal = ((queryDataUpper == null) ? null
                    : ((queryDataUpper instanceof DynamicDouble)
                            ? ((DynamicDouble) queryDataUpper).getDataDouble()
                            : ((Number) queryDataUpper.getDataObject()).doubleValue()));
            final Double lowerVal = ((queryDataLower == null) ? null
                    : ((queryDataLower instanceof DynamicDouble)
                            ? ((DynamicDouble) queryDataLower).getDataDouble()
                            : ((Number) queryDataLower.getDataObject()).doubleValue()));

            bqBuilder.add(DoublePoint.newRangeQuery(columnName, lowerVal, upperVal), Occur.SHOULD);

            if (((upperVal != null) && (upperVal <= Float.MAX_VALUE) && (upperVal >= Float.MIN_VALUE))
                    || ((lowerVal != null) && (lowerVal <= Float.MAX_VALUE) && (lowerVal >= Float.MIN_VALUE))) {
                fitsInFloat = true;
            }
        }

        if (fitsInFloat || (queryDataLower instanceof DynamicFloat)
                || (queryDataUpper instanceof DynamicFloat)) {
            final Float upperVal = ((queryDataUpper == null) ? null
                    : ((queryDataUpper == null) ? null
                            : ((queryDataUpper instanceof DynamicFloat)
                                    ? ((DynamicFloat) queryDataUpper).getDataFloat()
                                    : ((fitsInFloat && ((Number) queryDataUpper.getDataObject())
                                            .doubleValue() > Float.MAX_VALUE) ? Float.MAX_VALUE
                                                    : ((Number) queryDataUpper.getDataObject())
                                                            .floatValue()))));
            final Float lowerVal = ((queryDataLower == null) ? null
                    : ((queryDataLower instanceof DynamicFloat) ? ((DynamicFloat) queryDataLower).getDataFloat()
                            : ((fitsInFloat && ((Number) queryDataLower.getDataObject())
                                    .doubleValue() < Float.MIN_VALUE) ? Float.MIN_VALUE
                                            : ((Number) queryDataLower.getDataObject()).floatValue())));

            bqBuilder.add(FloatPoint.newRangeQuery(columnName, lowerVal, upperVal), Occur.SHOULD);
        }

        if ((queryDataLower instanceof DynamicLong) || (queryDataUpper instanceof DynamicLong)) {
            final Long upperVal = ((queryDataUpper == null) ? null
                    : ((queryDataUpper instanceof DynamicLong) ? ((DynamicLong) queryDataUpper).getDataLong()
                            : ((Number) queryDataUpper.getDataObject()).longValue()));
            final Long lowerVal = ((queryDataLower == null) ? null
                    : ((queryDataLower instanceof DynamicLong) ? ((DynamicLong) queryDataLower).getDataLong()
                            : ((Number) queryDataLower.getDataObject()).longValue()));

            bqBuilder.add(LongPoint.newRangeQuery(columnName, lowerVal, upperVal), Occur.SHOULD);

            if (((upperVal != null) && (upperVal <= Integer.MAX_VALUE) && (upperVal >= Integer.MIN_VALUE))
                    || ((lowerVal != null) && (lowerVal <= Integer.MAX_VALUE)
                            && (lowerVal >= Integer.MIN_VALUE))) {
                fitsInInt = true;
            }
        }

        if (fitsInInt || (queryDataLower instanceof DynamicInteger)
                || (queryDataUpper instanceof DynamicInteger) || (queryDataLower instanceof DynamicSequence)
                || (queryDataUpper instanceof DynamicSequence)) {
            final Integer upperVal = ((queryDataUpper == null) ? null
                    : ((queryDataUpper instanceof DynamicInteger)
                            ? ((DynamicInteger) queryDataUpper).getDataInteger()
                            : ((queryDataUpper instanceof DynamicSequence)
                                    ? ((DynamicSequence) queryDataUpper).getDataSequence()
                                    : ((fitsInInt && ((Number) queryDataUpper.getDataObject())
                                            .longValue() > Integer.MAX_VALUE) ? Integer.MAX_VALUE
                                                    : ((Number) queryDataUpper.getDataObject()).intValue()))));
            final Integer lowerVal = ((queryDataLower == null) ? null
                    : ((queryDataLower instanceof DynamicInteger)
                            ? ((DynamicInteger) queryDataLower).getDataInteger()
                            : ((queryDataLower instanceof DynamicSequence)
                                    ? ((DynamicSequence) queryDataLower).getDataSequence()
                                    : ((fitsInInt && ((Number) queryDataLower.getDataObject())
                                            .longValue() < Integer.MIN_VALUE) ? Integer.MIN_VALUE
                                                    : ((Number) queryDataLower.getDataObject()).intValue()))));

            bqBuilder.add(IntPoint.newRangeQuery(columnName, lowerVal, upperVal), Occur.SHOULD);
        }
        BooleanQuery bq = bqBuilder.build();
        if (bq.clauses().isEmpty()) {
            throw new RuntimeException("Not a numeric data type - can't perform a range query");
        } else {
            final BooleanQuery.Builder must = new BooleanQuery.Builder();

            must.add(bq, Occur.MUST);
            return must.build();
        }
    } catch (final ClassCastException e) {
        throw new RuntimeException(
                "One of the values is not a numeric data type - can't perform a range query");
    }
}