def test_query_car_by_purpose(self): g = self.nep.g result = g.V().hasLabel("Car")\ .and_( __.has("purposes", "family"), __.has("num_seats", 7))\ .values("fullname")\ .toList() print(result)
def test_query_car_by_price(self): g = self.nep.g result = g.V().hasLabel("Car")\ .and_( __.has('price', gt(450*1e6)), __.has('price', lt(550*1e6)))\ .values("fullname")\ .toList() print(result)
def check_duplicate_public_ips(g): """duplicate public ips """ r = g.V().hasLabel(within('floating_ip', 'instance_ip')) \ .or_(__.has('floating_ip_address'), __.has('instance_ip_address')) \ .property('ip_address', __.values('floating_ip_address', 'instance_ip_address')) \ .group().by('ip_address').unfold() \ .filter(lambda: "it.get().value.size() > 1 && it.get().value.findAll{it.label.value == 'floating_ip'} != []") \ .toList() if len(r) > 0: printo('Found %d %s:' % (len(r), check_duplicate_public_ips.__doc__.strip())) return r
def test_upsert(self) -> None: g = __.V().has('User', 'key', 'jack').fold().coalesce( unfold(), addV('User').property(Cardinality.single, 'key', 'jack')). \ coalesce(__.has('email', '*****@*****.**'), __.property(Cardinality.single, 'email', '*****@*****.**')). \ coalesce(__.has('url', 'https://twitter.com/jack'), __.property(Cardinality.single, 'url', 'https://twitter.com/jack')) actual = ScriptTranslator.translateB('g', g) self.assertEqual( actual, '''g.V().has("User","key","jack").fold().coalesce(__.unfold(),__.addV("User").property(single,"key","jack")).coalesce(__.has("email","*****@*****.**"),__.property(single,"email","*****@*****.**")).coalesce(__.has("url","https://twitter.com/jack"),__.property(single,"url","https://twitter.com/jack"))''' ) # noqa: E501
def upload(self, json_graph, source_name, verbose=True, drop_graph=True): def printX(obj=""): if clargs.verbose: print(obj) if isinstance(json_graph, str): input_graph = nx.readwrite.json_graph.node_link_graph( json.loads(json_graph)) elif isinstance(json_graph, io.TextIOBase): input_graph = nx.readwrite.json_graph.node_link_graph( json.load(json_graph)) printX("output Gremlin server: %s, %s" % (clargs.output_server, clargs.output_source)) output_graph = Graph().traversal().withRemote( DriverRemoteConnection(self.server_url, self.traversal_source)) if drop_graph: printX("Clearing ouput graph...") output_graph.V().drop().toList() output_graph.E().drop().toList() printX("done") for id, props in input_graph.nodes(data=True): printX("processing node: %s\nwith data: %s" % (id, props)) new_node = output_graph.addV('node_link_node').next() output_graph.V(new_node).property('original_id', id).toList() output_graph.V(new_node).property('source_name', source_name).toList() for prop, value in props.items(): output_graph.V(new_node).property(prop, value).toList() printX("added properties: %s" % output_graph.V(new_node).properties().toList()) for out_id, in_id, props in input_graph.edges(data=True): printX("processing edge: %s --> %s" % (out_id, in_id)) out_node = output_graph.V().where( __.has('original_id', out_id).has('source_name', source_name)).next() in_node = output_graph.V().where( __.has('original_id', in_id).has('source_name', source_name)).next() new_edge = output_graph.addE('node_link_connection').from_( out_node).to(in_node).next() for prop, value in props.items(): output_graph.E(new_edge).property(prop, value).toList() printX("added properties: %s" % output_graph.E(new_edge).properties().toList()) printX("total nodes added: %d" % output_graph.V().count().next()) printX("total edges added: %d" % output_graph.E().count().next())
async def test_strategies(self, remote_connection): statics.load_statics(globals()) # g = Graph().traversal().withRemote(remote_connection). \ withStrategies(TraversalStrategy("SubgraphStrategy", {"vertices": __.hasLabel("person"), "edges": __.hasLabel("created")})) assert 4 == await g.V().count().next() assert 0 == await g.E().count().next() assert 1 == await g.V().label().dedup().count().next() assert "person" == await g.V().label().dedup().next() # g = Graph().traversal().withRemote(remote_connection). \ withStrategies(SubgraphStrategy(vertices=__.hasLabel("person"), edges=__.hasLabel("created"))) assert 4 == await g.V().count().next() assert 0 == await g.E().count().next() assert 1 == await g.V().label().dedup().count().next() assert "person" == await g.V().label().dedup().next() # g = g.withoutStrategies(SubgraphStrategy). \ withComputer(vertices=__.has("name", "marko"), edges=__.limit(0)) assert 1 == await g.V().count().next() assert 0 == await g.E().count().next() assert "person" == await g.V().label().next() assert "marko" == await g.V().name.next() # g = Graph().traversal().withRemote(remote_connection).withComputer() assert 6 == await g.V().count().next() assert 6 == await g.E().count().next() await remote_connection.close()
def test_strategies(self): statics.load_statics(globals()) connection = DriverRemoteConnection('ws://localhost:8182/gremlin', 'g') # g = Graph().traversal().withRemote(connection). \ withStrategies(TraversalStrategy("SubgraphStrategy", {"vertices": __.hasLabel("person"), "edges": __.hasLabel("created")})) assert 4 == g.V().count().next() assert 0 == g.E().count().next() assert 1 == g.V().label().dedup().count().next() assert "person" == g.V().label().dedup().next() # g = Graph().traversal().withRemote(connection). \ withStrategies(SubgraphStrategy(vertices=__.hasLabel("person"), edges=__.hasLabel("created"))) assert 4 == g.V().count().next() assert 0 == g.E().count().next() assert 1 == g.V().label().dedup().count().next() assert "person" == g.V().label().dedup().next() # g = g.withoutStrategies(SubgraphStrategy). \ withComputer(workers=4, vertices=__.has("name", "marko"), edges=__.limit(0)) assert 1 == g.V().count().next() assert 0 == g.E().count().next() assert "person" == g.V().label().next() assert "marko" == g.V().name.next() # g = Graph().traversal().withRemote(connection).withComputer() assert 6 == g.V().count().next() assert 6 == g.E().count().next() connection.close()
def test_strategies(self): # we have a proxy model for now given that we don't want to have to have g:XXX all registered on the Gremlin traversal machine (yet) assert {"@type": "g:SubgraphStrategy", "@value": {}} == json.loads( self.graphson_writer.writeObject(SubgraphStrategy)) assert {"@type": "g:SubgraphStrategy", "@value": { "vertices": {"@type": "g:Bytecode", "@value": {"step": [["has", "name", "marko"]]}}}} == json.loads( self.graphson_writer.writeObject(SubgraphStrategy(vertices=__.has("name", "marko"))))
def check_ri_without_rt(g): """routing-instance that doesn't have any route-target (that crashes schema) """ return g.V().hasLabel("routing_instance") \ .not_(__.has('fq_name', within(["default-domain", "default-project", "ip-fabric", "__default__"], ["default-domain", "default-project", "__link_local__", "__link_local__"]))) \ .not_(__.out().hasLabel("route_target"))
def _repoint_vertex_edges( self, vertex_label: str, new_resource_urn: Union[URN, PartialUrn]) -> None: # https://tinkerpop.apache.org/docs/current/recipes/#edge-move resources_of_the_same_type = self.g.V().as_("old_vertex").hasLabel( vertex_label) for id_part in new_resource_urn.resource_id_parts: resources_of_the_same_type.has("_resource_id_parts", id_part) resources_with_same_id_but_unknown = (resources_of_the_same_type.or_( __.has("_account_id", "unknown"), __.has("_region", "unknown"))).toList() for old_vertex in resources_with_same_id_but_unknown: # Outbound old_vertices_outbound_edges = self.g.V(old_vertex).outE().as_("e1") old_outbound_edges_partner_vertex = old_vertices_outbound_edges.inV( ).as_("b") new_vertex = old_outbound_edges_partner_vertex.V( self.generate_vertex_id(new_resource_urn)).as_("new_vertex") add_old_outbound_edges_to_new_vertex = ( new_vertex.addE("has").to("b").as_("e2").sideEffect( __.select("e1").properties().unfold().as_("p").select( "e2").property( __.select("p").key(), __.select("p").value()))) add_old_outbound_edges_to_new_vertex.select("e1").drop().iterate() # Inbound old_vertices_inbound_edges = self.g.V(old_vertex).select( "old_vertex").inE().as_("old_inbound_edge") old_inbound_edges_partner_vertex = old_vertices_inbound_edges.inV( ).as_("c") new_vertex = old_inbound_edges_partner_vertex.select("new_vertex") add_old_inbound_edges_to_new_vertex = (new_vertex.addE( "has").from_("c").as_("new_inbound_edge").sideEffect( __.select("old_inbound_edge").properties().unfold().as_( "p").select("new_inbound_edge").property( __.select("p").key(), __.select("p").value()))) add_old_inbound_edges_to_new_vertex.select( "old_inbound_edge").drop().iterate() # Delete old vertex self.g.V(old_vertex).drop().iterate()
def test_strategies(self, remote_connection): statics.load_statics(globals()) g = traversal().withRemote(remote_connection). \ withStrategies(TraversalStrategy("SubgraphStrategy", {"vertices": __.hasLabel("person"), "edges": __.hasLabel("created")}, "org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.SubgraphStrategy")) assert 4 == g.V().count().next() assert 0 == g.E().count().next() assert 1 == g.V().label().dedup().count().next() assert 4 == g.V().filter( lambda: ("x -> true", "gremlin-groovy")).count().next() assert "person" == g.V().label().dedup().next() # g = traversal().withRemote(remote_connection). \ withStrategies(SubgraphStrategy(vertices=__.hasLabel("person"), edges=__.hasLabel("created"))) assert 4 == g.V().count().next() assert 0 == g.E().count().next() assert 1 == g.V().label().dedup().count().next() assert "person" == g.V().label().dedup().next() # g = traversal().withRemote(remote_connection). \ withStrategies(SubgraphStrategy(edges=__.hasLabel("created"))) assert 6 == g.V().count().next() assert 4 == g.E().count().next() assert 1 == g.E().label().dedup().count().next() assert "created" == g.E().label().dedup().next() # g = g.withoutStrategies(SubgraphStrategy). \ withComputer(vertices=__.has("name", "marko"), edges=__.limit(0)) assert 1 == g.V().count().next() assert 0 == g.E().count().next() assert "person" == g.V().label().next() assert "marko" == g.V().name.next() # g = traversal().withRemote(remote_connection).withComputer() assert 6 == g.V().count().next() assert 6 == g.E().count().next() # g = traversal().withRemote(remote_connection).withStrategies( SeedStrategy(12345)) shuffledResult = g.V().values("name").order().by( Order.shuffle).toList() assert shuffledResult == g.V().values("name").order().by( Order.shuffle).toList() assert shuffledResult == g.V().values("name").order().by( Order.shuffle).toList() assert shuffledResult == g.V().values("name").order().by( Order.shuffle).toList() # g = traversal().withRemote(remote_connection). \ withStrategies(ReservedKeysVerificationStrategy(throw_exception=True)) try: g.addV("person").property("id", "please-don't-use-id").iterate() assert False except GremlinServerError as gse: assert gse.status_code == 500
def get_traversal(self): graph = Graph() try: # take only non deleted resources return graph.traversal().withRemote( DriverRemoteConnection( 'ws://%s/gremlin' % self.gremlin_server, 'g')).withStrategies( SubgraphStrategy(vertices=__.has('deleted', 0))) except (HTTPError, socket.error) as e: raise CommandError('Failed to connect to Gremlin server: %s' % e)
def test_configurable(self): g = Graph().traversal() bytecode = g.withStrategies(MatchAlgorithmStrategy("greedy")).bytecode assert 1 == len(bytecode.source_instructions) assert 2 == len(bytecode.source_instructions[0]) assert "withStrategies" == bytecode.source_instructions[0][0] assert MatchAlgorithmStrategy() == bytecode.source_instructions[0][1] assert "MatchAlgorithmStrategy" == str(bytecode.source_instructions[0][1]) assert hash(MatchAlgorithmStrategy()) == hash( bytecode.source_instructions[0][1]) # even though different confs, same strategy assert 0 == len(g.traversal_strategies.traversal_strategies) # these strategies are proxies ### bytecode = g.withStrategies(SubgraphStrategy(vertices=__.has("name","marko"))).bytecode assert 1 == len(bytecode.source_instructions) assert 2 == len(bytecode.source_instructions[0]) assert "withStrategies" == bytecode.source_instructions[0][0] assert SubgraphStrategy() == bytecode.source_instructions[0][1] strategy = bytecode.source_instructions[0][1] assert 1 == len(strategy.configuration) assert __.has("name","marko") == strategy.configuration["vertices"]
def get_graph(self): time_point = int(time.time()) - 5 * 60 graph = Graph() try: # take only resources updated at least 5min ago and not deleted return graph.traversal().withRemote( DriverRemoteConnection('ws://%s/gremlin' % self.gremlin_server, 'g') ).withStrategies( SubgraphStrategy(vertices=__.has('updated', lt(time_point)).has('deleted', 0)) ) except (HTTPError, socket.error) as e: raise CommandError('Failed to connect to Gremlin server: %s' % e)
def get_airport_from_janus(id, context): try: res = ( g.V() .and_( __.hasLabel("airport"), __.has("id", id), ) .valueMap() .next() ) return get_values(res) except Exception as e: print(e)
def query_04(g, vertex_name = "unknown"): """ extract the subgraph containing only vertics pointing to the vertex_name :param g: graph traversal source object :param vertex_name: type: string , the name of the vertex to query :return: subGraph """ print("{0:}QUERY_04{0:}".format(23 * '=')) # find all neighbours pointing to unknown, set property 'point_unknown' to true id_ = g.V().has('name', vertex_name).next() neighbours = g.V(id_).in_().toList() # 'ztf23' appear twice for idx in neighbours: g.V(idx).property('point_unknown', 'true').next() # extract the sub_graph sub_graph = g.withStrategies(SubgraphStrategy(vertices= __.has('point_unknown', 'true'))) print("The sub_graph object:\n{}\n".format(sub_graph)) print("The vertex map:\n {}\n".format(sub_graph.V().elementMap().toList())) print("The edge map:\n {}\n".format(sub_graph.E().elementMap().toList())) return sub_graph
def test_strategies(self, remote_connection): statics.load_statics(globals()) # g = traversal().withRemote(remote_connection). \ withStrategies(TraversalStrategy("SubgraphStrategy", {"vertices": __.hasLabel("person"), "edges": __.hasLabel("created")})) assert 4 == g.V().count().next() assert 0 == g.E().count().next() assert 1 == g.V().label().dedup().count().next() assert 4 == g.V().filter( lambda: ("lambda x: True", "gremlin-python")).count().next() assert "person" == g.V().label().dedup().next() # g = traversal().withRemote(remote_connection). \ withStrategies(SubgraphStrategy(vertices=__.hasLabel("person"), edges=__.hasLabel("created"))) assert 4 == g.V().count().next() assert 0 == g.E().count().next() assert 1 == g.V().label().dedup().count().next() assert "person" == g.V().label().dedup().next() # g = traversal().withRemote(remote_connection). \ withStrategies(SubgraphStrategy(edges=__.hasLabel("created"))) assert 6 == g.V().count().next() assert 4 == g.E().count().next() assert 1 == g.E().label().dedup().count().next() assert "created" == g.E().label().dedup().next() # g = g.withoutStrategies(SubgraphStrategy). \ withComputer(vertices=__.has("name", "marko"), edges=__.limit(0)) assert 1 == g.V().count().next() assert 0 == g.E().count().next() assert "person" == g.V().label().next() assert "marko" == g.V().name.next() # g = traversal().withRemote(remote_connection).withComputer() assert 6 == g.V().count().next() assert 6 == g.E().count().next()
def test_strategies(self, remote_connection): statics.load_statics(globals()) # g = traversal().withRemote(remote_connection). \ withStrategies(TraversalStrategy("SubgraphStrategy", {"vertices": __.hasLabel("person"), "edges": __.hasLabel("created")})) assert 4 == g.V().count().next() assert 0 == g.E().count().next() assert 1 == g.V().label().dedup().count().next() assert 4 == g.V().filter(lambda: ("lambda x: True", "gremlin-python")).count().next() assert "person" == g.V().label().dedup().next() # g = traversal().withRemote(remote_connection). \ withStrategies(SubgraphStrategy(vertices=__.hasLabel("person"), edges=__.hasLabel("created"))) assert 4 == g.V().count().next() assert 0 == g.E().count().next() assert 1 == g.V().label().dedup().count().next() assert "person" == g.V().label().dedup().next() # g = traversal().withRemote(remote_connection). \ withStrategies(SubgraphStrategy(edges=__.hasLabel("created"))) assert 6 == g.V().count().next() assert 4 == g.E().count().next() assert 1 == g.E().label().dedup().count().next() assert "created" == g.E().label().dedup().next() # g = g.withoutStrategies(SubgraphStrategy). \ withComputer(vertices=__.has("name", "marko"), edges=__.limit(0)) assert 1 == g.V().count().next() assert 0 == g.E().count().next() assert "person" == g.V().label().next() assert "marko" == g.V().name.next() # g = traversal().withRemote(remote_connection).withComputer() assert 6 == g.V().count().next() assert 6 == g.E().count().next()
def check_iip_without_instance_ip_address(g): """instance-ip without any instance_ip_address property """ return g.V().hasLabel("instance_ip").not_( __.has("instance_ip_address") )
def test_translations(self): g = traversal().withGraph(Graph()) tests = list() # 0 tests.append([g.V(), "g.V()"]) # 1 tests.append([g.V('1', '2', '3', '4'), "g.V('1','2','3','4')"]) # 2 tests.append([g.V('3').valueMap(True), "g.V('3').valueMap(True)"]) # 3 tests.append([g.V().constant(5), "g.V().constant(5)"]) # 4 tests.append([g.V().constant(1.5), "g.V().constant(1.5)"]) # 5 tests.append([g.V().constant('Hello'), "g.V().constant('Hello')"]) # 6 tests.append([g.V().hasLabel('airport').limit(5), "g.V().hasLabel('airport').limit(5)"]) # 7 tests.append([g.V().hasLabel(within('a', 'b', 'c')), "g.V().hasLabel(within(['a','b','c']))"]) # 8 tests.append([g.V().hasLabel('airport', 'continent').out().limit(5), "g.V().hasLabel('airport','continent').out().limit(5)"]) # 9 tests.append([g.V().hasLabel('airport').out().values('code').limit(5), "g.V().hasLabel('airport').out().values('code').limit(5)"]) # 10 tests.append([g.V('3').as_('a').out('route').limit(10).where(eq('a')).by('region'), "g.V('3').as('a').out('route').limit(10).where(eq('a')).by('region')"]) # 11 tests.append([g.V('3').repeat(__.out('route').simplePath()).times(2).path().by('code'), "g.V('3').repeat(__.out('route').simplePath()).times(2).path().by('code')"]) # 12 tests.append([g.V().hasLabel('airport').out().has('region', 'US-TX').values('code').limit(5), "g.V().hasLabel('airport').out().has('region','US-TX').values('code').limit(5)"]) # 13 tests.append([g.V().hasLabel('airport').union(__.values('city'), __.values('region')).limit(5), "g.V().hasLabel('airport').union(__.values('city'),__.values('region')).limit(5)"]) # 14 tests.append([g.V('3').as_('a').out('route', 'routes'), "g.V('3').as('a').out('route','routes')"]) # 15 tests.append([g.V().where(__.values('runways').is_(5)), "g.V().where(__.values('runways').is(5))"]) # 16 tests.append([g.V('3').repeat(__.out().simplePath()).until(__.has('code', 'AGR')).path().by('code').limit(5), "g.V('3').repeat(__.out().simplePath()).until(__.has('code','AGR')).path().by('code').limit(5)"]) # 17 tests.append([g.V().hasLabel('airport').order().by(__.id()), "g.V().hasLabel('airport').order().by(__.id())"]) # 18 tests.append([g.V().hasLabel('airport').order().by(T.id), "g.V().hasLabel('airport').order().by(T.id)"]) # 19 tests.append([g.V().hasLabel('airport').order().by(__.id(),Order.desc), "g.V().hasLabel('airport').order().by(__.id(),Order.desc)"]) # 20 tests.append([g.V().hasLabel('airport').order().by('code',Order.desc), "g.V().hasLabel('airport').order().by('code',Order.desc)"]) # 21 tests.append([g.V('1', '2', '3').local(__.out().out().dedup().fold()), "g.V('1','2','3').local(__.out().out().dedup().fold())"]) # 22 tests.append([g.V('3').out().path().count(Scope.local), "g.V('3').out().path().count(Scope.local)"]) # 23 tests.append([g.E().count(), "g.E().count()"]) # 24 tests.append([g.V('5').outE('route').inV().path().limit(10), "g.V('5').outE('route').inV().path().limit(10)"]) # 25 tests.append([g.V('5').propertyMap().select(Column.keys), "g.V('5').propertyMap().select(Column.keys)"]) # 26 tests.append([g.V('5').propertyMap().select(Column.values), "g.V('5').propertyMap().select(Column.values)"]) # 27 tests.append([g.V('3').values('runways').math('_ + 1'), "g.V('3').values('runways').math('_ + 1')"]) # 28 tests.append([g.V('3').emit().repeat(__.out().simplePath()).times(3).limit(5).path(), "g.V('3').emit().repeat(__.out().simplePath()).times(3).limit(5).path()"]) # 29 tests.append([g.V().match(__.as_('a').has('code', 'LHR').as_('b')).select('b').by('code'), "g.V().match(__.as('a').has('code','LHR').as('b')).select('b').by('code')"]) # 30 tests.append([g.V().has('test-using-keyword-as-property','repeat'), "g.V().has('test-using-keyword-as-property','repeat')"]) # 31 tests.append([g.V('1').addE('test').to(__.V('4')), "g.V('1').addE('test').to(__.V('4'))"]) # 32 tests.append([g.V().values('runways').max(), "g.V().values('runways').max()"]) # 33 tests.append([g.V().values('runways').min(), "g.V().values('runways').min()"]) # 34 tests.append([g.V().values('runways').sum(), "g.V().values('runways').sum()"]) # 35 tests.append([g.V().values('runways').mean(), "g.V().values('runways').mean()"]) # 36 tests.append([g.withSack(0).V('3', '5').sack(Operator.sum).by('runways').sack(), "g.withSack(0).V('3','5').sack(Operator.sum).by('runways').sack()"]) # 37 tests.append([g.V('3').values('runways').store('x').V('4').values('runways').store('x').by(__.constant(1)).V('6').store('x').by(__.constant(1)).select('x').unfold().sum(), "g.V('3').values('runways').store('x').V('4').values('runways').store('x').by(__.constant(1)).V('6').store('x').by(__.constant(1)).select('x').unfold().sum()"]) # 38 tests.append([g.inject(3, 4, 5), "g.inject(3,4,5)"]) # 39 tests.append([g.inject([3, 4, 5]), "g.inject([3, 4, 5])"]) # 40 tests.append([g.inject(3, 4, 5).count(), "g.inject(3,4,5).count()"]) # 41 tests.append([g.V().has('runways', gt(5)).count(), "g.V().has('runways',gt(5)).count()"]) # 42 tests.append([g.V().has('runways', lte(5.3)).count(), "g.V().has('runways',lte(5.3)).count()"]) # 43 tests.append([g.V().has('code', within(123,124)), "g.V().has('code',within([123,124]))"]) # 44 tests.append([g.V().has('code', within(123, 'abc')), "g.V().has('code',within([123,'abc']))"]) # 45 tests.append([g.V().has('code', within('abc', 123)), "g.V().has('code',within(['abc',123]))"]) # 46 tests.append([g.V().has('code', within('abc', 'xyz')), "g.V().has('code',within(['abc','xyz']))"]) # 47 tests.append([g.V('1', '2').has('region', P.within('US-TX','US-GA')), "g.V('1','2').has('region',within(['US-TX','US-GA']))"]) # 48 tests.append([g.V().and_(__.has('runways', P.gt(5)), __.has('region','US-TX')), "g.V().and(__.has('runways',gt(5)),__.has('region','US-TX'))"]) # 49 tests.append([g.V().union(__.has('runways', gt(5)), __.has('region','US-TX')), "g.V().union(__.has('runways',gt(5)),__.has('region','US-TX'))"]) # 50 tests.append([g.V('3').choose(__.values('runways').is_(3),__.constant('three'),__.constant('not three')), "g.V('3').choose(__.values('runways').is(3),__.constant('three'),__.constant('not three'))"]) # 51 tests.append([g.V('3').choose(__.values('runways')).option(1,__.constant('three')).option(2,__.constant('not three')), "g.V('3').choose(__.values('runways')).option(1,__.constant('three')).option(2,__.constant('not three'))"]) # 52 tests.append([g.V('3').choose(__.values('runways')).option(1.5,__.constant('one and a half')).option(2,__.constant('not three')), "g.V('3').choose(__.values('runways')).option(1.5,__.constant('one and a half')).option(2,__.constant('not three'))"]) # 53 tests.append([g.V('3').repeat(__.out().simplePath()).until(__.loops().is_(1)).count(), "g.V('3').repeat(__.out().simplePath()).until(__.loops().is(1)).count()"]) # 54 tests.append([g.V().hasLabel('airport').limit(20).group().by('region').by('code').order(Scope.local).by(Column.keys), "g.V().hasLabel('airport').limit(20).group().by('region').by('code').order(Scope.local).by(Column.keys)"]) # 55 tests.append([g.V('1').as_('a').V('2').as_('a').select(Pop.all_, 'a'), "g.V('1').as('a').V('2').as('a').select(Pop.all,'a')"]) # 56 tests.append([g.addV('test').property(Cardinality.set_, 'p1', 10), "g.addV('test').property(Cardinality.set,'p1',10)"]) # 57 tests.append([g.addV('test').property(Cardinality.list_, 'p1', 10), "g.addV('test').property(Cardinality.list,'p1',10)"]) # 58 tests.append([g.addV('test').property(Cardinality.single, 'p1', 10), "g.addV('test').property(Cardinality.single,'p1',10)"]) # 59 tests.append([g.V().limit(5).order().by(T.label), "g.V().limit(5).order().by(T.label)"]) # 60 tests.append([g.V().range(1, 5), "g.V().range(1,5)"]) # 61 tests.append([g.addV('test').property('p1', 123), "g.addV('test').property('p1',123)"]) # 62 tests.append([g.addV('test').property('date',datetime(2021, 2, 1, 9, 30)), "g.addV('test').property('date',new Date(121,2,1,9,30,0))"]) # 63 tests.append([g.addV('test').property('date',datetime(2021, 2, 1)), "g.addV('test').property('date',new Date(121,2,1,0,0,0))"]) # 64 tests.append([g.addE('route').from_(__.V('1')).to(__.V('2')), "g.addE('route').from(__.V('1')).to(__.V('2'))"]) # 65 tests.append([g.withSideEffect('a', [1, 2]).V('3').select('a'), "g.withSideEffect('a',[1, 2]).V('3').select('a')"]) # 66 tests.append([g.withSideEffect('a', 1).V('3').select('a'), "g.withSideEffect('a',1).V('3').select('a')"]) # 67 tests.append([g.withSideEffect('a', 'abc').V('3').select('a'), "g.withSideEffect('a','abc').V('3').select('a')"]) # 68 tests.append([g.V().has('airport', 'region', 'US-NM').limit(3).values('elev').fold().index(), "g.V().has('airport','region','US-NM').limit(3).values('elev').fold().index()"]) # 69 tests.append([g.V('3').repeat(__.timeLimit(1000).out().simplePath()).until(__.has('code', 'AGR')).path(), "g.V('3').repeat(__.timeLimit(1000).out().simplePath()).until(__.has('code','AGR')).path()"]) # 70 tests.append([g.V().hasLabel('airport').where(__.values('elev').is_(gt(14000))), "g.V().hasLabel('airport').where(__.values('elev').is(gt(14000)))"]) # 71 tests.append([g.V().hasLabel('airport').where(__.out().count().is_(gt(250))).values('code'), "g.V().hasLabel('airport').where(__.out().count().is(gt(250))).values('code')"]) # 72 tests.append([g.V().hasLabel('airport').filter(__.out().count().is_(gt(250))).values('code'), "g.V().hasLabel('airport').filter(__.out().count().is(gt(250))).values('code')"]) # 73 tests.append([g.withSack(0). V('3'). repeat(__.outE('route').sack(Operator.sum).by('dist').inV()). until(__.has('code', 'AGR').or_().loops().is_(4)). has('code', 'AGR'). local(__.union(__.path().by('code').by('dist'),__.sack()).fold()). limit(10), "g.withSack(0).V('3').repeat(__.outE('route').sack(Operator.sum).by('dist').inV()).until(__.has('code','AGR').or().loops().is(4)).has('code','AGR').local(__.union(__.path().by('code').by('dist'),__.sack()).fold()).limit(10)"]) # 74 tests.append([g.addV().as_('a').addV().as_('b').addE('knows').from_('a').to('b'), "g.addV().as('a').addV().as('b').addE('knows').from('a').to('b')"]) # 75 tests.append([g.addV('Person').as_('a').addV('Person').as_('b').addE('knows').from_('a').to('b'), "g.addV('Person').as('a').addV('Person').as('b').addE('knows').from('a').to('b')"]) # 76 tests.append([g.V('3').project('Out','In').by(__.out().count()).by(__.in_().count()), "g.V('3').project('Out','In').by(__.out().count()).by(__.in().count())"]) # 77 tests.append([g.V('44').out().aggregate('a').out().where(within('a')).path(), "g.V('44').out().aggregate('a').out().where(within(['a'])).path()"]) # 78 tests.append([g.V().has('date', datetime(2021, 2, 22)), "g.V().has('date',new Date(121,2,22,0,0,0))"]) # 79 tests.append([g.V().has('date', within(datetime(2021, 2, 22), datetime(2021, 1, 1))), "g.V().has('date',within([new Date(121,2,22,0,0,0),new Date(121,1,1,0,0,0)]))"]) # 80 tests.append([g.V().has('date', between(datetime(2021, 1, 1), datetime(2021, 2, 22))), "g.V().has('date',between(new Date(121,1,1,0,0,0),new Date(121,2,22,0,0,0)))"]) # 81 tests.append([g.V().has('date', inside(datetime(2021, 1, 1),datetime(2021, 2, 22))), "g.V().has('date',inside(new Date(121,1,1,0,0,0),new Date(121,2,22,0,0,0)))"]) # 82 tests.append([g.V().has('date', P.gt(datetime(2021, 1, 1, 9, 30))), "g.V().has('date',gt(new Date(121,1,1,9,30,0)))"]) # 83 tests.append([g.V().has('runways', between(3,5)), "g.V().has('runways',between(3,5))"]) # 84 tests.append([g.V().has('runways', inside(3,5)), "g.V().has('runways',inside(3,5))"]) # 85 tests.append([g.V('44').outE().elementMap(), "g.V('44').outE().elementMap()"]) # 86 tests.append([g.V('44').valueMap().by(__.unfold()), "g.V('44').valueMap().by(__.unfold())"]) # 87 tests.append([g.V('44').valueMap().with_(WithOptions.tokens,WithOptions.labels), "g.V('44').valueMap().with(WithOptions.tokens,WithOptions.labels)"]) # 88 tests.append([g.V('44').valueMap().with_(WithOptions.tokens), "g.V('44').valueMap().with(WithOptions.tokens)"]) # 89 tests.append([g.withStrategies(ReadOnlyStrategy()).addV('test'), "g.withStrategies(new ReadOnlyStrategy()).addV('test')"]) # 90 strategy = SubgraphStrategy(vertices=__.has('region', 'US-TX'), edges=__.hasLabel('route')) tests.append([g.withStrategies(strategy).V().count(), "g.withStrategies(new SubgraphStrategy(vertices:__.has('region','US-TX'),edges:__.hasLabel('route'))).V().count()"]) # 91 strategy = SubgraphStrategy(vertex_properties=__.hasNot('runways')) tests.append([g.withStrategies(strategy).V().count(), "g.withStrategies(new SubgraphStrategy(vertexProperties:__.hasNot('runways'))).V().count()"]) # 92 strategy = SubgraphStrategy(vertices=__.has('region', 'US-TX'),vertex_properties=__.hasNot('runways')) tests.append([g.withStrategies(strategy).V().count(), "g.withStrategies(new SubgraphStrategy(vertices:__.has('region','US-TX'),vertexProperties:__.hasNot('runways'))).V().count()"]) # 93 strategy = SubgraphStrategy(vertices=__.has('region', 'US-TX'), edges=__.hasLabel('route')) tests.append([g.withStrategies(ReadOnlyStrategy(),strategy).V().count(), "g.withStrategies(new ReadOnlyStrategy(),new SubgraphStrategy(vertices:__.has('region','US-TX'),edges:__.hasLabel('route'))).V().count()"]) # 94 strategy = SubgraphStrategy(vertices=__.has('region', 'US-TX')) tests.append([g.withStrategies(ReadOnlyStrategy(), strategy).V().count(), "g.withStrategies(new ReadOnlyStrategy(),new SubgraphStrategy(vertices:__.has('region','US-TX'))).V().count()"]) # 95 tests.append([g.with_('evaluationTimeout', 500).V().count(), "g.withStrategies(new OptionsStrategy(evaluationTimeout:500)).V().count()"]) # 96 tests.append([g.withStrategies(OptionsStrategy({'evaluationTimeout': 500})).V().count(), "g.withStrategies(new OptionsStrategy(evaluationTimeout:500)).V().count()"]) # 97 tests.append([g.withStrategies(PartitionStrategy(partition_key="partition", write_partition="a", read_partitions=["a"])).addV('test'), "g.withStrategies(new PartitionStrategy(partitionKey:'partition',writePartition:'a',readPartitions:['a'])).addV('test')"]) # 98 tests.append([g.withComputer().V().shortestPath().with_(ShortestPath.target, __.has('name','peter')), "g.withStrategies(new VertexProgramStrategy()).V().shortestPath().with('~tinkerpop.shortestPath.target',__.has('name','peter'))"]) tlr = Translator().of('g') for t in range(len(tests)): a = tlr.translate(tests[t][0].bytecode) assert a == tests[t][1]
connection = DriverRemoteConnection(endpoint, 'g') g = graph.traversal().withRemote(connection) # Helper method to pretty print some headings. def heading(s): print("\n{}".format(s)) for i in range(len(s)): print("-", end="") print("") # Create a SubgraphStrategy that only picks up airports in Texas # and routes between them. heading('SubgraphStrategy - just Texas airports') strategy = SubgraphStrategy(vertices=__.has("region", "US-TX"), edges=__.hasLabel('route')) g2 = g.withStrategies(strategy) verts = g2.V().count().next() edges = g2.E().count().next() routes = g2.V().\ order().\ by(__.out().count()).\ group().\ by('code').\ by(__.out().count()).\ order(Scope.local).by(Column.values).\ next() print("Found {} airports and {} routes.".format(verts, edges))
# Obtain a graph traversal source using a remote connection graph=Graph() connection = DriverRemoteConnection(endpoint,'g') g = graph.traversal().withRemote(connection) # Helper method to pretty print some headings. def heading(s): print("\n{}".format(s)) for i in range(len(s)): print("-",end="") print("") # Create a SubgraphStrategy that only picks up airports in Texas # and routes between them. heading('SubgraphStrategy - just Texas airports') strategy = SubgraphStrategy(vertices=__.has("region","US-TX"), edges=__.hasLabel('route')) g2 = g.withStrategies(strategy) verts = g2.V().count().next() edges = g2.E().count().next() routes = g2.V().\ order().\ by(__.out().count()).\ group().\ by('code').\ by(__.out().count()).\ order(Scope.local).by(Column.values).\ next() print("Found {} airports and {} routes.".format(verts,edges)) for k,v in routes.items():
def get_airports_from_janus(city, country, code, context): try: if city and country and code: res = ( g.V() .and_( __.hasLabel("airport"), __.has("city", city), __.has("country", country), __.has("iata_code", code), ) .valueMap() .toList() ) elif city and country: res = ( g.V() .and_( __.hasLabel("airport"), __.has("city", city), __.has("country", country), ) .valueMap() .toList() ) elif city and code: res = ( g.V() .and_( __.hasLabel("airport"), __.has("city", city), __.has("iata_code", code), ) .valueMap() .toList() ) elif country and code: res = ( g.V() .and_( __.hasLabel("airport"), __.has("country", country), __.has("iata_code", code), ) .valueMap() .toList() ) elif city: res = ( g.V() .and_( __.hasLabel("airport"), __.has("city", city), ) .valueMap() .toList() ) elif country: res = ( g.V() .and_( __.hasLabel("airport"), __.has("country", country), ) .valueMap() .toList() ) elif code: res = ( g.V() .and_( __.hasLabel("airport"), __.has("iata_code", code), ) .valueMap() .toList() ) else: res = [] for i in range(0, len(res)): res[i] = get_values(res[i]) return res except Exception as e: print(e)
most_runways = g.V().has('runways',P.gte(5)).\ order().\ by('runways',Order.desc).\ local(__.values('code','runways').fold()).\ toList() heading("Airports with the most runways") for rows in most_runways: print(rows[0],rows[1]) # Shortest routes by distance from AUS to WLG. # Note the use of the Operator enum. routes = g.withSack(0).\ V().\ has('code','AUS').\ repeat(__.outE().sack(Operator.sum).by('dist').\ inV().simplePath()).\ until(__.has('code','WLG')).\ limit(10).\ order().\ by(__.sack()).\ local(__.union(__.path().by('code').by('dist'),__.sack()).fold()).\ toList() heading("Sack step tests") for route in routes: print(route) # All done so close the connetion connection.close()