Java和Python接口调用Gremlin中的sack、filter语句
场景:
该方法用于实现多跳路径查询,给定查询条件下的起始实体,找到目标实体类型的实体
命令行格式:
g.withSack{[:]}{it.clone()}.V().hasLabel('start_label')
.has('name', 'query').until(has('entity_type', 'end_label'))
.repeat(dedup().limit(5).sack{m,v -> m[v.values('entity_type')] = 1; m}
.both().simplePath().has('entity_type')
.filter{it.sack()[it.get().value('entity_type')] != 1}).limit(5);
Java接口格式:
package test; import com.gridgraph.driver.GridGraphAuthenticationException; import com.gridgraph.driver.GridGraphSecureCluster; import org.apache.tinkerpop.gremlin.driver.Client; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.apache.tinkerpop.gremlin.util.function.Lambda; import java.util.HashMap; import java.util.List; import java.util.Map; class JavaAPIClient{ public static void main(String[] args) throws GridGraphAuthenticationException { GridGraphSecureCluster cluster = new GridGraphSecureCluster("localhost", 8182, "user", "pass"); Client client = cluster.connect(true); client.submit("GridGraphFactory.openGraph('db');return;"); GraphTraversalSource g = cluster.traversal("db"); List<Vertex> res = g.<HashMap>withSack( Lambda.supplier("new HashMap<>()"), Lambda.unaryOperator("m -> (HashMap) m.clone()")).V() .hasLabel("start_label").has("name", "query").until(__.has("entity_type", "end_label")) .repeat(__.dedup().limit(5).<Map, Vertex>sack(Lambda.biFunction("m, v -> m[v.values('entity_type')] = 1; m")).both() .simplePath().has("entity_type").filter(Lambda.predicate("it.sack()[it.get().value('entity_type')] != 1"))).limit(5).toList(); System.out.println(res); client.close(); cluster.close(); } }
Python接口
from gremlin_python.structure.graph import Graph from gremlin_python.process.anonymous_traversal import traversal from gremlin_python.process.graph_traversal import __ from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection from gremlin_python.driver import client if __name__ == '__main__': client = client.Client('ws://localhost:8182/gremlin', None, username='user', password='pass') result_set = client.submit('GridGraphFactory.openGraph("db");g=graph.traversal();return;') connection = DriverRemoteConnection('ws://localhost:8182/gremlin', 'gdb', username='user', password='pass') g = traversal().withRemote(connection) res = g.withSack(lambda: '[:]', lambda :'it.clone()').V().hasLabel('start_label').has('name', 'query') \ .until(__.has('entity_type', 'end_label')).repeat(__.dedup().limit(5) \ .sack(lambda: "m,v -> m[v.values('entity_type')] = 1; m").both().simplePath() \ .has('entity_type').filter_(lambda: "it.sack()[it.get().value('entity_type')] != 1")) \ .limit(5).toList() print(res) client.close() connection.close()
参考资料:
浙公网安备 33010602011771号