org.elasticsearch.common.unit.DistanceUnit Java Examples

The following examples show how to use org.elasticsearch.common.unit.DistanceUnit. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GeoSettingsApplier.java    From crate with Apache License 2.0 6 votes vote down vote up
private static void applyPrecision(Map<String, Object> mapping, Settings geoSettings) {
    String precision = geoSettings.get("precision");
    if (precision == null) {
        Integer treeLevels = geoSettings.getAsInt("tree_levels", null);
        if (treeLevels != null) {
            mapping.put("tree_levels", treeLevels);
        }
    } else {
        try {
            DistanceUnit.parse(precision, DistanceUnit.DEFAULT, DistanceUnit.DEFAULT);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException(
                String.format(Locale.ENGLISH, "Value '%s' of setting precision is not a valid distance unit", precision)
            );
        }
        mapping.put("precision", precision);
    }
}
 
Example #2
Source File: ElasticsearchDocumentDistance.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public double getDistance() {
	String geohash = (String) ((ElasticsearchDocument) getDocument()).getSource().get(geoPointField);
	GeoPoint dstPoint = GeoPoint.fromGeohash(geohash);

	double unitDist = GeoDistance.ARC.calculate(srcPoint.getLat(), srcPoint.getLon(), dstPoint.getLat(),
			dstPoint.getLon(), unit);
	double distance;
	if (GEOF.UOM_METRE.equals(units)) {
		distance = unit.toMeters(unitDist);
	} else if (GEOF.UOM_DEGREE.equals(units)) {
		distance = unitDist / unit.getDistancePerDegree();
	} else if (GEOF.UOM_RADIAN.equals(units)) {
		distance = DistanceUtils.dist2Radians(unit.convert(unitDist, DistanceUnit.KILOMETERS),
				DistanceUtils.EARTH_MEAN_RADIUS_KM);
	} else if (GEOF.UOM_UNITY.equals(units)) {
		distance = unit.convert(unitDist, DistanceUnit.KILOMETERS) / (Math.PI * DistanceUtils.EARTH_MEAN_RADIUS_KM);
	} else {
		throw new UnsupportedOperationException("Unsupported units: " + units);
	}
	return distance;
}
 
Example #3
Source File: DecayFunctionParser.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
protected NumericDoubleValues distance(LeafReaderContext context) {
    final MultiGeoPointValues geoPointValues = fieldData.load(context).getGeoPointValues();
    return mode.select(new MultiValueMode.UnsortedNumericDoubleValues() {
        @Override
        public int count() {
            return geoPointValues.count();
        }

        @Override
        public void setDocument(int docId) {
            geoPointValues.setDocument(docId);
        }

        @Override
        public double valueAt(int index) {
            GeoPoint other = geoPointValues.valueAt(index);
            return Math.max(0.0d, distFunction.calculate(origin.lat(), origin.lon(), other.lat(), other.lon(), DistanceUnit.METERS) - offset);
        }
    }, 0.0);
}
 
Example #4
Source File: DecayFunctionParser.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private AbstractDistanceScoreFunction parseGeoVariable(String fieldName, XContentParser parser, QueryParseContext parseContext,
        GeoPointFieldMapper.GeoPointFieldType fieldType, MultiValueMode mode) throws IOException {
    XContentParser.Token token;
    String parameterName = null;
    GeoPoint origin = new GeoPoint();
    String scaleString = null;
    String offsetString = "0km";
    double decay = 0.5;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            parameterName = parser.currentName();
        } else if (parameterName.equals(DecayFunctionBuilder.SCALE)) {
            scaleString = parser.text();
        } else if (parameterName.equals(DecayFunctionBuilder.ORIGIN)) {
            origin = GeoUtils.parseGeoPoint(parser);
        } else if (parameterName.equals(DecayFunctionBuilder.DECAY)) {
            decay = parser.doubleValue();
        } else if (parameterName.equals(DecayFunctionBuilder.OFFSET)) {
            offsetString = parser.text();
        } else {
            throw new ElasticsearchParseException("parameter [{}] not supported!", parameterName);
        }
    }
    if (origin == null || scaleString == null) {
        throw new ElasticsearchParseException("[{}] and [{}] must be set for geo fields.", DecayFunctionBuilder.ORIGIN, DecayFunctionBuilder.SCALE);
    }
    double scale = DistanceUnit.DEFAULT.parse(scaleString, DistanceUnit.DEFAULT);
    double offset = DistanceUnit.DEFAULT.parse(offsetString, DistanceUnit.DEFAULT);
    IndexGeoPointFieldData indexFieldData = parseContext.getForField(fieldType);
    return new GeoFieldDataScoreFunction(origin, scale, decay, offset, getDecayFunction(), indexFieldData, mode);

}
 
