Search in sources :

Example 26 with HugeClient

use of com.baidu.hugegraph.driver.HugeClient in project incubator-hugegraph-toolchain by apache.

the class SingleExample method main.

public static void main(String[] args) throws IOException {
    // If connect failed will throw a exception.
    HugeClient hugeClient = HugeClient.builder("http://localhost:8080", "hugegraph").build();
    SchemaManager schema = hugeClient.schema();
    schema.propertyKey("name").asText().ifNotExist().create();
    schema.propertyKey("age").asInt().ifNotExist().create();
    schema.propertyKey("city").asText().ifNotExist().create();
    schema.propertyKey("weight").asDouble().ifNotExist().create();
    schema.propertyKey("lang").asText().ifNotExist().create();
    schema.propertyKey("date").asDate().ifNotExist().create();
    schema.propertyKey("price").asInt().ifNotExist().create();
    schema.vertexLabel("person").properties("name", "age", "city").primaryKeys("name").ifNotExist().create();
    schema.vertexLabel("software").properties("name", "lang", "price").primaryKeys("name").ifNotExist().create();
    schema.indexLabel("personByCity").onV("person").by("city").secondary().ifNotExist().create();
    schema.indexLabel("personByAgeAndCity").onV("person").by("age", "city").secondary().ifNotExist().create();
    schema.indexLabel("softwareByPrice").onV("software").by("price").range().ifNotExist().create();
    schema.edgeLabel("knows").sourceLabel("person").targetLabel("person").properties("date", "weight").ifNotExist().create();
    schema.edgeLabel("created").sourceLabel("person").targetLabel("software").properties("date", "weight").ifNotExist().create();
    schema.indexLabel("createdByDate").onE("created").by("date").secondary().ifNotExist().create();
    schema.indexLabel("createdByWeight").onE("created").by("weight").range().ifNotExist().create();
    schema.indexLabel("knowsByWeight").onE("knows").by("weight").range().ifNotExist().create();
    GraphManager graph = hugeClient.graph();
    Vertex marko = graph.addVertex(T.label, "person", "name", "marko", "age", 29, "city", "Beijing");
    Vertex vadas = graph.addVertex(T.label, "person", "name", "vadas", "age", 27, "city", "Hongkong");
    Vertex lop = graph.addVertex(T.label, "software", "name", "lop", "lang", "java", "price", 328);
    Vertex josh = graph.addVertex(T.label, "person", "name", "josh", "age", 32, "city", "Beijing");
    Vertex ripple = graph.addVertex(T.label, "software", "name", "ripple", "lang", "java", "price", 199);
    Vertex peter = graph.addVertex(T.label, "person", "name", "peter", "age", 35, "city", "Shanghai");
    marko.addEdge("knows", vadas, "date", "2016-01-10", "weight", 0.5);
    marko.addEdge("knows", josh, "date", "2013-02-20", "weight", 1.0);
    marko.addEdge("created", lop, "date", "2017-12-10", "weight", 0.4);
    josh.addEdge("created", lop, "date", "2009-11-11", "weight", 0.4);
    josh.addEdge("created", ripple, "date", "2017-12-10", "weight", 1.0);
    peter.addEdge("created", lop, "date", "2017-03-24", "weight", 0.2);
    GremlinManager gremlin = hugeClient.gremlin();
    System.out.println("==== Path ====");
    ResultSet resultSet = gremlin.gremlin("g.V().outE().path()").execute();
    Iterator<Result> results = resultSet.iterator();
    results.forEachRemaining(result -> {
        System.out.println(result.getObject().getClass());
        Object object = result.getObject();
        if (object instanceof Vertex) {
            System.out.println(((Vertex) object).id());
        } else if (object instanceof Edge) {
            System.out.println(((Edge) object).id());
        } else if (object instanceof Path) {
            List<Object> elements = ((Path) object).objects();
            elements.forEach(element -> {
                System.out.println(element.getClass());
                System.out.println(element);
            });
        } else {
            System.out.println(object);
        }
    });
    hugeClient.close();
}
Also used : Path(com.baidu.hugegraph.structure.graph.Path) Vertex(com.baidu.hugegraph.structure.graph.Vertex) HugeClient(com.baidu.hugegraph.driver.HugeClient) GraphManager(com.baidu.hugegraph.driver.GraphManager) ResultSet(com.baidu.hugegraph.structure.gremlin.ResultSet) SchemaManager(com.baidu.hugegraph.driver.SchemaManager) GremlinManager(com.baidu.hugegraph.driver.GremlinManager) Edge(com.baidu.hugegraph.structure.graph.Edge) Result(com.baidu.hugegraph.structure.gremlin.Result)

Example 27 with HugeClient

use of com.baidu.hugegraph.driver.HugeClient in project incubator-hugegraph-toolchain by apache.

the class ExecuteHistoryService method remove.

