Java Code Examples for org.springframework.data.geo.Distance

The following examples show how to use org.springframework.data.geo.Distance. These examples are extracted from open source projects. 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 Project: spring-data   Source File: ArangoResultConverter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Build a GeoResult from the given ArangoCursor
 *
 * @param cursor
 *            query result from driver
 * @return GeoResult object
 */
private GeoResult<?> buildGeoResult(final ArangoCursor<?> cursor) {
	GeoResult<?> geoResult = null;
	while (cursor.hasNext() && geoResult == null) {
		final Object object = cursor.next();
		if (!(object instanceof VPackSlice)) {
			continue;
		}

		final VPackSlice slice = (VPackSlice) object;
		final VPackSlice distSlice = slice.get("_distance");
		final Double distanceInMeters = distSlice.isDouble() ? distSlice.getAsDouble() : null;
		if (distanceInMeters == null) {
			continue;
		}

		final Object entity = operations.getConverter().read(domainClass, slice);
		final Distance distance = new Distance(distanceInMeters / 1000, Metrics.KILOMETERS);
		geoResult = new GeoResult<>(entity, distance);
	}
	return geoResult;
}
 
Example 2
Source Project: spring-data   Source File: ArangoResultConverter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Construct a GeoResult from the given object
 *
 * @param object
 *            object representing one document in the result
 * @return GeoResult object
 */
private GeoResult<?> buildGeoResult(final Object object) {
	if (object == null || !(object instanceof VPackSlice)) {
		return null;
	}

	final VPackSlice slice = (VPackSlice) object;
	final VPackSlice distSlice = slice.get("_distance");
	final Double distanceInMeters = distSlice.isDouble() ? distSlice.getAsDouble() : null;
	if (distanceInMeters == null) {
		return null;
	}

	final Object entity = operations.getConverter().read(domainClass, slice);
	final Distance distance = new Distance(distanceInMeters / 1000, Metrics.KILOMETERS);
	return new GeoResult<>(entity, distance);
}
 
Example 3
Source Project: spring-data   Source File: BindParameterBinding.java    License: Apache License 2.0 6 votes vote down vote up
public int bind(
	final Object value,
	final boolean shouldIgnoreCase,
	final Boolean borderStatus,
	final UniqueCheck uniqueCheck,
	final int startIndex) {
	int index = startIndex;
	final Object caseAdjusted = ignoreArgumentCase(value, shouldIgnoreCase);
	final Class<? extends Object> clazz = caseAdjusted.getClass();
	if (clazz == Distance.class) {
		final Distance distance = (Distance) caseAdjusted;
		bind(index++, convertDistanceToMeters(distance));
	} else if (borderStatus != null && borderStatus) {
		bind(index++, escapeSpecialCharacters((String) caseAdjusted) + "%");
	} else if (borderStatus != null) {
		bind(index++, "%" + escapeSpecialCharacters((String) caseAdjusted));
	} else {
		bind(index++, caseAdjusted);
	}
	return index;
}
 
Example 4
Source Project: spring-data   Source File: DerivedQueryCreatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void findWithinOrNearTest() {
	final List<Customer> toBeRetrieved = new LinkedList<>();
	final Customer customer1 = new Customer("---", "", 0);
	customer1.setLocation(new int[] { 45, 2 });
	toBeRetrieved.add(customer1);
	final Customer customer2 = new Customer("+++", "", 0);
	customer2.setLocation(new int[] { 60, 1 });
	toBeRetrieved.add(customer2);
	repository.saveAll(toBeRetrieved);
	final Customer customer3 = new Customer("---", "", 0);
	customer3.setLocation(new int[] { 0, 180 });
	repository.save(customer3);
	final double distanceInMeters = convertAngleToDistance(30);
	final Distance distance = new Distance(distanceInMeters / 1000, Metrics.KILOMETERS);
	final Circle circle = new Circle(new Point(0, 20), distance);
	final Iterable<Customer> retrieved = repository.findByLocationWithinOrNameAndLocationNear(circle, "+++",
		new Point(0, 0));
	assertTrue(equals(toBeRetrieved, retrieved, cmp, eq, false));
}
 