Example #5
Source File: GeoPointFieldMapperLegacy.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/** Get an instance based on the expected precision. Here are examples of the number of required bytes per value depending on the
 *  expected precision:<ul>
 *  <li>1km: 4 bytes</li>
 *  <li>3m: 6 bytes</li>
 *  <li>1m: 8 bytes</li>
 *  <li>1cm: 8 bytes</li>
 *  <li>1mm: 10 bytes</li></ul> */
public static final Encoding of(DistanceUnit.Distance precision) {
    for (Encoding encoding : INSTANCES) {
        if (encoding != null && encoding.precision().compareTo(precision) <= 0) {
            return encoding;
        }
    }
    return INSTANCES[MAX_NUM_BYTES];
}
 
Example #6
Source File: GeoShapeFieldMapper.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException {
    builder.field("type", contentType());

    if (includeDefaults || fieldType().tree().equals(Defaults.TREE) == false) {
        builder.field(Names.TREE, fieldType().tree());
    }
    if (includeDefaults || fieldType().treeLevels() != 0) {
        builder.field(Names.TREE_LEVELS, fieldType().treeLevels());
    }
    if (includeDefaults || fieldType().precisionInMeters() != -1) {
        builder.field(Names.TREE_PRESISION, DistanceUnit.METERS.toString(fieldType().precisionInMeters()));
    }
    if (includeDefaults || fieldType().strategyName() != Defaults.STRATEGY) {
        builder.field(Names.STRATEGY, fieldType().strategyName());
    }
    if (includeDefaults || fieldType().distanceErrorPct() != fieldType().defaultDistanceErrorPct) {
        builder.field(Names.DISTANCE_ERROR_PCT, fieldType().distanceErrorPct());
    }
    if (includeDefaults || fieldType().orientation() != Defaults.ORIENTATION) {
        builder.field(Names.ORIENTATION, fieldType().orientation());
    }
    if (includeDefaults || fieldType().pointsOnly() != GeoShapeFieldMapper.Defaults.POINTS_ONLY) {
        builder.field(Names.STRATEGY_POINTS_ONLY, fieldType().pointsOnly());
    }
    if (includeDefaults || coerce.explicit()) {
        builder.field("coerce", coerce.value());
    }
}
 
Example #7
Source File: GeoShapeFieldMapper.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
    Builder builder = geoShapeField(name);
    for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) {
        Map.Entry<String, Object> entry = iterator.next();
        String fieldName = Strings.toUnderscoreCase(entry.getKey());
        Object fieldNode = entry.getValue();
        if (Names.TREE.equals(fieldName)) {
            builder.fieldType().setTree(fieldNode.toString());
            iterator.remove();
        } else if (Names.TREE_LEVELS.equals(fieldName)) {
            builder.fieldType().setTreeLevels(Integer.parseInt(fieldNode.toString()));
            iterator.remove();
        } else if (Names.TREE_PRESISION.equals(fieldName)) {
            builder.fieldType().setPrecisionInMeters(DistanceUnit.parse(fieldNode.toString(), DistanceUnit.DEFAULT, DistanceUnit.DEFAULT));
            iterator.remove();
        } else if (Names.DISTANCE_ERROR_PCT.equals(fieldName)) {
            builder.fieldType().setDistanceErrorPct(Double.parseDouble(fieldNode.toString()));
            iterator.remove();
        } else if (Names.ORIENTATION.equals(fieldName)) {
            builder.fieldType().setOrientation(ShapeBuilder.orientationFromString(fieldNode.toString()));
            iterator.remove();
        } else if (Names.STRATEGY.equals(fieldName)) {
            builder.fieldType().setStrategyName(fieldNode.toString());
            iterator.remove();
        } else if (Names.COERCE.equals(fieldName)) {
            builder.coerce(nodeBooleanValue(fieldNode));
            iterator.remove();
        } else if (Names.STRATEGY_POINTS_ONLY.equals(fieldName)
            && builder.fieldType().strategyName.equals(SpatialStrategy.TERM.getStrategyName()) == false) {
            builder.fieldType().setPointsOnly(XContentMapValues.nodeBooleanValue(fieldNode));
            iterator.remove();
        }
    }
    return builder;
}
 
