Search in sources :

Example 16 with Path

use of com.baidu.hugegraph.structure.graph.Path in project incubator-hugegraph-toolchain by apache.

the class GremlinQueryService method buildTableView.

private TableView buildTableView(TypedResult typedResult) {
    List<Object> data = typedResult.getData();
    if (CollectionUtils.isEmpty(data)) {
        return TableView.EMPTY;
    }
    switch(typedResult.getType()) {
        case EMPTY:
            return TableView.EMPTY;
        case GENERAL:
            // result
            List<Object> results = new ArrayList<>(data.size());
            data.forEach(object -> {
                results.add(ImmutableMap.of("result", object));
            });
            return new TableView(TableView.GENERAL_HEADER, results);
        case VERTEX:
            // id, label, properties
            List<Object> vertices = new ArrayList<>(data.size());
            data.forEach(object -> {
                if (object instanceof Vertex) {
                    vertices.add(object);
                }
            });
            return new TableView(TableView.VERTEX_HEADER, vertices);
        case EDGE:
            // id, label, source, target, properties
            List<Object> edges = new ArrayList<>(data.size());
            data.forEach(object -> {
                if (object instanceof Edge) {
                    edges.add(object);
                }
            });
            return new TableView(TableView.EDGE_HEADER, edges);
        case PATH:
            // path, only fill vertex/edge id
            List<Object> paths = new ArrayList<>(data.size());
            data.forEach(object -> {
                if (object instanceof Path) {
                    Path path = (Path) object;
                    List<Object> ids = new ArrayList<>();
                    path.objects().forEach(element -> {
                        if (element instanceof Vertex) {
                            ids.add(((Vertex) element).id());
                        } else if (element instanceof Edge) {
                            ids.add(((Edge) element).id());
                        } else {
                            ids.add(element);
                        }
                    });
                    paths.add(ImmutableMap.of("path", ids));
                }
            });
            return new TableView(TableView.PATH_HEADER, paths);
        default:
            throw new AssertionError(String.format("Unknown result type '%s'", typedResult.getType()));
    }
}
Also used : Path(com.baidu.hugegraph.structure.graph.Path) Vertex(com.baidu.hugegraph.structure.graph.Vertex) ArrayList(java.util.ArrayList) Edge(com.baidu.hugegraph.structure.graph.Edge) TableView(com.baidu.hugegraph.entity.query.TableView)

Example 17 with Path

use of com.baidu.hugegraph.structure.graph.Path in project incubator-hugegraph-toolchain by apache.

the class GremlinQueryService method edgesOfVertex.