Example 5
Source Project: spring-data   Source File: DerivedQueryCreatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void geoPageTest() {
	final Customer customer1 = new Customer("", "", 0);
	customer1.setLocation(new int[] { 2, 0 });
	repository.save(customer1);
	final Customer customer2 = new Customer("", "", 0);
	customer2.setLocation(new int[] { 3, 0 });
	repository.save(customer2);
	final Customer customer3 = new Customer("", "", 0);
	customer3.setLocation(new int[] { 4, 0 });
	repository.save(customer3);
	final Customer customer4 = new Customer("", "", 0);
	customer4.setLocation(new int[] { 6, 0 });
	repository.save(customer4);
	final GeoPage<Customer> retrieved = repository.findByLocationNear(new Point(0, 0), PageRequest.of(1, 2));
	final List<GeoResult<Customer>> expectedGeoResults = new LinkedList<>();
	expectedGeoResults.add(new GeoResult<>(customer3,
			new Distance(getDistanceBetweenPoints(new Point(0, 0), new Point(0, 4)) / 1000, Metrics.KILOMETERS)));
	expectedGeoResults.add(new GeoResult<>(customer4,
			new Distance(getDistanceBetweenPoints(new Point(0, 0), new Point(0, 6)) / 1000, Metrics.KILOMETERS)));
	assertEquals(4, retrieved.getTotalElements());
	assertEquals(2, retrieved.getTotalPages());
	assertTrue(equals(expectedGeoResults, retrieved, geoCmp, geoEq, true));
}
 