Example #8
Source File: DistanceFunction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public Double evaluate(Input arg1, Input arg2) {
    Object value1 = arg1.value();
    if (value1 == null) {
        return null;
    }
    Object value2 = arg2.value();
    if (value2 == null) {
        return null;
    }
    double sourceLongitude;
    double sourceLatitude;
    double targetLongitude;
    double targetLatitude;

     // need to handle list also - because e.g. ESSearchTask returns geo_points as list
    if (value1 instanceof List) {
        sourceLongitude = (Double)((List) value1).get(0);
        sourceLatitude = (Double)((List) value1).get(1);
    } else {
        sourceLongitude = ((Double[]) value1)[0];
        sourceLatitude = ((Double[]) value1)[1];
    }
    if (value2 instanceof List) {
        targetLongitude = (Double)((List) value2).get(0);
        targetLatitude = (Double)((List) value2).get(1);
    } else {
        targetLongitude = ((Double[]) value2)[0];
        targetLatitude = ((Double[]) value2)[1];
    }
    return GeoDistance.SLOPPY_ARC.calculate(
            sourceLatitude, sourceLongitude, targetLatitude, targetLongitude, DistanceUnit.METERS);
}
 
Example #9
Source File: ScriptDocValues.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public double distanceInMilesWithDefault(double lat, double lon, double defaultValue) {
    if (isEmpty()) {
        return defaultValue;
    }
    GeoPoint point = getValue();
    return GeoDistance.PLANE.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.MILES);
}
 
Example #10
Source File: ScriptDocValues.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public double distanceInKmWithDefault(double lat, double lon, double defaultValue) {
    if (isEmpty()) {
        return defaultValue;
    }
    GeoPoint point = getValue();
    return GeoDistance.PLANE.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.KILOMETERS);
}
 
Example #11
Source File: ScriptDocValues.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public double distanceWithDefault(double lat, double lon, double defaultValue) {
    if (isEmpty()) {
        return defaultValue;
    }
    GeoPoint point = getValue();
    return GeoDistance.PLANE.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.DEFAULT);
}
 
Example #12
Source File: ElasticsearchDocumentDistance.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public ElasticsearchDocumentDistance(SearchHit hit,
		Function<? super String, ? extends SpatialContext> geoContextMapper, String geoPointField, IRI units,
		GeoPoint srcPoint, DistanceUnit unit) {
	super(hit, geoContextMapper);
	this.geoPointField = geoPointField;
	this.units = units;
	this.srcPoint = srcPoint;
	this.unit = unit;
}
 
Example #13
Source File: ScriptDocValues.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public double arcDistanceInMilesWithDefault(double lat, double lon, double defaultValue) {
    if (isEmpty()) {
        return defaultValue;
    }
    GeoPoint point = getValue();
    return GeoDistance.ARC.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.MILES);
}
 
Example #14
Source File: ScriptDocValues.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public double arcDistanceInKmWithDefault(double lat, double lon, double defaultValue) {
    if (isEmpty()) {
        return defaultValue;
    }
    GeoPoint point = getValue();
    return GeoDistance.ARC.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.KILOMETERS);
}
 
