[ 
https://issues.apache.org/jira/browse/TINKERPOP-2558?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=18146562#comment-18146562
 ] 

ASF GitHub Bot commented on TINKERPOP-2558:
-------------------------------------------

kenhuuu commented on code in PR #3809:
URL: https://github.com/apache/tinkerpop/pull/3809#discussion_r4609520818


##########
gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/GeoP.java:
##########
@@ -0,0 +1,405 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.process.traversal;
+
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
+import org.apache.tinkerpop.gremlin.process.traversal.step.GValue;
+import org.apache.tinkerpop.gremlin.structure.geo.Geometry;
+import org.apache.tinkerpop.gremlin.structure.geo.Model;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Predefined {@code Predicate} values that filter {@link Geometry} values by 
a spatial
+ * relationship, backed by the {@link Geo} predicates.
+ * <p>
+ * For {@code geoWithinDistance}, {@link #getValue()} is a two element list of 
the geometry and the
+ * distance, in that order.
+ * <p>
+ * An argument may instead come from a child traversal, which is resolved 
against each traverser.
+ * {@code geoWithinDistance} then holds a child traversal for each of its two 
arguments, and a
+ * constant given beside a traversal is carried as a constant traversal. An 
argument may also be a
+ * {@link GValue}, whose value is resolved when the traversal is built.
+ * <p>
+ * <b>Accuracy in the geographic model.</b> Distances are measured on a sphere 
of the WGS84 mean
+ * radius, within about 1% of WGS84. Edges are straight in longitude and 
latitude, so the relate
+ * predicates, and distances between shapes other than two points, hold for 
edges under about
+ * 100 km that cross neither the antimeridian nor a pole.
+ *
+ * @since 4.0.0
+ */
+public class GeoP extends P<Object> {

Review Comment:
   Using GeoP with `is()` exposes a typing problem:
   
   ```
   GraphTraversal<?, Geometry> locations = g.V().values("location");
   locations.is(GeoP.geoWithin(region)); // does not compile
   ```
   
   `is()` expects a `P<Geometry>`, but GeoP is a `P<Object>`.
   
   The underlying issue is that `P<V>` uses V for both the value being tested 
and the predicate argument. That works for geoWithin, which compares a Geometry 
with another Geometry, but not for geoWithinDistance, which compares a Geometry 
with arguments containing both a Geometry and a Number. This appears to be why 
GeoP was widened to Object.



##########
gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/GeoP.java:
##########
@@ -0,0 +1,405 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.process.traversal;
+
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
+import org.apache.tinkerpop.gremlin.process.traversal.step.GValue;
+import org.apache.tinkerpop.gremlin.structure.geo.Geometry;
+import org.apache.tinkerpop.gremlin.structure.geo.Model;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Predefined {@code Predicate} values that filter {@link Geometry} values by 
a spatial
+ * relationship, backed by the {@link Geo} predicates.
+ * <p>
+ * For {@code geoWithinDistance}, {@link #getValue()} is a two element list of 
the geometry and the
+ * distance, in that order.
+ * <p>
+ * An argument may instead come from a child traversal, which is resolved 
against each traverser.
+ * {@code geoWithinDistance} then holds a child traversal for each of its two 
arguments, and a
+ * constant given beside a traversal is carried as a constant traversal. An 
argument may also be a
+ * {@link GValue}, whose value is resolved when the traversal is built.
+ * <p>
+ * <b>Accuracy in the geographic model.</b> Distances are measured on a sphere 
of the WGS84 mean
+ * radius, within about 1% of WGS84. Edges are straight in longitude and 
latitude, so the relate
+ * predicates, and distances between shapes other than two points, hold for 
edges under about
+ * 100 km that cross neither the antimeridian nor a pole.
+ *
+ * @since 4.0.0
+ */
+public class GeoP extends P<Object> {
+
+    /**
+     * {@code geoWithinDistance}'s arguments as they were given, each either a 
value or a
+     * {@link GValue}, so that the pair can be rebuilt when a variable takes a 
new value. Null
+     * unless one of the arguments is a variable.
+     */
+    private final List<Object> arguments;
+
+    /**
+     * Constructs a {@code GeoP} from the argument as it was given, which is 
validated unless it is
+     * a child traversal.
+     *
+     * @since 4.0.0
+     */
+    public GeoP(final PBiPredicate<Object, Object> biPredicate, final Object 
value) {
+        super(biPredicate, value);
+        this.arguments = null;
+        if (!hasTraversal()) {
+            validateConstants(biPredicate, value);
+        }
+    }
+
+    /**
+     * Constructs a {@code GeoP} with a child traversal whose result is 
resolved at runtime against
+     * the current traverser.
+     *
+     * @since 4.0.0
+     */
+    public GeoP(final PBiPredicate<Object, Object> biPredicate, final 
Traversal.Admin<?, ?> traversalValue) {
+        super(biPredicate, traversalValue);
+        this.arguments = null;
+    }
+
+    /**
+     * Constructs a {@code GeoP} from a variable, whose value is validated 
once it is resolved.
+     *
+     * @since 4.0.0
+     */
+    @SuppressWarnings("unchecked")
+    public GeoP(final PBiPredicate<Object, Object> biPredicate, final 
GValue<?> value) {
+        super(biPredicate, (GValue<Object>) value);
+        this.arguments = null;
+        validateConstants(biPredicate, getValue());
+    }
+
+    /**
+     * Constructs a {@code GeoP} from arguments kept in the order they were 
written, so that a
+     * variable among them stays bound to the argument it was given for.
+     */
+    private GeoP(final PBiPredicate<Object, Object> biPredicate, final 
List<Object> arguments,
+                 final Map<String, Object> variables) {
+        super(biPredicate, 
Collections.<Object>singletonList(resolve(arguments, variables)), variables, 
false);
+        this.arguments = Collections.unmodifiableList(new 
ArrayList<>(arguments));
+        validateConstants(biPredicate, getValue());
+    }
+
+    @Override
+    public boolean equals(final Object other) {
+        return other instanceof GeoP && super.equals(other);
+    }
+
+    @Override
+    public P<Object> negate() {
+        return new NotP<>(this);
+    }
+
+    public GeoP clone() {
+        return (GeoP) super.clone();
+    }
+
+    /**
+     * {@inheritDoc}
+     * <p>
+     * A new value for one of this predicate's variables is validated as the 
same value given to a
+     * constructor would be.
+     */
+    @Override
+    public void updateVariable(final String name, final Object value) {
+        super.updateVariable(name, value);
+        if (!variables.containsKey(name)) return;
+        if (null != arguments) {
+            literals = Collections.singletonList((Object) resolve(arguments, 
variables));
+        }
+        if (!hasTraversal()) {
+            validateConstants(biPredicate, getValue());
+        }
+    }
+
+    //////////////// statics
+
+    /**
+     * Determines if a geometry lies entirely inside the given geometry. A 
value that lies only on
+     * the given geometry's boundary is not within it.
+     *
+     * @since 4.0.0
+     */
+    public static GeoP geoWithin(final Geometry value) {
+        return new GeoP(Geo.geoWithin, value);
+    }
+
+    /**
+     * Determines if a geometry lies entirely inside the geometry a variable 
holds.
+     *
+     * @since 4.0.0
+     */
+    public static GeoP geoWithin(final GValue<Geometry> value) {
+        return ofGeometry(Geo.geoWithin, value);
+    }
+
+    /**
+     * Determines if a geometry lies entirely inside the geometry resolved 
from a child traversal
+     * at runtime.
+     *
+     * @since 4.0.0
+     */
+    public static GeoP geoWithin(final Traversal<?, ?> traversalValue) {
+        return new GeoP(Geo.geoWithin, traversalValue.asAdmin());
+    }
+
+    /**
+     * Determines if a geometry entirely contains the given geometry. A 
geometry does not contain a
+     * value that lies only on its boundary.
+     *
+     * @since 4.0.0
+     */
+    public static GeoP geoContains(final Geometry value) {
+        return new GeoP(Geo.geoContains, value);
+    }
+
+    /**
+     * Determines if a geometry entirely contains the geometry a variable 
holds.
+     *
+     * @since 4.0.0
+     */
+    public static GeoP geoContains(final GValue<Geometry> value) {
+        return ofGeometry(Geo.geoContains, value);
+    }
+
+    /**
+     * Determines if a geometry entirely contains the geometry resolved from a 
child traversal at
+     * runtime.
+     *
+     * @since 4.0.0
+     */
+    public static GeoP geoContains(final Traversal<?, ?> traversalValue) {
+        return new GeoP(Geo.geoContains, traversalValue.asAdmin());
+    }
+
+    /**
+     * Determines if the distance between a geometry and the given geometry is 
at most
+     * {@code distance}, in coordinate units for {@link Model#CARTESIAN} and 
in meters for
+     * {@link Model#GEOGRAPHIC}.
+     *
+     * @since 4.0.0
+     */
+    public static GeoP geoWithinDistance(final Geometry value, final Number 
distance) {
+        return ofPair(value, distance);
+    }
+
+    /**
+     * Determines if the distance between a geometry and the geometry a 
variable holds is at most
+     * {@code distance}.
+     *
+     * @since 4.0.0
+     */
+    public static GeoP geoWithinDistance(final GValue<Geometry> value, final 
Number distance) {
+        return ofPair(value, distance);
+    }
+
+    /**
+     * Determines if the distance between a geometry and the given geometry is 
at most the distance
+     * a variable holds.
+     *
+     * @since 4.0.0
+     */
+    public static GeoP geoWithinDistance(final Geometry value, final 
GValue<Number> distance) {
+        return ofPair(value, distance);
+    }
+
+    /**
+     * Determines if the distance between a geometry and the geometry a 
variable holds is at most
+     * the distance a variable holds.
+     *
+     * @since 4.0.0
+     */
+    public static GeoP geoWithinDistance(final GValue<Geometry> value, final 
GValue<Number> distance) {
+        return ofPair(value, distance);
+    }
+
+    /**
+     * Determines if the distance between a geometry and the geometry resolved 
from a child
+     * traversal at runtime is at most {@code distance}.
+     *
+     * @since 4.0.0
+     */
+    public static GeoP geoWithinDistance(final Traversal<?, ?> traversalValue, 
final Number distance) {
+        validateDistance(Geo.geoWithinDistance.getPredicateName(), distance);
+        return new GeoP(Geo.geoWithinDistance, 
Arrays.asList(traversalValue.asAdmin(), __.constant(distance)));
+    }
+
+    /**
+     * Determines if the distance between a geometry and the geometry resolved 
from a child
+     * traversal at runtime is at most the distance a variable holds.
+     *
+     * @since 4.0.0
+     */
+    public static GeoP geoWithinDistance(final Traversal<?, ?> traversalValue, 
final GValue<Number> distance) {
+        if (null == distance || !distance.isVariable()) {
+            return geoWithinDistance(traversalValue, null == distance ? null : 
distance.get());
+        }
+        validateDistance(Geo.geoWithinDistance.getPredicateName(), 
distance.get());
+        return new GeoP(Geo.geoWithinDistance, 
Arrays.asList(traversalValue.asAdmin(), __.constant(distance)));

Review Comment:
   This introduces a new predicate pattern: one argument comes from a child 
traversal while another is a bindable GValue. Existing predicates either own 
the GValue directly or let the child traversal manage its own parameters.
   
   Here, wrapping the parameter in` __.constant()` breaks that model:
   
   `geoWithinDistance(__.select("region"), GValue.of("radius", 1000))`
   
   Rebinding radius to 2000 still leaves this predicate using 1000, because the 
GValue is no longer registered with parameter management. Could we preserve the 
parameter explicitly and add rebinding tests for this and the symmetric 
overload at line 289?



##########
gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/GeoP.java:
##########
@@ -0,0 +1,405 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.process.traversal;
+
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
+import org.apache.tinkerpop.gremlin.process.traversal.step.GValue;
+import org.apache.tinkerpop.gremlin.structure.geo.Geometry;
+import org.apache.tinkerpop.gremlin.structure.geo.Model;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Predefined {@code Predicate} values that filter {@link Geometry} values by 
a spatial
+ * relationship, backed by the {@link Geo} predicates.
+ * <p>
+ * For {@code geoWithinDistance}, {@link #getValue()} is a two element list of 
the geometry and the
+ * distance, in that order.
+ * <p>
+ * An argument may instead come from a child traversal, which is resolved 
against each traverser.
+ * {@code geoWithinDistance} then holds a child traversal for each of its two 
arguments, and a
+ * constant given beside a traversal is carried as a constant traversal. An 
argument may also be a
+ * {@link GValue}, whose value is resolved when the traversal is built.
+ * <p>
+ * <b>Accuracy in the geographic model.</b> Distances are measured on a sphere 
of the WGS84 mean
+ * radius, within about 1% of WGS84. Edges are straight in longitude and 
latitude, so the relate
+ * predicates, and distances between shapes other than two points, hold for 
edges under about
+ * 100 km that cross neither the antimeridian nor a pole.
+ *
+ * @since 4.0.0
+ */
+public class GeoP extends P<Object> {
+
+    /**
+     * {@code geoWithinDistance}'s arguments as they were given, each either a 
value or a
+     * {@link GValue}, so that the pair can be rebuilt when a variable takes a 
new value. Null
+     * unless one of the arguments is a variable.
+     */
+    private final List<Object> arguments;
+
+    /**
+     * Constructs a {@code GeoP} from the argument as it was given, which is 
validated unless it is
+     * a child traversal.
+     *
+     * @since 4.0.0
+     */
+    public GeoP(final PBiPredicate<Object, Object> biPredicate, final Object 
value) {
+        super(biPredicate, value);
+        this.arguments = null;
+        if (!hasTraversal()) {
+            validateConstants(biPredicate, value);
+        }
+    }
+
+    /**
+     * Constructs a {@code GeoP} with a child traversal whose result is 
resolved at runtime against
+     * the current traverser.
+     *
+     * @since 4.0.0
+     */
+    public GeoP(final PBiPredicate<Object, Object> biPredicate, final 
Traversal.Admin<?, ?> traversalValue) {
+        super(biPredicate, traversalValue);
+        this.arguments = null;
+    }
+
+    /**
+     * Constructs a {@code GeoP} from a variable, whose value is validated 
once it is resolved.
+     *
+     * @since 4.0.0
+     */
+    @SuppressWarnings("unchecked")
+    public GeoP(final PBiPredicate<Object, Object> biPredicate, final 
GValue<?> value) {
+        super(biPredicate, (GValue<Object>) value);
+        this.arguments = null;
+        validateConstants(biPredicate, getValue());
+    }
+
+    /**
+     * Constructs a {@code GeoP} from arguments kept in the order they were 
written, so that a
+     * variable among them stays bound to the argument it was given for.
+     */
+    private GeoP(final PBiPredicate<Object, Object> biPredicate, final 
List<Object> arguments,
+                 final Map<String, Object> variables) {
+        super(biPredicate, 
Collections.<Object>singletonList(resolve(arguments, variables)), variables, 
false);
+        this.arguments = Collections.unmodifiableList(new 
ArrayList<>(arguments));
+        validateConstants(biPredicate, getValue());
+    }
+
+    @Override
+    public boolean equals(final Object other) {
+        return other instanceof GeoP && super.equals(other);
+    }
+
+    @Override
+    public P<Object> negate() {
+        return new NotP<>(this);
+    }
+
+    public GeoP clone() {
+        return (GeoP) super.clone();

Review Comment:
   `super.clone()` leaves the mutable variables map shared between GeoP 
instances. Traversals are cloned for script-cache reuse and then rebound 
independently, so rebinding one clone can affect another or race with 
concurrent executions. Could the parameter state be copied during cloning?



##########
gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/GeoP.java:
##########
@@ -0,0 +1,405 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.process.traversal;
+
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
+import org.apache.tinkerpop.gremlin.process.traversal.step.GValue;
+import org.apache.tinkerpop.gremlin.structure.geo.Geometry;
+import org.apache.tinkerpop.gremlin.structure.geo.Model;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Predefined {@code Predicate} values that filter {@link Geometry} values by 
a spatial
+ * relationship, backed by the {@link Geo} predicates.
+ * <p>
+ * For {@code geoWithinDistance}, {@link #getValue()} is a two element list of 
the geometry and the
+ * distance, in that order.
+ * <p>
+ * An argument may instead come from a child traversal, which is resolved 
against each traverser.
+ * {@code geoWithinDistance} then holds a child traversal for each of its two 
arguments, and a
+ * constant given beside a traversal is carried as a constant traversal. An 
argument may also be a
+ * {@link GValue}, whose value is resolved when the traversal is built.
+ * <p>
+ * <b>Accuracy in the geographic model.</b> Distances are measured on a sphere 
of the WGS84 mean
+ * radius, within about 1% of WGS84. Edges are straight in longitude and 
latitude, so the relate
+ * predicates, and distances between shapes other than two points, hold for 
edges under about
+ * 100 km that cross neither the antimeridian nor a pole.
+ *
+ * @since 4.0.0
+ */
+public class GeoP extends P<Object> {
+
+    /**
+     * {@code geoWithinDistance}'s arguments as they were given, each either a 
value or a
+     * {@link GValue}, so that the pair can be rebuilt when a variable takes a 
new value. Null
+     * unless one of the arguments is a variable.
+     */
+    private final List<Object> arguments;
+
+    /**
+     * Constructs a {@code GeoP} from the argument as it was given, which is 
validated unless it is
+     * a child traversal.
+     *
+     * @since 4.0.0
+     */
+    public GeoP(final PBiPredicate<Object, Object> biPredicate, final Object 
value) {
+        super(biPredicate, value);
+        this.arguments = null;
+        if (!hasTraversal()) {
+            validateConstants(biPredicate, value);
+        }
+    }
+
+    /**
+     * Constructs a {@code GeoP} with a child traversal whose result is 
resolved at runtime against
+     * the current traverser.
+     *
+     * @since 4.0.0
+     */
+    public GeoP(final PBiPredicate<Object, Object> biPredicate, final 
Traversal.Admin<?, ?> traversalValue) {
+        super(biPredicate, traversalValue);
+        this.arguments = null;
+    }
+
+    /**
+     * Constructs a {@code GeoP} from a variable, whose value is validated 
once it is resolved.
+     *
+     * @since 4.0.0
+     */
+    @SuppressWarnings("unchecked")
+    public GeoP(final PBiPredicate<Object, Object> biPredicate, final 
GValue<?> value) {
+        super(biPredicate, (GValue<Object>) value);
+        this.arguments = null;
+        validateConstants(biPredicate, getValue());
+    }
+
+    /**
+     * Constructs a {@code GeoP} from arguments kept in the order they were 
written, so that a
+     * variable among them stays bound to the argument it was given for.
+     */
+    private GeoP(final PBiPredicate<Object, Object> biPredicate, final 
List<Object> arguments,
+                 final Map<String, Object> variables) {
+        super(biPredicate, 
Collections.<Object>singletonList(resolve(arguments, variables)), variables, 
false);
+        this.arguments = Collections.unmodifiableList(new 
ArrayList<>(arguments));
+        validateConstants(biPredicate, getValue());
+    }
+
+    @Override
+    public boolean equals(final Object other) {
+        return other instanceof GeoP && super.equals(other);
+    }
+
+    @Override
+    public P<Object> negate() {
+        return new NotP<>(this);
+    }
+
+    public GeoP clone() {
+        return (GeoP) super.clone();
+    }
+
+    /**
+     * {@inheritDoc}
+     * <p>
+     * A new value for one of this predicate's variables is validated as the 
same value given to a
+     * constructor would be.
+     */
+    @Override
+    public void updateVariable(final String name, final Object value) {
+        super.updateVariable(name, value);

Review Comment:
   Nit: This mutates the variable before validating it, so a rejected binding 
leaves the predicate in an invalid state. Could we validate the proposed value 
first and only update variables and literals after validation succeeds? Not 
that important but it kind of makes sense to me for it to behave this way 
instead.



##########
gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/geo/GeoPredicates.java:
##########
@@ -0,0 +1,149 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.structure.geo;
+
+import org.locationtech.jts.geom.Coordinate;
+import org.locationtech.jts.operation.distance.DistanceOp;
+import org.locationtech.jts.operation.relateng.RelateNG;
+import org.locationtech.jts.operation.relateng.RelatePredicate;
+import org.locationtech.spatial4j.distance.DistanceUtils;
+
+/**
+ * Evaluates the geometry predicates with JTS and Spatial4j.
+ * <p>
+ * A value that cannot be compared gives {@code false}: a non-geometry, null, 
an empty geometry, a
+ * different SRID, or a model other than {@link Model#CARTESIAN} or {@link 
Model#GEOGRAPHIC}.
+ * <p>
+ * All math is 2D. {@link Model#GEOGRAPHIC} relates shapes in longitude and 
latitude and measures
+ * meters on a sphere of the WGS84 mean radius, within about 1% of WGS84. 
Between shapes other than
+ * two points, this holds for edges under about 100 km that cross neither the 
antimeridian nor a pole.
+ * <p>
+ * Operands are converted to JTS on every call and nothing is cached, because 
JTS geometries are not
+ * thread safe and one predicate may be shared by many traversers.
+ *
+ * @since 4.0.0
+ */
+public final class GeoPredicates {
+
+    /**
+     * The WGS84 mean radius in meters, which is the sphere the geographic 
model measures on.
+     */
+    private static final double EARTH_RADIUS_METERS = 6371008.8;
+
+    private GeoPredicates() {
+        // static methods only, do not instantiate class
+    }
+
+    /**
+     * Returns true if {@code value} lies entirely inside {@code argument}. A 
value that lies only on
+     * the argument's boundary is not within it.
+     *
+     * @since 4.0.0
+     */
+    public static boolean within(final Object value, final Object argument) {

Review Comment:
   This converts the argument geometry to JTS for every tested value, even when 
it is a constant. For a has() scan, that means repeatedly converting the same 
geometry. Could we track preparing and caching constant arguments as a 
follow-up Jira, as described in Proposal 10?



##########
gremlin-js/gremlin-javascript/lib/language/translator/TranslateVisitor.ts:
##########
@@ -268,6 +278,55 @@ export default class TranslateVisitor {
         this.appendExplicitNaming(ctx.getText(), 'GType');

Review Comment:
   The grammar accepts lowercase forms such as `GType.lineString` and 
`lineString`, but this preserves that casing and emits the nonexistent Java 
enum member `GType.lineString`. Could this normalize the extracted name to 
uppercase so all forms translate to `GType.LINESTRING`?



##########
gremlin-js/gremlin-javascript/lib/language/translator/TranslateVisitor.ts:
##########
@@ -450,3 +536,38 @@ export default class TranslateVisitor {
         this.visitChildren(ctx);
     }
 }
+
+// ─── Helpers 
─────────────────────────────────────────────────────────────────
+
+/** The SRID of the CARTESIAN model. */
+const CARTESIAN_SRID = 0;
+
+/** The SRID of the GEOGRAPHIC model, which is WGS84. */
+const GEOGRAPHIC_SRID = 4326;
+
+/**
+ * Reads the SRID of a geometry literal, which the grammar writes in the 
decimal, hexadecimal or octal
+ * form, with underscore separators and an optional integer type suffix.
+ */
+function parseSridLiteral(text: string): number {

Review Comment:
   This reimplements Gremlin integer parsing but loses the existing suffix and 
range semantics. For example, 32618B is an invalid byte literal but becomes 
SRID 32618, while 2147483648L exceeds the required 32-bit SRID range. Using 
number can also round large values. Could this use a shared exact 
integer-literal parser, equivalent to 
`GenericLiteralVisitor.visitIntegerLiteral()`, and then enforce the signed 
32-bit SRID range?



##########
gremlin-js/gremlin-javascript/lib/language/translator/JavaTranslateVisitor.ts:
##########
@@ -226,6 +226,10 @@ export default class JavaTranslateVisitor extends 
TranslateVisitor {
         this.sb.push('))');
     }
 
+    visitGeometryLiteral(ctx: any): void {
+        this.appendGeometryFromWkt(ctx);

Review Comment:
   Geometry translation is covered by the Java translator tests, but those do 
not exercise this separate TypeScript implementation. I don’t see any geometry 
cases added to `gremlin-translator-test.js` for either Java or Groovy output. 
Could we add equivalent coverage here, including escaped WKT, lowercase GType, 
SRID handling, and the traversal/value predicate combinations?



##########
gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/GeoP.java:
##########
@@ -0,0 +1,405 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.tinkerpop.gremlin.process.traversal;
+
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
+import org.apache.tinkerpop.gremlin.process.traversal.step.GValue;
+import org.apache.tinkerpop.gremlin.structure.geo.Geometry;
+import org.apache.tinkerpop.gremlin.structure.geo.Model;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Predefined {@code Predicate} values that filter {@link Geometry} values by 
a spatial
+ * relationship, backed by the {@link Geo} predicates.
+ * <p>
+ * For {@code geoWithinDistance}, {@link #getValue()} is a two element list of 
the geometry and the
+ * distance, in that order.
+ * <p>
+ * An argument may instead come from a child traversal, which is resolved 
against each traverser.
+ * {@code geoWithinDistance} then holds a child traversal for each of its two 
arguments, and a
+ * constant given beside a traversal is carried as a constant traversal. An 
argument may also be a
+ * {@link GValue}, whose value is resolved when the traversal is built.
+ * <p>
+ * <b>Accuracy in the geographic model.</b> Distances are measured on a sphere 
of the WGS84 mean
+ * radius, within about 1% of WGS84. Edges are straight in longitude and 
latitude, so the relate
+ * predicates, and distances between shapes other than two points, hold for 
edges under about
+ * 100 km that cross neither the antimeridian nor a pole.
+ *
+ * @since 4.0.0
+ */
+public class GeoP extends P<Object> {
+
+    /**
+     * {@code geoWithinDistance}'s arguments as they were given, each either a 
value or a
+     * {@link GValue}, so that the pair can be rebuilt when a variable takes a 
new value. Null
+     * unless one of the arguments is a variable.
+     */
+    private final List<Object> arguments;

Review Comment:
   Could we consider representing each predicate argument as an ordered slot 
containing either a literal, GValue, or child traversal? Currently 
literal/variable arguments use` GeoP.arguments` plus P’s variable/literal 
state, while traversal combinations convert every argument into a traversal. A 
slot abstraction could provide one path for resolution, rebinding, validation, 
and cloning, and would scale better to multiargument predicates such as 
`geoIntersectsBox`.
   
   I don't think this needs to be addressed in this PR, probably a follow-up 
Jira for a potentially cleaner design.



##########
gremlin-js/gremlin-javascript/lib/language/translator/TranslateVisitor.ts:
##########
@@ -268,6 +278,55 @@ export default class TranslateVisitor {
         this.appendExplicitNaming(ctx.getText(), 'GType');
     }
 
+    /**
+     * Extracts the name of the type from a `GType` which may be written with 
or without the `GType`
+     * prefix and in either the camel case or the upper case form, as in 
`lineString` and `LINESTRING`.
+     */
+    protected static extractGTypeName(ctx: any): string {
+        const split: string[] = ctx.getText().split('.');
+        return split[split.length - 1];
+    }
+
+    /**
+     * Determines if a `GType` names a geometry type, which the translators 
that have no geometry support use
+     * to reject the type.
+     */
+    protected static isGeometryGType(ctx: any): boolean {
+        return 
TranslateVisitor.GEOMETRY_GTYPE_NAMES.has(TranslateVisitor.extractGTypeName(ctx).toUpperCase());
+    }
+
+    /**
+     * Appends `Geometry.fromWkt("...")`, the form the JVM languages use since 
they have a WKT reader, with
+     * `Model.GEOGRAPHIC` or the SRID as a second argument where the geometry 
carries one. The WKT is written
+     * as the Gremlin spells it, since this translator has no WKT reader of 
its own to normalize it through.
+     * WKT holds no quote or backslash, so the text needs no escaping.
+     */
+    protected appendGeometryFromWkt(ctx: any): void {
+        this.sb.push('Geometry.fromWkt("');
+        
this.sb.push(TranslateVisitor.removeFirstAndLastCharacters(ctx.stringLiteral().getText()));

Review Comment:
   This slices the raw Gremlin string token rather than decoding it. For 
example, `Geometry("POINT(1 2)"s)` translates to invalid Java/Groovy: 
`Geometry.fromWkt("POINT(1 2)"")`. Escapes such as `\u000a` can also produce 
invalid target-language strings. Could we decode the Gremlin string first, then 
escape it as a Java/Groovy string literal?



##########
gremlin-language/src/main/antlr4/Gremlin.g4:
##########
@@ -1113,6 +1113,11 @@ traversalDT
     | K_DAY | K_DT DOT K_DAY
     ;
 
+traversalModel

Review Comment:
   This rule is only reachable from `Geometry(...)` and excludes OTHER. 
GremlinLang can emit expressions such as `g.inject(Model.OTHER)`, which the 
grammar cannot parse back. Could all three Model values be supported as generic 
literals, with a separate narrower rule restricting geometry construction to 
CARTESIAN and GEOGRAPHIC?



##########
gremlin-js/gremlin-javascript/lib/language/translator/TranslateVisitor.ts:
##########
@@ -268,6 +278,55 @@ export default class TranslateVisitor {
         this.appendExplicitNaming(ctx.getText(), 'GType');
     }
 
+    /**
+     * Extracts the name of the type from a `GType` which may be written with 
or without the `GType`
+     * prefix and in either the camel case or the upper case form, as in 
`lineString` and `LINESTRING`.
+     */
+    protected static extractGTypeName(ctx: any): string {
+        const split: string[] = ctx.getText().split('.');
+        return split[split.length - 1];
+    }
+
+    /**
+     * Determines if a `GType` names a geometry type, which the translators 
that have no geometry support use
+     * to reject the type.
+     */
+    protected static isGeometryGType(ctx: any): boolean {
+        return 
TranslateVisitor.GEOMETRY_GTYPE_NAMES.has(TranslateVisitor.extractGTypeName(ctx).toUpperCase());
+    }
+
+    /**
+     * Appends `Geometry.fromWkt("...")`, the form the JVM languages use since 
they have a WKT reader, with
+     * `Model.GEOGRAPHIC` or the SRID as a second argument where the geometry 
carries one. The WKT is written
+     * as the Gremlin spells it, since this translator has no WKT reader of 
its own to normalize it through.
+     * WKT holds no quote or backslash, so the text needs no escaping.
+     */
+    protected appendGeometryFromWkt(ctx: any): void {
+        this.sb.push('Geometry.fromWkt("');
+        
this.sb.push(TranslateVisitor.removeFirstAndLastCharacters(ctx.stringLiteral().getText()));
+        this.sb.push('"');
+
+        const modelCtx = ctx.traversalModel();
+        if (modelCtx != null) {
+            const modelName: string = 
modelCtx.getText().split('.').pop().toUpperCase();
+            // CARTESIAN is the default model and so goes unwritten

Review Comment:
   This differs from the Java translator, which parses the complete geometry 
and rejects conflicting EWKT/model information. Here, explicit CARTESIAN and 
SRID 0 are removed without parsing the WKT. For example, 
`Geometry("SRID=4326;POINT(1 2)", CARTESIAN)` is rejected by the Java 
translator but becomes a valid geographic geometry here. Could this preserve 
the explicit argument or otherwise match the Java translator’s validation?





> GEO Spatial APIs
> ----------------
>
>                 Key: TINKERPOP-2558
>                 URL: https://issues.apache.org/jira/browse/TINKERPOP-2558
>             Project: TinkerPop
>          Issue Type: Improvement
>          Components: process
>    Affects Versions: 3.5.0
>            Reporter: Jitesh
>            Priority: Major
>
> Provide support for Geo based APIs (predicates, objects, etc)
>  
>  



--
This message was sent by Atlassian Jira
(v10.3.26#10030026)

Reply via email to