@Transactional(isolation = Isolation.READ_COMMITTED)
public void remove(int connId, int id) {
    ExecuteHistory history = this.mapper.selectById(id);
    HugeClient client = this.getClient(connId);
    if (history.getType().equals(ExecuteType.GREMLIN_ASYNC)) {
        client.task().delete(history.getAsyncId());
    }
    if (this.mapper.deleteById(id) != 1) {
        throw new InternalException("entity.delete.failed", history);
    }
}
Also used : HugeClient(com.baidu.hugegraph.driver.HugeClient) ExecuteHistory(com.baidu.hugegraph.entity.query.ExecuteHistory) InternalException(com.baidu.hugegraph.exception.InternalException) Transactional(org.springframework.transaction.annotation.Transactional)

Example 28 with HugeClient

use of com.baidu.hugegraph.driver.HugeClient in project incubator-hugegraph-toolchain by apache.

the class ExecuteHistoryService method get.

public ExecuteHistory get(int connId, int id) {
    HugeClient client = this.getClient(connId);
    ExecuteHistory history = this.mapper.selectById(id);
    if (history.getType().equals(ExecuteType.GREMLIN_ASYNC)) {
        try {
            Task task = client.task().get(history.getAsyncId());
            history.setDuration(task.updateTime() - task.createTime());
            history.setAsyncStatus(task.status().toUpperCase());
        } catch (Exception e) {
            history.setDuration(0L);
            history.setAsyncStatus(AsyncTaskStatus.UNKNOWN);
        }
    }
    return history;
}
Also used : HugeClient(com.baidu.hugegraph.driver.HugeClient) Task(com.baidu.hugegraph.structure.Task) ExecuteHistory(com.baidu.hugegraph.entity.query.ExecuteHistory) InternalException(com.baidu.hugegraph.exception.InternalException)

Example 29 with HugeClient

use of com.baidu.hugegraph.driver.HugeClient in project incubator-hugegraph-toolchain by apache.

the class GremlinQueryService method expandVertex.

public GremlinResult expandVertex(int connId, AdjacentQuery query) {
    HugeClient client = this.getClient(connId);
    // Build gremlin query
    String gremlin = this.buildGremlinQuery(connId, query);
    log.debug("expand vertex gremlin ==> {}", gremlin);
    // Execute gremlin query
    ResultSet resultSet = this.executeGremlin(gremlin, client);
    List<Vertex> vertices = new ArrayList<>(resultSet.size());
    List<Edge> edges = new ArrayList<>(resultSet.size());
    for (Iterator<Result> iter = resultSet.iterator(); iter.hasNext(); ) {
        Path path = iter.next().getPath();
        List<Object> objects = path.objects();
        assert objects.size() == 3;
        Edge edge = (Edge) objects.get(1);
        Vertex vertex = (Vertex) objects.get(2);
        // Filter vertices and edges that existed in query
        if (query.retainEdge(edge)) {
            edges.add(edge);
        }
        if (query.retainVertex(vertex)) {
            vertices.add(vertex);
        }
    }
    // Build graph view
    GraphView graphView = new GraphView(vertices, edges);
    return GremlinResult.builder().type(Type.PATH).graphView(graphView).build();
}
Also used : Path(com.baidu.hugegraph.structure.graph.Path) Vertex(com.baidu.hugegraph.structure.graph.Vertex) HugeClient(com.baidu.hugegraph.driver.HugeClient) ArrayList(java.util.ArrayList) GraphView(com.baidu.hugegraph.entity.query.GraphView) 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 30 with HugeClient

use of com.baidu.hugegraph.driver.HugeClient 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)

Aggregations

HugeClient (com.baidu.hugegraph.driver.HugeClient)66 Vertex (com.baidu.hugegraph.structure.graph.Vertex)21 ArrayList (java.util.ArrayList)16 ExternalException (com.baidu.hugegraph.exception.ExternalException)15 IndexLabel (com.baidu.hugegraph.structure.schema.IndexLabel)14 ServerException (com.baidu.hugegraph.exception.ServerException)12 GraphManager (com.baidu.hugegraph.driver.GraphManager)11 Edge (com.baidu.hugegraph.structure.graph.Edge)10 SchemaManager (com.baidu.hugegraph.driver.SchemaManager)9 ResultSet (com.baidu.hugegraph.structure.gremlin.ResultSet)8 EdgeLabel (com.baidu.hugegraph.structure.schema.EdgeLabel)8 Test (org.junit.Test)8 VertexLabel (com.baidu.hugegraph.structure.schema.VertexLabel)7 PropertyKey (com.baidu.hugegraph.structure.schema.PropertyKey)6 ExecuteHistory (com.baidu.hugegraph.entity.query.ExecuteHistory)4 GraphView (com.baidu.hugegraph.entity.query.GraphView)4 LoadOptions (com.baidu.hugegraph.loader.executor.LoadOptions)4 ClientException (com.baidu.hugegraph.rest.ClientException)4 BeforeClass (org.junit.BeforeClass)4 GraphConnection (com.baidu.hugegraph.entity.GraphConnection)3