Example #15
Source File: ElasticsearchIndex.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected Iterable<? extends DocumentDistance> geoQuery(final IRI geoProperty, Point p, final IRI units,
		double distance, String distanceVar, Var contextVar) throws MalformedQueryException, IOException {
	double unitDist;
	final DistanceUnit unit;
	if (GEOF.UOM_METRE.equals(units)) {
		unit = DistanceUnit.METERS;
		unitDist = distance;
	} else if (GEOF.UOM_DEGREE.equals(units)) {
		unit = DistanceUnit.KILOMETERS;
		unitDist = unit.getDistancePerDegree() * distance;
	} else if (GEOF.UOM_RADIAN.equals(units)) {
		unit = DistanceUnit.KILOMETERS;
		unitDist = DistanceUtils.radians2Dist(distance, DistanceUtils.EARTH_MEAN_RADIUS_KM);
	} else if (GEOF.UOM_UNITY.equals(units)) {
		unit = DistanceUnit.KILOMETERS;
		unitDist = distance * Math.PI * DistanceUtils.EARTH_MEAN_RADIUS_KM;
	} else {
		throw new MalformedQueryException("Unsupported units: " + units);
	}

	double lat = p.getY();
	double lon = p.getX();
	final String fieldName = toGeoPointFieldName(SearchFields.getPropertyField(geoProperty));
	QueryBuilder qb = QueryBuilders.functionScoreQuery(
			QueryBuilders.geoDistanceQuery(fieldName).point(lat, lon).distance(unitDist, unit),
			ScoreFunctionBuilders.linearDecayFunction(fieldName, GeohashUtils.encodeLatLon(lat, lon),
					new DistanceUnit.Distance(unitDist, unit).toString()));
	if (contextVar != null) {
		qb = addContextTerm(qb, (Resource) contextVar.getValue());
	}

	SearchRequestBuilder request = client.prepareSearch();
	SearchHits hits = search(request, qb);
	final GeoPoint srcPoint = new GeoPoint(lat, lon);
	return Iterables.transform(hits, (Function<SearchHit, DocumentDistance>) hit -> {
		return new ElasticsearchDocumentDistance(hit, geoContextMapper, fieldName, units, srcPoint, unit);
	});
}
 
Example #16
Source File: ScriptDocValues.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public double arcDistanceWithDefault(double lat, double lon, double defaultValue) {
    if (isEmpty()) {
        return defaultValue;
    }
    GeoPoint point = getValue();
    return GeoDistance.ARC.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.DEFAULT);
}
 
Example #17
Source File: ScriptDocValues.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public double factorDistanceWithDefault(double lat, double lon, double defaultValue) {
    if (isEmpty()) {
        return defaultValue;
    }
    GeoPoint point = getValue();
    return GeoDistance.FACTOR.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.DEFAULT);
}
 
Example #18
Source File: GeoDistanceParser.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public GeoDistanceFactory(String name, ValuesSourceConfig<ValuesSource.GeoPoint> valueSourceConfig,
                          InternalRange.Factory rangeFactory, GeoPoint origin, DistanceUnit unit, GeoDistance distanceType,
                          List<RangeAggregator.Range> ranges, boolean keyed) {
    super(name, rangeFactory.type(), valueSourceConfig);
    this.origin = origin;
    this.unit = unit;
    this.distanceType = distanceType;
    this.rangeFactory = rangeFactory;
    this.ranges = ranges;
    this.keyed = keyed;
}
 
Example #19
Source File: GeoDistanceParser.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public DistanceSource(ValuesSource.GeoPoint source, GeoDistance distanceType, org.elasticsearch.common.geo.GeoPoint origin, DistanceUnit unit) {
    this.source = source;
    // even if the geo points are unique, there's no guarantee the distances are
    this.distanceType = distanceType;
    this.unit = unit;
    this.origin = origin;
}
 