Example 6
Source Project: spring-data-examples   Source File: StoresController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Looks up the stores in the given distance around the given location.
 *
 * @param model the {@link Model} to populate.
 * @param location the optional location, if none is given, no search results will be returned.
 * @param distance the distance to use, if none is given the {@link #DEFAULT_DISTANCE} is used.
 * @param pageable the pagination information
 * @return
 */
@RequestMapping(value = "/", method = RequestMethod.GET)
String index(Model model, @RequestParam Optional<Point> location, @RequestParam Optional<Distance> distance,
		Pageable pageable) {

	Point point = location.orElse(KNOWN_LOCATIONS.get("Timesquare NY"));

	Page<Store> stores = repository.findByAddressLocationNear(point, distance.orElse(DEFAULT_DISTANCE), pageable);

	model.addAttribute("stores", stores);
	model.addAttribute("distances", DISTANCES);
	model.addAttribute("selectedDistance", distance.orElse(DEFAULT_DISTANCE));
	model.addAttribute("location", point);
	model.addAttribute("locations", KNOWN_LOCATIONS);
	model.addAttribute("api",
			entityLinks.linkToSearchResource(Store.class, LinkRelation.of("by-location"), pageable).getHref());

	return "index";
}
 
Example 7
/**
 * Test case to show the usage of the geo-spatial APIs to lookup people within a given distance of a reference point.
 */
@Test
public void exposesGeoSpatialFunctionality() {

	GeospatialIndex indexDefinition = new GeospatialIndex("address.location");
	indexDefinition.getIndexOptions().put("min", -180);
	indexDefinition.getIndexOptions().put("max", 180);

	operations.indexOps(Customer.class).ensureIndex(indexDefinition);

	Customer ollie = new Customer("Oliver", "Gierke");
	ollie.setAddress(new Address(new Point(52.52548, 13.41477)));
	ollie = repository.save(ollie);

	Point referenceLocation = new Point(52.51790, 13.41239);
	Distance oneKilometer = new Distance(1, Metrics.KILOMETERS);

	GeoResults<Customer> result = repository.findByAddressLocationNear(referenceLocation, oneKilometer);

	assertThat(result.getContent(), hasSize(1));

	Distance distanceToFirstStore = result.getContent().get(0).getDistance();
	assertThat(distanceToFirstStore.getMetric(), is(Metrics.KILOMETERS));
	assertThat(distanceToFirstStore.getValue(), closeTo(0.862, 0.001));
}
 
Example 8
Source Project: spring-data-hazelcast   Source File: QueryIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void countByLocationNear() {

    final City mumbai = new City("1001", "Mumbai", new Point(19.0990358,72.9612976));
    final City pune = new City("1002", "Pune", new Point(18.5247663,73.792756));
    final City bangalore = new City("1003", "Bangalore", new Point(12.9542944,77.4905127));

    Point solapur = new Point(17.661548,75.8835121);

    this.cityMap.put(mumbai.getId(), mumbai);
    this.cityMap.put(pune.getId(), pune);
    this.cityMap.put(bangalore.getId(), bangalore);

    Long cities = this.cityRepository.countByLocationNear(solapur, new Distance(100, Metrics.KILOMETERS));
    assertThat("Nothing should returned", cities, equalTo(0L));

    cities = this.cityRepository.countByLocationNear(solapur, new Distance(250, Metrics.KILOMETERS));
    assertThat("Pune should return", cities, equalTo(1L));

    cities = this.cityRepository.countByLocationNear(solapur, new Distance(350, Metrics.KILOMETERS));
    assertThat("Pune and Mumbai should return", cities, equalTo(2L));

    this.cityMap.remove(mumbai.getId());
    this.cityMap.remove(pune.getId());
    this.cityMap.remove(bangalore.getId());
}
 
Example 9
Source Project: sdn-rx   Source File: Neo4jQuerySupport.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Converts parameter as needed by the query generated, which is not covered by standard conversion services.
 *
 * @param parameter The parameter to fit into the generated query.
 * @return A parameter that fits the place holders of a generated query
 */
final Object convertParameter(Object parameter) {

	if (parameter == null) {
		// According to https://neo4j.com/docs/cypher-manual/current/syntax/working-with-null/#cypher-null-intro
		// it does not make any sense to continue if a `null` value gets into a comparison
		// but we just warn the users and do not throw an exception on `null`.
		log.warn("Do not use `null` as a property value for comparison."
			+ " It will always be false and return an empty result.");

		return Values.NULL;
	}

	// Maybe move all of those into Neo4jConverter at some point.
	if (parameter instanceof Range) {
		return convertRange((Range) parameter);
	} else if (parameter instanceof Distance) {
		return calculateDistanceInMeter((Distance) parameter);
	} else if (parameter instanceof Circle) {
		return convertCircle((Circle) parameter);
	} else if (parameter instanceof Instant) {
		return ((Instant) parameter).atOffset(ZoneOffset.UTC);
	} else if (parameter instanceof Box) {
		return convertBox((Box) parameter);
	} else if (parameter instanceof BoundingBox) {
		return convertBoundingBox((BoundingBox) parameter);
	}

	// Good hook to check the NodeManager whether the thing is an entity and we replace the value with a known id.
	return mappingContext.getConverter()
		.writeValueFromProperty(parameter, ClassTypeInformation.from(parameter.getClass()));
}
 
Example 10
Source Project: sdn-rx   Source File: Neo4jQuerySupport.java    License: Apache License 2.0 5 votes vote down vote up
private static double calculateDistanceInMeter(Distance distance) {

		if (distance.getMetric() == Metrics.KILOMETERS) {
			double kilometersDivisor = 0.001d;
			return distance.getValue() / kilometersDivisor;

		} else if (distance.getMetric() == Metrics.MILES) {
			double milesDivisor = 0.00062137d;
			return distance.getValue() / milesDivisor;

		} else {
			return distance.getValue();
		}
	}
 
Example 11
Source Project: sdn-rx   Source File: CypherQueryCreator.java    License: Apache License 2.0 5 votes vote down vote up
private Condition createNearCondition(Neo4jPersistentProperty persistentProperty,
	Iterator<Object> actualParameters) {

	Parameter p1 = nextRequiredParameter(actualParameters);
	Optional<Parameter> p2 = nextOptionalParameter(actualParameters);

	Expression referencePoint;

	Optional<Parameter> other;
	if (p1.value instanceof Point) {
		referencePoint = toCypherParameter(p1, false);
		other = p2;
	} else if (p2.isPresent() && p2.get().value instanceof Point) {
		referencePoint = toCypherParameter(p2.get(), false);
		other = Optional.of(p1);
	} else {
		throw new IllegalArgumentException(
			String.format("The NEAR operation requires a reference point of type %s", Point.class));
	}

	Expression distanceFunction = Functions.distance(toCypherProperty(persistentProperty, false), referencePoint);

	if (other.filter(p -> p.hasValueOfType(Distance.class)).isPresent()) {
		return distanceFunction.lte(toCypherParameter(other.get(), false));
	} else if (other.filter(p -> p.hasValueOfType(Range.class)).isPresent()) {
		return createRangeConditionForProperty(distanceFunction, other.get());
	} else {
		// We only have a point toCypherParameter, that's ok, but we have to put back the last toCypherParameter when it wasn't null
		other.ifPresent(this.lastParameter::offer);

		// Also, we cannot filter, but need to sort in the end.
		this.sortItems.add(distanceFunction.ascending());
		return Conditions.noCondition();
	}
}
 
Example 12
Source Project: flash-waimai   Source File: MongoRepository.java    License: MIT License 5 votes vote down vote up
/**
 * 查询指定位置附近的商家
 * @param x
 * @param y
 * @param collectionName
 * @param params
 * @param miles 公里数
 * @return
 */
public GeoResults<Map> near(double x, double y, String collectionName, Map<String, Object> params,Integer miles) {
    Point location = new Point(x, y);
    NearQuery nearQuery = NearQuery.near(location).maxDistance(new Distance(miles, Metrics.MILES));
    if (params != null && !params.isEmpty()) {
        Query query = Query.query(criteria(params));
        nearQuery.query(query);
    }
    try {
        return mongoTemplate.geoNear(nearQuery, Map.class, collectionName);
    }catch (Exception e){
        System.out.println(e.getMessage());
    }
    return null;
}
 
Example 13
Source Project: spring-data   Source File: BindParameterBinding.java    License: Apache License 2.0 5 votes vote down vote up
private int bindRange(final Range<?> range, int index) {
	Object lowerBound = range.getLowerBound().getValue().get();
	Object upperBound = range.getUpperBound().getValue().get();
	if (lowerBound.getClass() == Distance.class && upperBound.getClass() == lowerBound.getClass()) {
		lowerBound = convertDistanceToMeters((Distance) lowerBound);
		upperBound = convertDistanceToMeters((Distance) upperBound);
	}
	bind(index++, lowerBound);
	bind(index++, upperBound);
	return index;
}
 
Example 14
Source Project: spring-data   Source File: CustomerRepository.java    License: Apache License 2.0 5 votes vote down vote up
GeoResults<Customer> findByNameOrSurnameAndLocationWithinOrLocationWithin(
String name,
String surname,
Point location1,
Distance distance,
Point location2,
Range<Distance> distanceRange);
 
Example 15
Source Project: spring-data   Source File: DerivedQueryCreatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void geoResultsTest() {
	final List<Customer> toBeRetrieved = new LinkedList<>();
	final Customer customer1 = new Customer("", "", 0);
	customer1.setLocation(new int[] { 43, 21 });
	toBeRetrieved.add(customer1);
	final Customer customer2 = new Customer("", "", 0);
	customer2.setLocation(new int[] { 21, 43 });
	toBeRetrieved.add(customer2);
	repository.saveAll(toBeRetrieved);
	final Customer customer3 = new Customer("", "", 0);
	customer3.setLocation(new int[] { 70, 50 });
	repository.save(customer3);
	final Customer customer4 = new Customer("", "", 0);
	customer4.setLocation(new int[] { 3, 2 });
	repository.save(customer4);
	final Bound<Double> lowerBound = Bound.inclusive(convertAngleToDistance(30));
	final Bound<Double> upperBound = Bound.inclusive(convertAngleToDistance(50));
	final GeoResults<Customer> retrieved = repository.findByLocationWithin(new Point(1, 0),
		Range.of(lowerBound, upperBound));
	final List<GeoResult<Customer>> expectedGeoResults = new LinkedList<>();
	expectedGeoResults.add(new GeoResult<>(customer1,
			new Distance(getDistanceBetweenPoints(new Point(1, 0), new Point(21, 43)) / 1000, Metrics.KILOMETERS)));
	expectedGeoResults.add(new GeoResult<>(customer2,
			new Distance(getDistanceBetweenPoints(new Point(1, 0), new Point(43, 21)) / 1000, Metrics.KILOMETERS)));
	assertTrue(equals(expectedGeoResults, retrieved, geoCmp, geoEq, false));
}
 
Example 16
Source Project: spring-data   Source File: DerivedQueryCreatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void buildPredicateWithDistanceTest() {
	final List<Customer> toBeRetrieved = new LinkedList<>();
	final Customer customer1 = new Customer("+", "", 0);
	customer1.setLocation(new int[] { 89, 89 });
	toBeRetrieved.add(customer1);
	final Customer customer2 = new Customer("", "+", 0);
	customer2.setLocation(new int[] { 5, 0 });
	toBeRetrieved.add(customer2);
	final Customer customer3 = new Customer("", "", 0);
	customer3.setLocation(new int[] { 0, 25 });
	toBeRetrieved.add(customer3);
	repository.saveAll(toBeRetrieved);
	final Customer customer4 = new Customer("", "", 0);
	customer4.setLocation(new int[] { 15, 0 });
	repository.save(customer4);
	final Customer customer5 = new Customer("", "", 0);
	customer5.setLocation(new int[] { 0, 35 });
	repository.save(customer5);
	final double distanceInMeters = convertAngleToDistance(10);
	final Distance distance = new Distance(distanceInMeters / 1000, Metrics.KILOMETERS);
	final Range<Distance> distanceRange = Range.of(
		Bound.inclusive(new Distance(convertAngleToDistance(20) / 1000, Metrics.KILOMETERS)),
		Bound.inclusive(new Distance(convertAngleToDistance(30) / 1000, Metrics.KILOMETERS)));
	final Point location = new Point(0, 0);
	final GeoResults<Customer> retrieved = repository.findByNameOrSurnameAndLocationWithinOrLocationWithin("+", "+",
		location, distance, location, distanceRange);
	final List<GeoResult<Customer>> expectedGeoResults = new LinkedList<>();
	expectedGeoResults.add(new GeoResult<>(customer1,
			new Distance(getDistanceBetweenPoints(location, new Point(89, 89)) / 1000, Metrics.KILOMETERS)));
	expectedGeoResults.add(new GeoResult<>(customer2,
			new Distance(getDistanceBetweenPoints(location, new Point(0, 5)) / 1000, Metrics.KILOMETERS)));
	expectedGeoResults.add(new GeoResult<>(customer3,
			new Distance(getDistanceBetweenPoints(location, new Point(25, 0)) / 1000, Metrics.KILOMETERS)));
	assertTrue(equals(expectedGeoResults, retrieved, geoCmp, geoEq, false));
}
 
Example 17
Source Project: dubbox   Source File: SolrQueryCreator.java    License: Apache License 2.0 5 votes vote down vote up
private Criteria createNearCriteria(Iterator<?> parameters, Criteria criteria) {
	Object value = getBindableValue((BindableSolrParameter) parameters.next());
	if (value instanceof Box) {
		return criteria.near((Box) value);
	} else {
		return criteria.near((Point) value, (Distance) getBindableValue((BindableSolrParameter) parameters.next()));
	}
}
 
Example 18
Source Project: dubbox   Source File: QueryParserBase.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object doProcess(Predicate predicate, Field field) {
	String nearFragment;
	Object[] args = (Object[]) predicate.getValue();
	if (args[0] instanceof Box) {
		Box box = (Box) args[0];
		nearFragment = field.getName() + ":[";
		nearFragment += createRangeFragment(box.getFirst(), box.getSecond());
		nearFragment += "]";
	} else {
		nearFragment = createSpatialFunctionFragment(field.getName(),
				(org.springframework.data.geo.Point) args[0], (Distance) args[1], "bbox");
	}
	return nearFragment;
}
 
Example 19
Source Project: dubbox   Source File: QueryParserBase.java    License: Apache License 2.0 5 votes vote down vote up
protected String createSpatialFunctionFragment(String fieldName, org.springframework.data.geo.Point location,
		Distance distance, String function) {
	String spatialFragment = "{!" + function + " " + SpatialParams.POINT + "=";
	spatialFragment += filterCriteriaValue(location);
	spatialFragment += " " + SpatialParams.FIELD + "=" + fieldName;
	spatialFragment += " " + SpatialParams.DISTANCE + "=" + filterCriteriaValue(distance);
	spatialFragment += "}";
	return spatialFragment;
}
 
Example 20
Source Project: spring-data-examples   Source File: GeoOperationsTests.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Look up points using a geo-index member as reference.
 */
@Test
public void geoRadiusByMember() {

	GeoResults<GeoLocation<String>> byDistance = geoOperations.geoRadiusByMember("Sicily", "Palermo",
			new Distance(100, DistanceUnit.KILOMETERS));

	assertThat(byDistance).hasSize(2).extracting("content.name").contains("Arigento", "Palermo");

	GeoResults<GeoLocation<String>> greaterDistance = geoOperations.geoRadiusByMember("Sicily", "Palermo",
			new Distance(200, DistanceUnit.KILOMETERS));

	assertThat(greaterDistance).hasSize(3).extracting("content.name").contains("Arigento", "Catania", "Palermo");
}
 
Example 21
Source Project: spring-data-examples   Source File: GeoOperationsTests.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Lookup points within a circle around coordinates.
 */
@Test
public void geoRadius() {

	Circle circle = new Circle(new Point(13.583333, 37.316667), //
			new Distance(100, DistanceUnit.KILOMETERS));
	GeoResults<GeoLocation<String>> result = geoOperations.geoRadius("Sicily", circle);

	assertThat(result).hasSize(2).extracting("content.name").contains("Arigento", "Palermo");
}
 
Example 22
Source Project: tutorials   Source File: CampusServiceImplLiveTest.java    License: MIT License 5 votes vote down vote up
@Test
public final void whenFindByLocationNearBoston_thenResultContainsHarvard() throws Exception {
    Set<Campus> campuses = campusService.findByLocationNear(Boston, new Distance(1, Metrics.NEUTRAL));
    assertFalse(campuses.isEmpty());
    assertTrue(campuses.contains(Harvard));
    assertFalse(campuses.contains(Columbia));
}
 
Example 23
/**
 * Find entity by a {@link GeoIndexed} property on an embedded entity.
 */
@Test
public void findByGeoLocationProperty() {

	Address winterfell = new Address();
	winterfell.setCountry("the north");
	winterfell.setCity("winterfell");
	winterfell.setLocation(new Point(52.9541053, -1.2401016));

	eddard.setAddress(winterfell);

	Address casterlystein = new Address();
	casterlystein.setCountry("Westerland");
	casterlystein.setCity("Casterlystein");
	casterlystein.setLocation(new Point(51.5287352, -0.3817819));

	robb.setAddress(casterlystein);

	flushTestUsers();

	Circle innerCircle = new Circle(new Point(51.8911912, -0.4979756), new Distance(50, Metrics.KILOMETERS));
	List<Person> eddardStark = repository.findByAddress_LocationWithin(innerCircle);

	assertThat(eddardStark).containsOnly(robb);

	Circle biggerCircle = new Circle(new Point(51.8911912, -0.4979756), new Distance(200, Metrics.KILOMETERS));
	List<Person> eddardAndRobbStark = repository.findByAddress_LocationWithin(biggerCircle);

	assertThat(eddardAndRobbStark).hasSize(2).contains(robb, eddard);
}
 
Example 24
@Test
public void findsStoresByLocation() {

	Point location = new Point(-73.995146, 40.740337);
	Store store = new Store(UUID.randomUUID(), "Foo", new Address("street", "city", "zip", location));

	store = repository.save(store);

	Page<Store> stores = repository.findByAddressLocationNear(location, new Distance(1.0, Metrics.KILOMETERS),
			PageRequest.of(0, 10));

	assertThat(stores.getContent(), hasSize(1));
	assertThat(stores.getContent(), hasItem(store));
}
 
Example 25
Source Project: redisson   Source File: RedissonConnection.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public GeoResults<GeoLocation<byte[]>> geoRadiusByMember(byte[] key, byte[] member, Distance radius,
        GeoRadiusCommandArgs args) {
    List<Object> params = new ArrayList<Object>();
    params.add(key);
    params.add(member);
    params.add(radius.getValue());
    params.add(radius.getMetric().getAbbreviation());
    
    RedisCommand<GeoResults<GeoLocation<byte[]>>> command;
    if (args.getFlags().contains(GeoRadiusCommandArgs.Flag.WITHCOORD)) {
        command = new RedisCommand<GeoResults<GeoLocation<byte[]>>>("GEORADIUSBYMEMBER", postitionDecoder);
        params.add("WITHCOORD");
    } else {
        MultiDecoder<GeoResults<GeoLocation<byte[]>>> distanceDecoder = new ListMultiDecoder2(new GeoResultsDecoder(radius.getMetric()), new GeoDistanceDecoder());
        command = new RedisCommand<GeoResults<GeoLocation<byte[]>>>("GEORADIUSBYMEMBER", distanceDecoder);
        params.add("WITHDIST");
    }
    
    if (args.getLimit() != null) {
        params.add("COUNT");
        params.add(args.getLimit());
    }
    if (args.getSortDirection() != null) {
        params.add(args.getSortDirection().name());
    }
    
    return read(key, ByteArrayCodec.INSTANCE, command, params.toArray());
}
 
Example 26
Source Project: tutorials   Source File: CampusServiceImplLiveTest.java    License: MIT License 5 votes vote down vote up
@Test
public final void whenFindByLocationNearNewYorkCity_thenResultContainsColumbia() throws Exception {
    Set<Campus> campuses = campusService.findByLocationNear(NewYorkCity, new Distance(1, Metrics.NEUTRAL));
    assertFalse(campuses.isEmpty());
    assertTrue(campuses.contains(Columbia));
    assertFalse(campuses.contains(Harvard));
}
 
Example 27
Source Project: redisson   Source File: RedissonConnection.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public GeoResults<GeoLocation<byte[]>> geoRadiusByMember(byte[] key, byte[] member, Distance radius,
        GeoRadiusCommandArgs args) {
    List<Object> params = new ArrayList<Object>();
    params.add(key);
    params.add(member);
    params.add(radius.getValue());
    params.add(radius.getMetric().getAbbreviation());
    
    RedisCommand<GeoResults<GeoLocation<byte[]>>> command;
    if (args.getFlags().contains(GeoRadiusCommandArgs.Flag.WITHCOORD)) {
        command = new RedisCommand<GeoResults<GeoLocation<byte[]>>>("GEORADIUSBYMEMBER", postitionDecoder);
        params.add("WITHCOORD");
    } else {
        MultiDecoder<GeoResults<GeoLocation<byte[]>>> distanceDecoder = new ListMultiDecoder2(new GeoResultsDecoder(radius.getMetric()), new GeoDistanceDecoder());
        command = new RedisCommand<GeoResults<GeoLocation<byte[]>>>("GEORADIUSBYMEMBER", distanceDecoder);
        params.add("WITHDIST");
    }
    
    if (args.getLimit() != null) {
        params.add("COUNT");
        params.add(args.getLimit());
    }
    if (args.getSortDirection() != null) {
        params.add(args.getSortDirection().name());
    }
    
    return read(key, ByteArrayCodec.INSTANCE, command, params.toArray());
}
 
Example 28
Source Project: redisson   Source File: RedissonConnection.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public GeoResults<GeoLocation<byte[]>> geoRadiusByMember(byte[] key, byte[] member, Distance radius,
        GeoRadiusCommandArgs args) {
    List<Object> params = new ArrayList<Object>();
    params.add(key);
    params.add(member);
    params.add(radius.getValue());
    params.add(radius.getMetric().getAbbreviation());
    
    RedisCommand<GeoResults<GeoLocation<byte[]>>> command;
    if (args.getFlags().contains(GeoRadiusCommandArgs.Flag.WITHCOORD)) {
        command = new RedisCommand<GeoResults<GeoLocation<byte[]>>>("GEORADIUSBYMEMBER", postitionDecoder);
        params.add("WITHCOORD");
    } else {
        MultiDecoder<GeoResults<GeoLocation<byte[]>>> distanceDecoder = new ListMultiDecoder2(new GeoResultsDecoder(radius.getMetric()), new GeoDistanceDecoder());
        command = new RedisCommand<GeoResults<GeoLocation<byte[]>>>("GEORADIUSBYMEMBER", distanceDecoder);
        params.add("WITHDIST");
    }
    
    if (args.getLimit() != null) {
        params.add("COUNT");
        params.add(args.getLimit());
    }
    if (args.getSortDirection() != null) {
        params.add(args.getSortDirection().name());
    }
    
    return read(key, ByteArrayCodec.INSTANCE, command, params.toArray());
}
 
Example 29
Source Project: redisson   Source File: RedissonConnection.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public GeoResults<GeoLocation<byte[]>> geoRadiusByMember(byte[] key, byte[] member, Distance radius,
        GeoRadiusCommandArgs args) {
    List<Object> params = new ArrayList<Object>();
    params.add(key);
    params.add(member);
    params.add(radius.getValue());
    params.add(radius.getMetric().getAbbreviation());
    
    RedisCommand<GeoResults<GeoLocation<byte[]>>> command;
    if (args.getFlags().contains(GeoRadiusCommandArgs.Flag.WITHCOORD)) {
        command = new RedisCommand<GeoResults<GeoLocation<byte[]>>>("GEORADIUSBYMEMBER", postitionDecoder);
        params.add("WITHCOORD");
    } else {
        MultiDecoder<GeoResults<GeoLocation<byte[]>>> distanceDecoder = new ListMultiDecoder2(new GeoResultsDecoder(radius.getMetric()), new GeoDistanceDecoder());
        command = new RedisCommand<GeoResults<GeoLocation<byte[]>>>("GEORADIUSBYMEMBER", distanceDecoder);
        params.add("WITHDIST");
    }
    
    if (args.getLimit() != null) {
        params.add("COUNT");
        params.add(args.getLimit());
    }
    if (args.getSortDirection() != null) {
        params.add(args.getSortDirection().name());
    }
    
    return read(key, ByteArrayCodec.INSTANCE, command, params.toArray());
}
 
Example 30
Source Project: spring-data-hazelcast   Source File: QueryIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void findByLocationNearWithDistance() {

    final City mumbai = new City("1001", "Mumbai", new Point(19.0990358,72.9612976));
    final City pune = new City("1002", "Pune", new Point(18.5247663,73.792756));
    final City bangalore = new City("1003", "Bangalore", new Point(12.9542944,77.4905127));

    Point solapur = new Point(17.661548,75.8835121);

    this.cityMap.put(mumbai.getId(), mumbai);
    this.cityMap.put(pune.getId(), pune);
    this.cityMap.put(bangalore.getId(), bangalore);

    List<City> matches = this.cityRepository.findByLocationNear(solapur, new Distance(100, Metrics.KILOMETERS));
    int len = matches.size();
    assertThat("Nothing should returned", len, equalTo(0));

    matches = this.cityRepository.findByLocationNear(solapur, new Distance(250, Metrics.KILOMETERS));
    len = matches.size();
    assertThat("Pune should return", len, equalTo(1));
    assertThat("Pune should return", matches.get(0), equalTo(pune));

    matches = this.cityRepository.findByLocationNear(solapur, new Distance(350, Metrics.KILOMETERS));
    len = matches.size();
    assertThat("Pune and Mumbai should return", len, equalTo(2));
    assertThat("Pune and Mumbai should return", matches, containsInAnyOrder(pune, mumbai));

    this.cityMap.remove(mumbai.getId());
    this.cityMap.remove(pune.getId());
    this.cityMap.remove(bangalore.getId());
}