Search in sources :

Example 21 with ConditionQuery

use of com.baidu.hugegraph.backend.query.ConditionQuery in project incubator-hugegraph by apache.

the class Example1 method testQuery.

public static void testQuery(final HugeGraph graph) {
    // query all
    GraphTraversal<Vertex, Vertex> vertices = graph.traversal().V();
    int size = vertices.toList().size();
    assert size == 12;
    LOG.info(">>>> query all vertices: size {}", size);
    // query by label
    vertices = graph.traversal().V().hasLabel("person");
    size = vertices.toList().size();
    assert size == 5;
    LOG.info(">>>> query all persons: size {}", size);
    // query vertex by primary-values
    vertices = graph.traversal().V().hasLabel("author").has("id", 1);
    List<Vertex> vertexList = vertices.toList();
    assert vertexList.size() == 1;
    LOG.info(">>>> query vertices by primary-values: {}", vertexList);
    VertexLabel author = graph.schema().getVertexLabel("author");
    String authorId = String.format("%s:%s", author.id().asString(), "11");
    // query vertex by id and query out edges
    vertices = graph.traversal().V(authorId);
    GraphTraversal<Vertex, Edge> edgesOfVertex = vertices.outE("created");
    List<Edge> edgeList = edgesOfVertex.toList();
    assert edgeList.size() == 1;
    LOG.info(">>>> query edges of vertex: {}", edgeList);
    vertices = graph.traversal().V(authorId);
    vertexList = vertices.out("created").toList();
    assert vertexList.size() == 1;
    LOG.info(">>>> query vertices of vertex: {}", vertexList);
    // query edge by sort-values
    vertices = graph.traversal().V(authorId);
    edgesOfVertex = vertices.outE("write").has("time", "2017-4-28");
    edgeList = edgesOfVertex.toList();
    assert edgeList.size() == 2;
    LOG.info(">>>> query edges of vertex by sort-values: {}", edgeList);
    // query vertex by condition (filter by property name)
    ConditionQuery q = new ConditionQuery(HugeType.VERTEX);
    PropertyKey age = graph.propertyKey("age");
    q.key(HugeKeys.PROPERTIES, age.id());
    if (graph.backendStoreFeatures().supportsQueryWithContainsKey()) {
        Iterator<Vertex> iter = graph.vertices(q);
        assert iter.hasNext();
        LOG.info(">>>> queryVertices(age): {}", iter.hasNext());
        while (iter.hasNext()) {
            LOG.info(">>>> queryVertices(age): {}", iter.next());
        }
    }
    // query all edges
    GraphTraversal<Edge, Edge> edges = graph.traversal().E().limit(2);
    size = edges.toList().size();
    assert size == 2;
    LOG.info(">>>> query all edges with limit 2: size {}", size);
    // query edge by id
    EdgeLabel authored = graph.edgeLabel("authored");
    VertexLabel book = graph.schema().getVertexLabel("book");
    String book1Id = String.format("%s:%s", book.id().asString(), "java-1");
    String book2Id = String.format("%s:%s", book.id().asString(), "java-2");
    String edgeId = String.format("S%s>%s>%s>S%s", authorId, authored.id(), "", book2Id);
    edges = graph.traversal().E(edgeId);
    edgeList = edges.toList();
    assert edgeList.size() == 1;
    LOG.info(">>>> query edge by id: {}", edgeList);
    Edge edge = edgeList.get(0);
    edges = graph.traversal().E(edge.id());
    edgeList = edges.toList();
    assert edgeList.size() == 1;
    LOG.info(">>>> query edge by id: {}", edgeList);
    // query edge by condition
    q = new ConditionQuery(HugeType.EDGE);
    q.eq(HugeKeys.OWNER_VERTEX, IdGenerator.of(authorId));
    q.eq(HugeKeys.DIRECTION, Directions.OUT);
    q.eq(HugeKeys.LABEL, authored.id());
    q.eq(HugeKeys.SORT_VALUES, "");
    q.eq(HugeKeys.OTHER_VERTEX, IdGenerator.of(book1Id));
    Iterator<Edge> edges2 = graph.edges(q);
    assert edges2.hasNext();
    LOG.info(">>>> queryEdges(id-condition): {}", edges2.hasNext());
    while (edges2.hasNext()) {
        LOG.info(">>>> queryEdges(id-condition): {}", edges2.next());
    }
    // NOTE: query edge by has-key just supported by Cassandra
    if (graph.backendStoreFeatures().supportsQueryWithContainsKey()) {
        PropertyKey contribution = graph.propertyKey("contribution");
        q.key(HugeKeys.PROPERTIES, contribution.id());
        Iterator<Edge> edges3 = graph.edges(q);
        assert edges3.hasNext();
        LOG.info(">>>> queryEdges(contribution): {}", edges3.hasNext());
        while (edges3.hasNext()) {
            LOG.info(">>>> queryEdges(contribution): {}", edges3.next());
        }
    }
    // query by vertex label
    vertices = graph.traversal().V().hasLabel("book");
    size = vertices.toList().size();
    assert size == 5;
    LOG.info(">>>> query all books: size {}", size);
    // query by vertex label and key-name
    vertices = graph.traversal().V().hasLabel("person").has("age");
    size = vertices.toList().size();
    assert size == 5;
    LOG.info(">>>> query all persons with age: size {}", size);
    // query by vertex props
    vertices = graph.traversal().V().hasLabel("person").has("city", "Taipei");
    vertexList = vertices.toList();
    assert vertexList.size() == 1;
    LOG.info(">>>> query all persons in Taipei: {}", vertexList);
    vertices = graph.traversal().V().hasLabel("person").has("age", 19);
    vertexList = vertices.toList();
    assert vertexList.size() == 1;
    LOG.info(">>>> query all persons age==19: {}", vertexList);
    vertices = graph.traversal().V().hasLabel("person").has("age", P.lt(19));
    vertexList = vertices.toList();
    assert vertexList.size() == 1;
    assert vertexList.get(0).property("age").value().equals(3);
    LOG.info(">>>> query all persons age<19: {}", vertexList);
    String addr = "Bay Area";
    vertices = graph.traversal().V().hasLabel("author").has("lived", Text.contains(addr));
    vertexList = vertices.toList();
    assert vertexList.size() == 1;
    LOG.info(">>>> query all authors lived {}: {}", addr, vertexList);
}
Also used : Vertex(org.apache.tinkerpop.gremlin.structure.Vertex) EdgeLabel(com.baidu.hugegraph.schema.EdgeLabel) ConditionQuery(com.baidu.hugegraph.backend.query.ConditionQuery) VertexLabel(com.baidu.hugegraph.schema.VertexLabel) Edge(org.apache.tinkerpop.gremlin.structure.Edge) PropertyKey(com.baidu.hugegraph.schema.PropertyKey)