Example #20
Source File: ScriptDocValues.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public double geohashDistanceInMiles(String geohash) {
    GeoPoint point = getValue();
    GeoPoint p = new GeoPoint().resetFromGeoHash(geohash);
    return GeoDistance.ARC.calculate(point.lat(), point.lon(), p.lat(), p.lon(), DistanceUnit.MILES);
}
 
Example #21
Source File: ElasticsearchSearchQueryBase.java    From vertexium with Apache License 2.0 4 votes vote down vote up
private CircleBuilder getCircleBuilder(GeoCircle geoCircle) {
    return ShapeBuilders.newCircleBuilder()
        .center(geoCircle.getLongitude(), geoCircle.getLatitude())
        .radius(geoCircle.getRadius(), DistanceUnit.KILOMETERS);
}
 
Example #22
Source File: GeoShapeFieldMapper.java    From crate with Apache License 2.0 4 votes vote down vote up
@Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
    Builder builder = new Builder(name);
    Boolean pointsOnly = null;
    for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) {
        Map.Entry<String, Object> entry = iterator.next();
        String fieldName = entry.getKey();
        Object fieldNode = entry.getValue();
        if (Names.TREE.equals(fieldName)) {
            builder.fieldType().setTree(fieldNode.toString());
            iterator.remove();
        } else if (Names.TREE_LEVELS.equals(fieldName)) {
            builder.fieldType().setTreeLevels(Integer.parseInt(fieldNode.toString()));
            iterator.remove();
        } else if (Names.TREE_PRESISION.equals(fieldName)) {
            builder.fieldType().setPrecisionInMeters(DistanceUnit.parse(fieldNode.toString(), DistanceUnit.DEFAULT, DistanceUnit.DEFAULT));
            iterator.remove();
        } else if (Names.DISTANCE_ERROR_PCT.equals(fieldName)) {
            builder.fieldType().setDistanceErrorPct(Double.parseDouble(fieldNode.toString()));
            iterator.remove();
        } else if (Names.ORIENTATION.equals(fieldName)) {
            builder.fieldType().setOrientation(ShapeBuilder.Orientation.fromString(fieldNode.toString()));
            iterator.remove();
        } else if (Names.STRATEGY.equals(fieldName)) {
            builder.fieldType().setStrategyName(fieldNode.toString());
            iterator.remove();
        } else if (IGNORE_MALFORMED.equals(fieldName)) {
            builder.ignoreMalformed(nodeBooleanValue(fieldNode, fieldName + ".ignore_malformed"));
            iterator.remove();
        } else if (Names.COERCE.equals(fieldName)) {
            builder.coerce(nodeBooleanValue(fieldNode, fieldName + '.' + Names.COERCE));
            iterator.remove();
        } else if (GeoPointFieldMapper.Names.IGNORE_Z_VALUE.getPreferredName().equals(fieldName)) {
            builder.ignoreZValue(
                nodeBooleanValue(fieldNode, fieldName + '.' + GeoPointFieldMapper.Names.IGNORE_Z_VALUE.getPreferredName()));
            iterator.remove();
        } else if (Names.STRATEGY_POINTS_ONLY.equals(fieldName)) {
            pointsOnly = nodeBooleanValue(fieldNode, fieldName + '.' + Names.STRATEGY_POINTS_ONLY);
            iterator.remove();
        } else if ("position".equals(fieldName)) {
            builder.position(nodeIntegerValue(fieldNode));
            iterator.remove();
        }
    }
    if (pointsOnly != null) {
        if (builder.fieldType().strategyName.equals(SpatialStrategy.TERM.getStrategyName()) && pointsOnly == false) {
            throw new IllegalArgumentException("points_only cannot be set to false for term strategy");
        } else {
            builder.fieldType().setPointsOnly(pointsOnly);
        }
    }
    return builder;
}
 