private Map<String, Edge> edgesOfVertex(TypedResult result, Map<Object, Vertex> vertices, HugeClient client) {
    final HugeConfig config = this.config;
    int batchSize = config.get(HubbleOptions.GREMLIN_BATCH_QUERY_IDS);
    int edgeLimit = config.get(HubbleOptions.GREMLIN_EDGES_TOTAL_LIMIT);
    int degreeLimit = config.get(HubbleOptions.GREMLIN_VERTEX_DEGREE_LIMIT);
    Set<Object> vertexIds = vertices.keySet();
    Map<String, Edge> edges = new HashMap<>(vertexIds.size());
    Iterables.partition(vertexIds, batchSize).forEach(batch -> {
        List<String> escapedIds = batch.stream().map(GremlinUtil::escapeId).collect(Collectors.toList());
        String ids = StringUtils.join(escapedIds, ",");
        // Any better way to find two vertices has linked?
        String gremlin;
        if (result.getType().isPath()) {
            // If result type is path, the vertices count not too much in theory
            gremlin = String.format("g.V(%s).bothE().local(limit(%s)).dedup()", ids, degreeLimit);
        } else {
            gremlin = String.format("g.V(%s).bothE().dedup().limit(%s)", ids, edgeLimit);
        }
        ResultSet resultSet = client.gremlin().gremlin(gremlin).execute();
        // The edges count for per vertex
        Map<Object, Integer> degrees = new HashMap<>(resultSet.size());
        for (Iterator<Result> iter = resultSet.iterator(); iter.hasNext(); ) {
            Edge edge = iter.next().getEdge();
            Object source = edge.sourceId();
            Object target = edge.targetId();
            // only add the interconnected edges of the found vertices
            if (!vertexIds.contains(source) || !vertexIds.contains(target)) {
                continue;
            }
            edges.put(edge.id(), edge);
            if (edges.size() >= edgeLimit) {
                break;
            }
            int deg = degrees.compute(source, (k, v) -> v == null ? 1 : v + 1);
            if (deg >= degreeLimit) {
                break;
            }
            deg = degrees.compute(target, (k, v) -> v == null ? 1 : v + 1);
            if (deg >= degreeLimit) {
                break;
            }
        }
    });
    return edges;
}
Also used : Direction(com.baidu.hugegraph.structure.constant.Direction) Iterables(com.google.common.collect.Iterables) Type(com.baidu.hugegraph.entity.query.GremlinResult.Type) ServerException(com.baidu.hugegraph.exception.ServerException) ExternalException(com.baidu.hugegraph.exception.ExternalException) AdjacentQuery(com.baidu.hugegraph.entity.query.AdjacentQuery) IdStrategy(com.baidu.hugegraph.structure.constant.IdStrategy) VertexLabelEntity(com.baidu.hugegraph.entity.schema.VertexLabelEntity) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) Ex(com.baidu.hugegraph.util.Ex) StringUtils(org.apache.commons.lang3.StringUtils) ResultSet(com.baidu.hugegraph.structure.gremlin.ResultSet) ArrayList(java.util.ArrayList) JsonView(com.baidu.hugegraph.entity.query.JsonView) HashSet(java.util.HashSet) GremlinUtil(com.baidu.hugegraph.util.GremlinUtil) TableView(com.baidu.hugegraph.entity.query.TableView) Service(org.springframework.stereotype.Service) Map(java.util.Map) ClientException(com.baidu.hugegraph.rest.ClientException) Path(com.baidu.hugegraph.structure.graph.Path) HugeClient(com.baidu.hugegraph.driver.HugeClient) GremlinRequest(com.baidu.hugegraph.api.gremlin.GremlinRequest) ImmutableSet(com.google.common.collect.ImmutableSet) Iterator(java.util.Iterator) ImmutableMap(com.google.common.collect.ImmutableMap) GraphView(com.baidu.hugegraph.entity.query.GraphView) Set(java.util.Set) Result(com.baidu.hugegraph.structure.gremlin.Result) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) TypedResult(com.baidu.hugegraph.entity.query.TypedResult) Edge(com.baidu.hugegraph.structure.graph.Edge) IllegalGremlinException(com.baidu.hugegraph.exception.IllegalGremlinException) Vertex(com.baidu.hugegraph.structure.graph.Vertex) HubbleOptions(com.baidu.hugegraph.options.HubbleOptions) VertexLabelService(com.baidu.hugegraph.service.schema.VertexLabelService) List(java.util.List) CollectionUtils(org.springframework.util.CollectionUtils) HugeClientPoolService(com.baidu.hugegraph.service.HugeClientPoolService) Log4j2(lombok.extern.log4j.Log4j2) HugeConfig(com.baidu.hugegraph.config.HugeConfig) Comparator(java.util.Comparator) InternalException(com.baidu.hugegraph.exception.InternalException) Collections(java.util.Collections) GremlinQuery(com.baidu.hugegraph.entity.query.GremlinQuery) GremlinResult(com.baidu.hugegraph.entity.query.GremlinResult) HashMap(java.util.HashMap) HugeConfig(com.baidu.hugegraph.config.HugeConfig) Result(com.baidu.hugegraph.structure.gremlin.Result) TypedResult(com.baidu.hugegraph.entity.query.TypedResult) GremlinResult(com.baidu.hugegraph.entity.query.GremlinResult) ResultSet(com.baidu.hugegraph.structure.gremlin.ResultSet) Edge(com.baidu.hugegraph.structure.graph.Edge)

Example 18 with Path

use of com.baidu.hugegraph.structure.graph.Path in project incubator-hugegraph-toolchain by apache.

the class GremlinQueryService method buildGraphView.

private GraphView buildGraphView(TypedResult result, HugeClient client) {
    List<Object> data = result.getData();
    if (!result.getType().isGraph() || CollectionUtils.isEmpty(data)) {
        return GraphView.EMPTY;
    }
    Map<Object, Vertex> vertices = new HashMap<>();
    Map<String, Edge> edges = new HashMap<>();
    for (Object object : data) {
        if (object instanceof Vertex) {
            Vertex vertex = (Vertex) object;
            vertices.put(vertex.id(), vertex);
        } else if (object instanceof Edge) {
            Edge edge = (Edge) object;
            edges.put(edge.id(), edge);
        } else if (object instanceof Path) {
            List<Object> elements = ((Path) object).objects();
            for (Object element : elements) {
                if (element instanceof Vertex) {
                    Vertex vertex = (Vertex) element;
                    vertices.put(vertex.id(), vertex);
                } else if (element instanceof Edge) {
                    Edge edge = (Edge) element;
                    edges.put(edge.id(), edge);
                } else {
                    return GraphView.EMPTY;
                }
            }
        }
    }
    if (!edges.isEmpty()) {
        if (vertices.isEmpty()) {
            vertices = this.verticesOfEdge(result, edges, client);
        } else {
            // TODO: reduce the number of requests
            vertices.putAll(this.verticesOfEdge(result, edges, client));
        }
    } else {
        if (!vertices.isEmpty()) {
            edges = this.edgesOfVertex(result, vertices, client);
        }
    }
    if (!edges.isEmpty()) {
        Ex.check(!vertices.isEmpty(), "gremlin.edges.linked-vertex.not-exist");
    }
    return new GraphView(vertices.values(), edges.values());
}
Also used : Path(com.baidu.hugegraph.structure.graph.Path) Vertex(com.baidu.hugegraph.structure.graph.Vertex) HashMap(java.util.HashMap) Edge(com.baidu.hugegraph.structure.graph.Edge) GraphView(com.baidu.hugegraph.entity.query.GraphView)