Example 22 with ConditionQuery

use of com.baidu.hugegraph.backend.query.ConditionQuery in project incubator-hugegraph by apache.

the class GraphTransaction method queryNumber.

@Override
public Number queryNumber(Query query) {
    E.checkArgument(!this.hasUpdate(), "It's not allowed to query number when " + "there are uncommitted records.");
    if (!(query instanceof ConditionQuery)) {
        return super.queryNumber(query);
    }
    Aggregate aggregate = query.aggregateNotNull();
    QueryList<Number> queries = this.optimizeQueries(query, q -> {
        boolean indexQuery = q.getClass() == IdQuery.class;
        OptimizedType optimized = ((ConditionQuery) query).optimized();
        Number result;
        if (!indexQuery) {
            result = super.queryNumber(q);
        } else {
            E.checkArgument(aggregate.func() == AggregateFunc.COUNT, "The %s operator on index is not supported now", aggregate.func().string());
            if (this.optimizeAggrByIndex && optimized == OptimizedType.INDEX) {
                // The ids size means results count (assume no left index)
                result = q.idsSize();
            } else {
                assert optimized == OptimizedType.INDEX_FILTER || optimized == OptimizedType.INDEX;
                assert q.resultType().isVertex() || q.resultType().isEdge();
                result = IteratorUtils.count(q.resultType().isVertex() ? this.queryVertices(q) : this.queryEdges(q));
            }
        }
        return new QueryResults<>(IteratorUtils.of(result), q);
    });
    QueryResults<Number> results = queries.empty() ? QueryResults.empty() : queries.fetch(this.pageSize);
    return aggregate.reduce(results.iterator());
}
Also used : OptimizedType(com.baidu.hugegraph.backend.query.ConditionQuery.OptimizedType) ConditionQuery(com.baidu.hugegraph.backend.query.ConditionQuery) Aggregate(com.baidu.hugegraph.backend.query.Aggregate) QueryResults(com.baidu.hugegraph.backend.query.QueryResults)

Example 23 with ConditionQuery

use of com.baidu.hugegraph.backend.query.ConditionQuery in project incubator-hugegraph by apache.

the class GraphIndexTransaction method existUniqueValueInStore.