Example #23
Source File: Test.java    From AsuraFramework with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
   /* QueryBuilder qb1 = QueryBuilders.matchQuery("a","b");
    System.out.println(qb1.toString());*/
    String json="{\"query\":{\"match_all\":{}},\"filter\":{\"geo_shape\":{\"geometry\":{\"relation\":\"CONTAINS\",\"shape\":{\"coordinates\":[116.402257,39.914548],\"type\":\"point\"}}}}}";
    QueryBuilder qb= QueryBuilders.matchAllQuery();
    //System.out.println(qb.toString());
    SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();
    searchSourceBuilder.query(qb);
   // System.out.println(searchSourceBuilder.toString());
    ShapeBuilder shapeBuilder= ShapeBuilder.newPoint(new Coordinate(116.402257,39.914548));
    QueryBuilder qb2= QueryBuilders.geoShapeQuery("geometry",shapeBuilder, ShapeRelation.CONTAINS);
    System.out.println(qb2.toString());

    //searchSourceBuilder.postFilter(qb2);
    QueryBuilder qb3= QueryBuilders.boolQuery().must(qb).filter(qb2);
    searchSourceBuilder.query(qb3);
    System.out.println(qb3.toString());
    System.out.println(searchSourceBuilder.toString());
    QueryBuilder qb4= QueryBuilders.boolQuery().must(qb).must(qb2);
    System.out.println(qb4.toString());


    SortBuilder sort= SortBuilders.geoDistanceSort("pin.location") .point(40, -70).
            unit(DistanceUnit.fromString(DistanceUnit.KILOMETERS.toString())).order(SortOrder.DESC);
  /*  QueryBuilder qb5 = QueryBuilders.geoDistanceQuery("pin.location")
            .point(40, -70)
            .distance(400,  DistanceUnit.fromString(DistanceUnit.KILOMETERS.toString()))
            .geoDistance(GeoDistance.ARC);
             System.out.println(qb5.toString());
            */
    searchSourceBuilder.sort(sort);
    System.out.println(searchSourceBuilder.toString());
    //QueryBuilder qb3=QueryBuilders.filteredQuery(null,qb2);
    //QueryBuilder qb4=QueryBuilders.filteredQuery(qb,qb2);
    //searchSourceBuilder.query(qb3.toString());
   // searchSourceBuilder.query(qb4);
   // System.out.println(qb4.toString());
    //System.out.println(searchSourceBuilder.toString());

    // System.out.println(qb.toString());
   /* QueryBuilder qb2 = QueryBuilders.geoBoundingBoxQuery("pin.location")
            .topLeft(40.73, -74.1)
            .bottomRight(40.717, -73.99);
    //String  strstr= JSON.toJSONString(qb2);
    System.out.println(qb2.toString());
    System.out.println("1111111");*/
}
 