Example 19 with Path

use of com.baidu.hugegraph.structure.graph.Path in project incubator-hugegraph-toolchain by apache.

the class OltpAlgoService method shortestPath.

public GremlinResult shortestPath(int connId, ShortestPath body) {
    HugeClient client = this.getClient(connId);
    TraverserManager traverser = client.traverser();
    Path result = traverser.shortestPath(body.getSource(), body.getTarget(), body.getDirection(), body.getLabel(), body.getMaxDepth(), body.getMaxDegree(), body.getSkipDegree(), body.getCapacity());
    JsonView jsonView = new JsonView();
    jsonView.setData(result.objects());
    Date createTime = HubbleUtil.nowDate();
    TableView tableView = this.buildPathTableView(result);
    GraphView graphView = this.buildPathGraphView(result);
    // Insert execute history
    ExecuteStatus status = ExecuteStatus.SUCCESS;
    ExecuteHistory history;
    history = new ExecuteHistory(null, connId, 0L, ExecuteType.ALGORITHM, body.toString(), status, AsyncTaskStatus.UNKNOWN, -1L, createTime);
    this.historyService.save(history);
    return GremlinResult.builder().type(GremlinResult.Type.PATH).jsonView(jsonView).tableView(tableView).graphView(graphView).build();
}
Also used : ShortestPath(com.baidu.hugegraph.entity.algorithm.ShortestPath) Path(com.baidu.hugegraph.structure.graph.Path) HugeClient(com.baidu.hugegraph.driver.HugeClient) ExecuteHistory(com.baidu.hugegraph.entity.query.ExecuteHistory) JsonView(com.baidu.hugegraph.entity.query.JsonView) ExecuteStatus(com.baidu.hugegraph.entity.enums.ExecuteStatus) GraphView(com.baidu.hugegraph.entity.query.GraphView) TraverserManager(com.baidu.hugegraph.driver.TraverserManager) Date(java.util.Date) TableView(com.baidu.hugegraph.entity.query.TableView)

Example 20 with Path

use of com.baidu.hugegraph.structure.graph.Path in project incubator-hugegraph-toolchain by apache.

the class PathSerializerTest method testDeserializePathWithSimpleType.

@Test
public void testDeserializePathWithSimpleType() {
    String json = "{" + "\"labels\":[" + "[]," + "[]" + "]," + "\"objects\":[" + "\"marko\"," + "\"lop\"" + "]" + "}";
    Path path = deserialize(json, Path.class);
    Assert.assertEquals(2, path.labels().size());
    Assert.assertEquals(ImmutableList.of(), path.labels().get(0));
    Assert.assertEquals(ImmutableList.of(), path.labels().get(1));
    Assert.assertEquals(2, path.objects().size());
    Assert.assertArrayEquals(new Object[] { "marko", "lop" }, path.objects().toArray());
    json = "{" + "\"labels\":[" + "[]," + "[]" + "]," + "\"objects\":[" + "29," + "32" + "]" + "}";
    path = deserialize(json, Path.class);
    Assert.assertEquals(2, path.objects().size());
    Assert.assertArrayEquals(new Object[] { 29, 32 }, path.objects().toArray());
}
Also used : Path(com.baidu.hugegraph.structure.graph.Path) Test(org.junit.Test)

Aggregations

Path (com.baidu.hugegraph.structure.graph.Path)30 Test (org.junit.Test)21 Vertex (com.baidu.hugegraph.structure.graph.Vertex)11 Edge (com.baidu.hugegraph.structure.graph.Edge)9 List (java.util.List)9 ImmutableList (com.google.common.collect.ImmutableList)7 BaseApiTest (com.baidu.hugegraph.api.BaseApiTest)6 Result (com.baidu.hugegraph.structure.gremlin.Result)6 HugeClient (com.baidu.hugegraph.driver.HugeClient)4 GraphView (com.baidu.hugegraph.entity.query.GraphView)4 ResultSet (com.baidu.hugegraph.structure.gremlin.ResultSet)4 ArrayList (java.util.ArrayList)4 GremlinResult (com.baidu.hugegraph.entity.query.GremlinResult)3 TableView (com.baidu.hugegraph.entity.query.TableView)3 TypedResult (com.baidu.hugegraph.entity.query.TypedResult)3 HashMap (java.util.HashMap)3 GremlinRequest (com.baidu.hugegraph.api.gremlin.GremlinRequest)2 Type (com.baidu.hugegraph.entity.query.GremlinResult.Type)2 JsonView (com.baidu.hugegraph.entity.query.JsonView)2 RestResult (com.baidu.hugegraph.rest.RestResult)2