private boolean existUniqueValueInStore(IndexLabel indexLabel, Object value) {
    ConditionQuery query = new ConditionQuery(HugeType.UNIQUE_INDEX);
    query.eq(HugeKeys.INDEX_LABEL_ID, indexLabel.id());
    query.eq(HugeKeys.FIELD_VALUES, value);
    boolean exist;
    Iterator<BackendEntry> iterator = this.query(query).iterator();
    try {
        exist = iterator.hasNext();
        if (exist) {
            HugeIndex index = this.serializer.readIndex(graph(), query, iterator.next());
            this.removeExpiredIndexIfNeeded(index, query.showExpired());
            // Memory backend might return empty BackendEntry
            if (index.elementIds().isEmpty()) {
                return false;
            }
            LOG.debug("Already has existed unique index record {}", index.elementId());
        }
        while (iterator.hasNext()) {
            LOG.warn("Unique constraint conflict found by record {}", iterator.next());
        }
    } finally {
        CloseableIterator.closeIterator(iterator);
    }
    return exist;
}
Also used : BackendEntry(com.baidu.hugegraph.backend.store.BackendEntry) ConditionQuery(com.baidu.hugegraph.backend.query.ConditionQuery) HugeIndex(com.baidu.hugegraph.structure.HugeIndex)

Example 24 with ConditionQuery

use of com.baidu.hugegraph.backend.query.ConditionQuery in project incubator-hugegraph by apache.

the class GraphIndexTransaction method recordIndexValue.

private void recordIndexValue(ConditionQuery query, HugeIndex index) {
    if (!shouldRecordIndexValue(query, index)) {
        return;
    }
    ConditionQuery originQuery = query.originConditionQuery();
    Id fieldId = index.indexLabel().indexField();
    for (Id id : index.elementIds()) {
        Object value = index.indexLabel().validValue(index.fieldValues());
        originQuery.recordIndexValue(fieldId, id, value);
    }
}
Also used : ConditionQuery(com.baidu.hugegraph.backend.query.ConditionQuery) Id(com.baidu.hugegraph.backend.id.Id)

Example 25 with ConditionQuery

use of com.baidu.hugegraph.backend.query.ConditionQuery in project incubator-hugegraph by apache.

the class GraphIndexTransaction method doSearchIndex.

@Watched(prefix = "index")
private IdHolderList doSearchIndex(ConditionQuery query, MatchedIndex index) {
    query = this.constructSearchQuery(query, index);
    // Sorted by matched count
    IdHolderList holders = new SortByCountIdHolderList(query.paging());
    List<ConditionQuery> flatten = ConditionQueryFlatten.flatten(query);
    for (ConditionQuery q : flatten) {
        if (!q.noLimit() && flatten.size() > 1) {
            // Increase limit for union operation
            increaseLimit(q);
        }
        IndexQueries queries = index.constructIndexQueries(q);
        assert !query.paging() || queries.size() <= 1;
        IdHolder holder = this.doSingleOrJointIndex(queries);
        // NOTE: ids will be merged into one IdHolder if not in paging
        holders.add(holder);
    }
    return holders;
}
Also used : SortByCountIdHolderList(com.baidu.hugegraph.backend.page.SortByCountIdHolderList) SortByCountIdHolderList(com.baidu.hugegraph.backend.page.SortByCountIdHolderList) IdHolderList(com.baidu.hugegraph.backend.page.IdHolderList) ConditionQuery(com.baidu.hugegraph.backend.query.ConditionQuery) IdHolder(com.baidu.hugegraph.backend.page.IdHolder) FixedIdHolder(com.baidu.hugegraph.backend.page.IdHolder.FixedIdHolder) PagingIdHolder(com.baidu.hugegraph.backend.page.IdHolder.PagingIdHolder) BatchIdHolder(com.baidu.hugegraph.backend.page.IdHolder.BatchIdHolder) Watched(com.baidu.hugegraph.perf.PerfUtil.Watched)

Aggregations

ConditionQuery (com.baidu.hugegraph.backend.query.ConditionQuery)59 Id (com.baidu.hugegraph.backend.id.Id)19 Test (org.junit.Test)19 Condition (com.baidu.hugegraph.backend.query.Condition)17 HugeGraph (com.baidu.hugegraph.HugeGraph)13 ArrayList (java.util.ArrayList)12 BaseUnitTest (com.baidu.hugegraph.unit.BaseUnitTest)10 Vertex (org.apache.tinkerpop.gremlin.structure.Vertex)10 Watched (com.baidu.hugegraph.perf.PerfUtil.Watched)8 Collection (java.util.Collection)8 Query (com.baidu.hugegraph.backend.query.Query)7 IndexLabel (com.baidu.hugegraph.schema.IndexLabel)7 PropertyKey (com.baidu.hugegraph.schema.PropertyKey)7 Map (java.util.Map)7 Edge (org.apache.tinkerpop.gremlin.structure.Edge)7 VertexLabel (com.baidu.hugegraph.schema.VertexLabel)6 IdQuery (com.baidu.hugegraph.backend.query.IdQuery)5 HugeEdge (com.baidu.hugegraph.structure.HugeEdge)5 HugeType (com.baidu.hugegraph.type.HugeType)5 ImmutableMap (com.google.common.collect.ImmutableMap)5