Example #24
Source File: GeoShapeFieldMapper.java    From crate with Apache License 2.0 4 votes vote down vote up
@Override
protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException {
    builder.field("type", contentType());

    if (includeDefaults || fieldType().tree().equals(Defaults.TREE) == false) {
        builder.field(Names.TREE, fieldType().tree());
    }

    if (position != null) {
        builder.field("position", position);
    }

    if (fieldType().treeLevels() != 0) {
        builder.field(Names.TREE_LEVELS, fieldType().treeLevels());
    } else if (includeDefaults && fieldType().precisionInMeters() == -1) { // defaults only make sense if precision is not specified
        if ("geohash".equals(fieldType().tree())) {
            builder.field(Names.TREE_LEVELS, Defaults.GEOHASH_LEVELS);
        } else if ("legacyquadtree".equals(fieldType().tree())) {
            builder.field(Names.TREE_LEVELS, Defaults.QUADTREE_LEVELS);
        } else if ("quadtree".equals(fieldType().tree())) {
            builder.field(Names.TREE_LEVELS, Defaults.QUADTREE_LEVELS);
        } else {
            throw new IllegalArgumentException("Unknown prefix tree type [" + fieldType().tree() + "]");
        }
    }
    if (fieldType().precisionInMeters() != -1) {
        builder.field(Names.TREE_PRESISION, DistanceUnit.METERS.toString(fieldType().precisionInMeters()));
    } else if (includeDefaults && fieldType().treeLevels() == 0) { // defaults only make sense if tree levels are not specified
        builder.field(Names.TREE_PRESISION, DistanceUnit.METERS.toString(50));
    }
    if (includeDefaults || fieldType().strategyName().equals(Defaults.STRATEGY) == false) {
        builder.field(Names.STRATEGY, fieldType().strategyName());
    }
    if (includeDefaults || fieldType().distanceErrorPct() != fieldType().defaultDistanceErrorPct) {
        builder.field(Names.DISTANCE_ERROR_PCT, fieldType().distanceErrorPct());
    }
    if (includeDefaults || fieldType().orientation() != Defaults.ORIENTATION) {
        builder.field(Names.ORIENTATION, fieldType().orientation());
    }
    if (fieldType().strategyName().equals(SpatialStrategy.TERM.getStrategyName())) {
        // For TERMs strategy the defaults for points only change to true
        if (includeDefaults || fieldType().pointsOnly() != true) {
            builder.field(Names.STRATEGY_POINTS_ONLY, fieldType().pointsOnly());
        }
    } else {
        if (includeDefaults || fieldType().pointsOnly() != GeoShapeFieldMapper.Defaults.POINTS_ONLY) {
            builder.field(Names.STRATEGY_POINTS_ONLY, fieldType().pointsOnly());
        }
    }
    if (includeDefaults || coerce.explicit()) {
        builder.field(Names.COERCE, coerce.value());
    }
    if (includeDefaults || ignoreMalformed.explicit()) {
        builder.field(IGNORE_MALFORMED, ignoreMalformed.value());
    }
    if (includeDefaults || ignoreZValue.explicit()) {
        builder.field(GeoPointFieldMapper.Names.IGNORE_Z_VALUE.getPreferredName(), ignoreZValue.value());
    }
}
 
Example #25
Source File: GeoDistance.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public SloppyArcFixedSourceDistance(double sourceLatitude, double sourceLongitude, DistanceUnit unit) {
    super(sourceLatitude, sourceLongitude, unit);
}
 
Example #26
Source File: GeoDistance.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public ArcFixedSourceDistance(double sourceLatitude, double sourceLongitude, DistanceUnit unit) {
    super(sourceLatitude, sourceLongitude, unit);
}
 
Example #27
Source File: GeoDistance.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public FixedSourceDistanceBase(double sourceLatitude, double sourceLongitude, DistanceUnit unit) {
    this.sourceLatitude = sourceLatitude;
    this.sourceLongitude = sourceLongitude;
    this.unit = unit;
}
 
Example #28
Source File: GeoJsonParser.java    From crate with Apache License 2.0 4 votes vote down vote up
protected static ShapeBuilder parse(XContentParser parser, GeoShapeFieldMapper shapeMapper)
    throws IOException {
    GeoShapeType shapeType = null;
    DistanceUnit.Distance radius = null;
    CoordinateNode coordinateNode = null;
    GeometryCollectionBuilder geometryCollections = null;

    ShapeBuilder.Orientation requestedOrientation =
        (shapeMapper == null) ? ShapeBuilder.Orientation.RIGHT : shapeMapper.fieldType().orientation();
    final Explicit<Boolean> coerce = (shapeMapper == null) ? GeoShapeFieldMapper.Defaults.COERCE : shapeMapper.coerce();
    final Explicit<Boolean> ignoreZValue = (shapeMapper == null) ? GeoShapeFieldMapper.Defaults.IGNORE_Z_VALUE : shapeMapper.ignoreZValue();

    String malformedException = null;

    XContentParser.Token token;
    try {
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                String fieldName = parser.currentName();

                if (ShapeParser.FIELD_TYPE.match(fieldName, parser.getDeprecationHandler())) {
                    parser.nextToken();
                    final GeoShapeType type = GeoShapeType.forName(parser.text());
                    if (shapeType != null && shapeType.equals(type) == false) {
                        malformedException = ShapeParser.FIELD_TYPE + " already parsed as ["
                            + shapeType + "] cannot redefine as [" + type + "]";
                    } else {
                        shapeType = type;
                    }
                } else if (ShapeParser.FIELD_COORDINATES.match(fieldName, parser.getDeprecationHandler())) {
                    parser.nextToken();
                    CoordinateNode tempNode = parseCoordinates(parser, ignoreZValue.value());
                    if (coordinateNode != null && tempNode.numDimensions() != coordinateNode.numDimensions()) {
                        throw new ElasticsearchParseException("Exception parsing coordinates: " +
                            "number of dimensions do not match");
                    }
                    coordinateNode = tempNode;
                } else if (ShapeParser.FIELD_GEOMETRIES.match(fieldName, parser.getDeprecationHandler())) {
                    if (shapeType == null) {
                        shapeType = GeoShapeType.GEOMETRYCOLLECTION;
                    } else if (shapeType.equals(GeoShapeType.GEOMETRYCOLLECTION) == false) {
                        malformedException = "cannot have [" + ShapeParser.FIELD_GEOMETRIES + "] with type set to ["
                            + shapeType + "]";
                    }
                    parser.nextToken();
                    geometryCollections = parseGeometries(parser, shapeMapper);
                } else if (CircleBuilder.FIELD_RADIUS.match(fieldName, parser.getDeprecationHandler())) {
                    if (shapeType == null) {
                        shapeType = GeoShapeType.CIRCLE;
                    } else if (shapeType.equals(GeoShapeType.CIRCLE) == false) {
                        malformedException = "cannot have [" + CircleBuilder.FIELD_RADIUS + "] with type set to ["
                            + shapeType + "]";
                    }
                    parser.nextToken();
                    radius = DistanceUnit.Distance.parseDistance(parser.text());
                } else if (ShapeParser.FIELD_ORIENTATION.match(fieldName, parser.getDeprecationHandler())) {
                    if (shapeType != null
                        && (shapeType.equals(GeoShapeType.POLYGON) || shapeType.equals(GeoShapeType.MULTIPOLYGON)) == false) {
                        malformedException = "cannot have [" + ShapeParser.FIELD_ORIENTATION + "] with type set to [" + shapeType + "]";
                    }
                    parser.nextToken();
                    requestedOrientation = ShapeBuilder.Orientation.fromString(parser.text());
                } else {
                    parser.nextToken();
                    parser.skipChildren();
                }
            }
        }
    } catch (Exception ex) {
        // Skip all other fields until the end of the object
        while (parser.currentToken() != XContentParser.Token.END_OBJECT && parser.currentToken() != null) {
            parser.nextToken();
            parser.skipChildren();
        }
        throw ex;
    }

    if (malformedException != null) {
        throw new ElasticsearchParseException(malformedException);
    } else if (shapeType == null) {
        throw new ElasticsearchParseException("shape type not included");
    } else if (coordinateNode == null && GeoShapeType.GEOMETRYCOLLECTION != shapeType) {
        throw new ElasticsearchParseException("coordinates not included");
    } else if (geometryCollections == null && GeoShapeType.GEOMETRYCOLLECTION == shapeType) {
        throw new ElasticsearchParseException("geometries not included");
    } else if (radius != null && GeoShapeType.CIRCLE != shapeType) {
        throw new ElasticsearchParseException("field [{}] is supported for [{}] only", CircleBuilder.FIELD_RADIUS,
            CircleBuilder.TYPE);
    }

    if (shapeType.equals(GeoShapeType.GEOMETRYCOLLECTION)) {
        return geometryCollections;
    }

    return shapeType.getBuilder(coordinateNode, radius, requestedOrientation, coerce.value());
}
 
Example #29
Source File: CircleBuilder.java    From crate with Apache License 2.0 4 votes vote down vote up
/**
 * Get the radius unit of the circle
 */
public DistanceUnit unit() {
    return this.unit;
}
 
Example #30
Source File: GeoDistance.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public FactorFixedSourceDistance(double sourceLatitude, double sourceLongitude, DistanceUnit unit) {
    this.sourceLongitude = sourceLongitude;
    this.a = Math.toRadians(90D - sourceLatitude);
    this.sinA = Math.sin(a);
    this.cosA = Math.cos(a);
}