Search in sources :

Example 11 with EdgeLabel

use of com.thinkaurelius.titan.core.EdgeLabel in project titan by thinkaurelius.

the class TitanGraphTest method testConsistencyEnforcement.

/* ==================================================================================
                            CONSISTENCY
     ==================================================================================*/
/**
     * Tests the correct application of ConsistencyModifiers across transactional boundaries
     */
@Test
public void testConsistencyEnforcement() {
    PropertyKey uid = makeVertexIndexedUniqueKey("uid", Integer.class);
    PropertyKey name = makeKey("name", String.class);
    mgmt.setConsistency(uid, ConsistencyModifier.LOCK);
    mgmt.setConsistency(name, ConsistencyModifier.LOCK);
    mgmt.setConsistency(mgmt.getGraphIndex("uid"), ConsistencyModifier.LOCK);
    EdgeLabel knows = mgmt.makeEdgeLabel("knows").multiplicity(Multiplicity.SIMPLE).make();
    EdgeLabel spouse = mgmt.makeEdgeLabel("spouse").multiplicity(Multiplicity.ONE2ONE).make();
    EdgeLabel connect = mgmt.makeEdgeLabel("connect").multiplicity(Multiplicity.MULTI).make();
    EdgeLabel related = mgmt.makeEdgeLabel("related").multiplicity(Multiplicity.MULTI).make();
    mgmt.setConsistency(knows, ConsistencyModifier.LOCK);
    mgmt.setConsistency(spouse, ConsistencyModifier.LOCK);
    mgmt.setConsistency(related, ConsistencyModifier.FORK);
    finishSchema();
    name = tx.getPropertyKey("name");
    connect = tx.getEdgeLabel("connect");
    related = tx.getEdgeLabel("related");
    TitanVertex v1 = tx.addVertex("uid", 1);
    TitanVertex v2 = tx.addVertex("uid", 2);
    TitanVertex v3 = tx.addVertex("uid", 3);
    Edge e1 = v1.addEdge(connect.name(), v2, name.name(), "e1");
    Edge e2 = v1.addEdge(related.name(), v2, name.name(), "e2");
    newTx();
    v1 = getV(tx, v1);
    /*
         ==== check fork, no fork behavior
         */
    long e1id = getId(e1);
    long e2id = getId(e2);
    e1 = getOnlyElement(v1.query().direction(Direction.OUT).labels("connect").edges());
    assertEquals("e1", e1.value("name"));
    assertEquals(e1id, getId(e1));
    e2 = getOnlyElement(v1.query().direction(Direction.OUT).labels("related").edges());
    assertEquals("e2", e2.value("name"));
    assertEquals(e2id, getId(e2));
    //Update edges - one should simply update, the other fork
    e1.property("name", "e1.2");
    e2.property("name", "e2.2");
    newTx();
    v1 = getV(tx, v1);
    e1 = getOnlyElement(v1.query().direction(Direction.OUT).labels("connect").edges());
    assertEquals("e1.2", e1.value("name"));
    //should have same id
    assertEquals(e1id, getId(e1));
    e2 = getOnlyElement(v1.query().direction(Direction.OUT).labels("related").edges());
    assertEquals("e2.2", e2.value("name"));
    //should have different id since forked
    assertNotEquals(e2id, getId(e2));
    clopen();
    /*
         === check cross transaction
         */
    final Random random = new Random();
    final long[] vids = { getId(v1), getId(v2), getId(v3) };
    //1) Index uniqueness
    executeLockConflictingTransactionJobs(graph, new TransactionJob() {

        private int pos = 0;

        @Override
        public void run(TitanTransaction tx) {
            TitanVertex u = getV(tx, vids[pos++]);
            u.property(VertexProperty.Cardinality.single, "uid", 5);
        }
    });
    //2) Property out-uniqueness
    executeLockConflictingTransactionJobs(graph, new TransactionJob() {

        @Override
        public void run(TitanTransaction tx) {
            TitanVertex u = getV(tx, vids[0]);
            u.property(VertexProperty.Cardinality.single, "name", "v" + random.nextInt(10));
        }
    });
    //3) knows simpleness
    executeLockConflictingTransactionJobs(graph, new TransactionJob() {

        @Override
        public void run(TitanTransaction tx) {
            TitanVertex u1 = getV(tx, vids[0]), u2 = getV(tx, vids[1]);
            u1.addEdge("knows", u2);
        }
    });
    //4) knows one2one (in 2 separate configurations)
    executeLockConflictingTransactionJobs(graph, new TransactionJob() {

        private int pos = 1;

        @Override
        public void run(TitanTransaction tx) {
            TitanVertex u1 = getV(tx, vids[0]), u2 = getV(tx, vids[pos++]);
            u1.addEdge("spouse", u2);
        }
    });
    executeLockConflictingTransactionJobs(graph, new TransactionJob() {

        private int pos = 1;

        @Override
        public void run(TitanTransaction tx) {
            TitanVertex u1 = getV(tx, vids[pos++]), u2 = getV(tx, vids[0]);
            u1.addEdge("spouse", u2);
        }
    });
    //######### TRY INVALID CONSISTENCY
    try {
        //Fork does not apply to constrained types
        mgmt.setConsistency(mgmt.getPropertyKey("name"), ConsistencyModifier.FORK);
        fail();
    } catch (IllegalArgumentException e) {
    }
}
Also used : TitanVertex(com.thinkaurelius.titan.core.TitanVertex) Random(java.util.Random) EdgeLabel(com.thinkaurelius.titan.core.EdgeLabel) TitanEdge(com.thinkaurelius.titan.core.TitanEdge) Edge(org.apache.tinkerpop.gremlin.structure.Edge) TitanTransaction(com.thinkaurelius.titan.core.TitanTransaction) PropertyKey(com.thinkaurelius.titan.core.PropertyKey) Test(org.junit.Test)

Example 12 with EdgeLabel

use of com.thinkaurelius.titan.core.EdgeLabel in project atlas by apache.

the class Titan0GraphManagement method createEdgeIndex.

@Override
public void createEdgeIndex(String label, String indexName, AtlasEdgeDirection edgeDirection, List<AtlasPropertyKey> propertyKeys) {
    EdgeLabel edgeLabel = management.getEdgeLabel(label);
    if (edgeLabel == null) {
        edgeLabel = management.makeEdgeLabel(label).make();
    }
    Direction direction = TitanObjectFactory.createDirection(edgeDirection);
    PropertyKey[] keys = TitanObjectFactory.createPropertyKeys(propertyKeys);
    management.buildEdgeIndex(edgeLabel, indexName, direction, keys);
}
Also used : EdgeLabel(com.thinkaurelius.titan.core.EdgeLabel) AtlasEdgeLabel(org.apache.atlas.repository.graphdb.AtlasEdgeLabel) AtlasEdgeDirection(org.apache.atlas.repository.graphdb.AtlasEdgeDirection) Direction(com.tinkerpop.blueprints.Direction) AtlasPropertyKey(org.apache.atlas.repository.graphdb.AtlasPropertyKey) PropertyKey(com.thinkaurelius.titan.core.PropertyKey)

Example 13 with EdgeLabel

use of com.thinkaurelius.titan.core.EdgeLabel in project titan by thinkaurelius.

the class TitanGraphTest method testVertexCentricQuery.

/* ==================================================================================
                            VERTEX CENTRIC QUERIES
     ==================================================================================*/
@Test
@SuppressWarnings("deprecation")
public void testVertexCentricQuery() {
    makeVertexIndexedUniqueKey("name", String.class);
    PropertyKey time = makeKey("time", Integer.class);
    PropertyKey weight = makeKey("weight", Double.class);
    PropertyKey number = makeKey("number", Long.class);
    ((StandardEdgeLabelMaker) mgmt.makeEdgeLabel("connect")).sortKey(time).make();
    ((StandardEdgeLabelMaker) mgmt.makeEdgeLabel("connectDesc")).sortKey(time).sortOrder(Order.DESC).make();
    ((StandardEdgeLabelMaker) mgmt.makeEdgeLabel("friend")).sortKey(weight, time).sortOrder(Order.ASC).signature(number).make();
    ((StandardEdgeLabelMaker) mgmt.makeEdgeLabel("friendDesc")).sortKey(weight, time).sortOrder(Order.DESC).signature(number).make();
    ((StandardEdgeLabelMaker) mgmt.makeEdgeLabel("knows")).sortKey(number, weight).make();
    mgmt.makeEdgeLabel("follows").make();
    finishSchema();
    TitanVertex v = tx.addVertex("name", "v");
    TitanVertex u = tx.addVertex("name", "u");
    int noVertices = 10000;
    assertEquals(0, (noVertices - 1) % 3);
    TitanVertex[] vs = new TitanVertex[noVertices];
    for (int i = 1; i < noVertices; i++) {
        vs[i] = tx.addVertex("name", "v" + i);
    }
    EdgeLabel[] labelsV = { tx.getEdgeLabel("connect"), tx.getEdgeLabel("friend"), tx.getEdgeLabel("knows") };
    EdgeLabel[] labelsU = { tx.getEdgeLabel("connectDesc"), tx.getEdgeLabel("friendDesc"), tx.getEdgeLabel("knows") };
    for (int i = 1; i < noVertices; i++) {
        for (TitanVertex vertex : new TitanVertex[] { v, u }) {
            for (Direction d : new Direction[] { OUT, IN }) {
                EdgeLabel label = vertex == v ? labelsV[i % 3] : labelsU[i % 3];
                TitanEdge e = d == OUT ? vertex.addEdge(n(label), vs[i]) : vs[i].addEdge(n(label), vertex);
                e.property("time", i);
                e.property("weight", i % 4 + 0.5);
                e.property("name", "e" + i);
                e.property("number", i % 5);
            }
        }
    }
    int edgesPerLabel = noVertices / 3;
    VertexList vl;
    Map<TitanVertex, Iterable<TitanEdge>> results;
    Map<TitanVertex, Iterable<TitanVertexProperty>> results2;
    TitanVertex[] qvs;
    int lastTime;
    Iterator<? extends Edge> outer;
    clopen();
    long[] vidsubset = new long[31 - 3];
    for (int i = 0; i < vidsubset.length; i++) vidsubset[i] = vs[i + 3].longId();
    Arrays.sort(vidsubset);
    //##################################################
    //Queries from Cache
    //##################################################
    clopen();
    for (int i = 1; i < noVertices; i++) vs[i] = getV(tx, vs[i].longId());
    v = getV(tx, v.longId());
    u = getV(tx, u.longId());
    qvs = new TitanVertex[] { vs[6], vs[9], vs[12], vs[15], vs[60] };
    //To trigger queries from cache (don't copy!!!)
    assertCount(2 * (noVertices - 1), v.query().direction(Direction.BOTH).edges());
    assertEquals(1, v.query().propertyCount());
    assertEquals(10, size(v.query().labels("connect").limit(10).vertices()));
    assertEquals(10, size(u.query().labels("connectDesc").limit(10).vertices()));
    assertEquals(10, size(v.query().labels("connect").has("time", Cmp.GREATER_THAN, 30).limit(10).vertices()));
    assertEquals(10, size(u.query().labels("connectDesc").has("time", Cmp.GREATER_THAN, 30).limit(10).vertices()));
    lastTime = 0;
    for (TitanEdge e : (Iterable<TitanEdge>) v.query().labels("connect").direction(OUT).limit(20).edges()) {
        int nowTime = e.value("time");
        assertTrue(lastTime + " vs. " + nowTime, lastTime <= nowTime);
        lastTime = nowTime;
    }
    lastTime = Integer.MAX_VALUE;
    for (Edge e : (Iterable<TitanEdge>) u.query().labels("connectDesc").direction(OUT).limit(20).edges()) {
        int nowTime = e.value("time");
        assertTrue(lastTime + " vs. " + nowTime, lastTime >= nowTime);
        lastTime = nowTime;
    }
    assertEquals(10, size(v.query().labels("connect").direction(OUT).has("time", Cmp.GREATER_THAN, 60).limit(10).vertices()));
    assertEquals(10, size(u.query().labels("connectDesc").direction(OUT).has("time", Cmp.GREATER_THAN, 60).limit(10).vertices()));
    outer = v.query().labels("connect").direction(OUT).limit(20).edges().iterator();
    for (Edge e : (Iterable<TitanEdge>) v.query().labels("connect").direction(OUT).limit(10).edges()) {
        assertEquals(e, outer.next());
    }
    evaluateQuery(v.query().labels("connect").direction(OUT).interval("time", 3, 31), EDGE, 10, 1, new boolean[] { true, true });
    evaluateQuery(v.query().labels("connect").direction(OUT).has("time", 15).has("weight", 3.5), EDGE, 1, 1, new boolean[] { false, true });
    evaluateQuery(u.query().labels("connectDesc").direction(OUT).interval("time", 3, 31), EDGE, 10, 1, new boolean[] { true, true });
    assertEquals(10, v.query().labels("connect").direction(IN).interval("time", 3, 31).edgeCount());
    assertEquals(10, u.query().labels("connectDesc").direction(IN).interval("time", 3, 31).edgeCount());
    assertEquals(0, v.query().labels("connect").direction(OUT).has("time", null).edgeCount());
    assertEquals(10, v.query().labels("connect").direction(OUT).interval("time", 3, 31).vertexIds().size());
    assertEquals(edgesPerLabel - 10, v.query().labels("connect").direction(OUT).has("time", Cmp.GREATER_THAN, 31).count());
    assertEquals(10, size(v.query().labels("connect").direction(OUT).interval("time", 3, 31).vertices()));
    assertEquals(3, v.query().labels("friend").direction(OUT).limit(3).count());
    evaluateQuery(v.query().labels("friend").direction(OUT).has("weight", 0.5).limit(3), EDGE, 3, 1, new boolean[] { true, true });
    evaluateQuery(v.query().labels("friend").direction(OUT).interval("time", 3, 33).has("weight", 0.5), EDGE, 3, 1, new boolean[] { true, true });
    evaluateQuery(v.query().labels("friend").direction(OUT).interval("time", 3, 33).has("weight", Contain.IN, ImmutableList.of(0.5)), EDGE, 3, 1, new boolean[] { true, true });
    evaluateQuery(v.query().labels("friend").direction(OUT).has("weight", Contain.IN, ImmutableList.of(0.5, 1.5, 2.5)).interval("time", 3, 33), EDGE, 7, 3, new boolean[] { true, true });
    evaluateQuery(v.query().labels("friend").direction(OUT).has("weight", Contain.IN, ImmutableList.of(0.5, 1.5)), EDGE, 1667, 2, new boolean[] { true, true });
    assertEquals(3, u.query().labels("friendDesc").direction(OUT).interval("time", 3, 33).has("weight", 0.5).edgeCount());
    assertEquals(1, v.query().labels("friend").direction(OUT).has("weight", 0.5).interval("time", 4, 10).edgeCount());
    assertEquals(1, u.query().labels("friendDesc").direction(OUT).has("weight", 0.5).interval("time", 4, 10).edgeCount());
    assertEquals(3, v.query().labels("friend").direction(OUT).interval("time", 3, 33).has("weight", 0.5).edgeCount());
    assertEquals(4, v.query().labels("friend").direction(OUT).has("time", Cmp.LESS_THAN_EQUAL, 10).edgeCount());
    assertEquals(edgesPerLabel - 4, v.query().labels("friend").direction(OUT).has("time", Cmp.GREATER_THAN, 10).edgeCount());
    assertEquals(20, v.query().labels("friend", "connect").direction(OUT).interval("time", 3, 33).edgeCount());
    assertEquals((int) Math.ceil(edgesPerLabel / 5.0), v.query().labels("knows").direction(OUT).has("number", 0).edgeCount());
    assertEquals((int) Math.ceil(edgesPerLabel / 5.0), v.query().labels("knows").direction(OUT).has("number", 0).interval("weight", 0.0, 4.0).edgeCount());
    assertEquals((int) Math.ceil(edgesPerLabel / (5.0 * 2)), v.query().labels("knows").direction(OUT).has("number", 0).interval("weight", 0.0, 2.0).edgeCount());
    assertEquals((int) Math.floor(edgesPerLabel / (5.0 * 2)), v.query().labels("knows").direction(OUT).has("number", 0).interval("weight", 2.1, 4.0).edgeCount());
    assertEquals(20, size(v.query().labels("connect", "friend").direction(OUT).interval("time", 3, 33).vertices()));
    assertEquals(20, size(v.query().labels("connect", "friend").direction(OUT).interval("time", 3, 33).vertexIds()));
    assertEquals(30, v.query().labels("friend", "connect", "knows").direction(OUT).interval("time", 3, 33).edgeCount());
    assertEquals(noVertices - 2, v.query().labels("friend", "connect", "knows").direction(OUT).has("time", Cmp.NOT_EQUAL, 10).edgeCount());
    assertEquals(0, v.query().has("age", null).labels("undefined").direction(OUT).edgeCount());
    assertEquals(1, v.query().labels("connect").direction(OUT).adjacent(vs[6]).has("time", 6).edgeCount());
    assertEquals(1, v.query().labels("knows").direction(OUT).adjacent(vs[11]).edgeCount());
    assertEquals(1, v.query().labels("knows").direction(IN).adjacent(vs[11]).edgeCount());
    assertEquals(2, v.query().labels("knows").direction(BOTH).adjacent(vs[11]).edgeCount());
    assertEquals(1, v.query().labels("knows").direction(OUT).adjacent(vs[11]).has("weight", 3.5).edgeCount());
    assertEquals(2, v.query().labels("connect").adjacent(vs[6]).has("time", 6).edgeCount());
    assertEquals(0, v.query().labels("connect").adjacent(vs[8]).has("time", 8).edgeCount());
    assertEquals(edgesPerLabel, v.query().labels("connect").direction(OUT).edgeCount());
    assertEquals(edgesPerLabel, v.query().labels("connect").direction(IN).edgeCount());
    assertEquals(2 * edgesPerLabel, v.query().labels("connect").direction(BOTH).edgeCount());
    assertEquals(edgesPerLabel, v.query().labels("connect").has("undefined", null).direction(OUT).edgeCount());
    assertEquals(2 * (int) Math.ceil((noVertices - 1) / 4.0), size(v.query().labels("connect", "friend", "knows").has("weight", 1.5).vertexIds()));
    assertEquals(1, v.query().direction(IN).has("time", 1).edgeCount());
    assertEquals(10, v.query().direction(OUT).interval("time", 4, 14).edgeCount());
    assertEquals(9, v.query().direction(IN).interval("time", 4, 14).has("time", Cmp.NOT_EQUAL, 10).edgeCount());
    assertEquals(9, v.query().direction(OUT).interval("time", 4, 14).has("time", Cmp.NOT_EQUAL, 10).edgeCount());
    assertEquals(noVertices - 1, size(v.query().direction(OUT).vertices()));
    assertEquals(noVertices - 1, size(v.query().direction(IN).vertices()));
    for (Direction dir : new Direction[] { IN, OUT }) {
        vl = v.query().labels().direction(dir).interval("time", 3, 31).vertexIds();
        vl.sort();
        for (int i = 0; i < vl.size(); i++) assertEquals(vidsubset[i], vl.getID(i));
    }
    assertCount(2 * (noVertices - 1), v.query().direction(Direction.BOTH).edges());
    //Property queries
    assertEquals(1, size(v.query().properties()));
    assertEquals(1, size(v.query().keys("name").properties()));
    //MultiQueries
    results = tx.multiQuery(qvs).direction(IN).labels("connect").edges();
    for (Iterable<TitanEdge> result : results.values()) assertEquals(1, size(result));
    results = tx.multiQuery(Sets.newHashSet(qvs)).labels("connect").edges();
    for (Iterable<TitanEdge> result : results.values()) assertEquals(2, size(result));
    results = tx.multiQuery(qvs).labels("knows").edges();
    for (Iterable<TitanEdge> result : results.values()) assertEquals(0, size(result));
    results = tx.multiQuery(qvs).edges();
    for (Iterable<TitanEdge> result : results.values()) assertEquals(4, size(result));
    results2 = tx.multiQuery(qvs).properties();
    for (Iterable<TitanVertexProperty> result : results2.values()) assertEquals(1, size(result));
    results2 = tx.multiQuery(qvs).keys("name").properties();
    for (Iterable<TitanVertexProperty> result : results2.values()) assertEquals(1, size(result));
    //##################################################
    //Same queries as above but without memory loading (i.e. omitting the first query)
    //##################################################
    clopen();
    for (int i = 1; i < noVertices; i++) vs[i] = getV(tx, vs[i].longId());
    v = getV(tx, v.longId());
    u = getV(tx, u.longId());
    qvs = new TitanVertex[] { vs[6], vs[9], vs[12], vs[15], vs[60] };
    assertEquals(10, size(v.query().labels("connect").limit(10).vertices()));
    assertEquals(10, size(u.query().labels("connectDesc").limit(10).vertices()));
    assertEquals(10, size(v.query().labels("connect").has("time", Cmp.GREATER_THAN, 30).limit(10).vertices()));
    assertEquals(10, size(u.query().labels("connectDesc").has("time", Cmp.GREATER_THAN, 30).limit(10).vertices()));
    lastTime = 0;
    for (Edge e : (Iterable<TitanEdge>) v.query().labels("connect").direction(OUT).limit(20).edges()) {
        int nowTime = e.value("time");
        assertTrue(lastTime + " vs. " + nowTime, lastTime <= nowTime);
        lastTime = nowTime;
    }
    lastTime = Integer.MAX_VALUE;
    for (Edge e : (Iterable<TitanEdge>) u.query().labels("connectDesc").direction(OUT).limit(20).edges()) {
        int nowTime = e.value("time");
        assertTrue(lastTime + " vs. " + nowTime, lastTime >= nowTime);
        lastTime = nowTime;
    }
    assertEquals(10, size(v.query().labels("connect").direction(OUT).has("time", Cmp.GREATER_THAN, 60).limit(10).vertices()));
    assertEquals(10, size(u.query().labels("connectDesc").direction(OUT).has("time", Cmp.GREATER_THAN, 60).limit(10).vertices()));
    outer = v.query().labels("connect").direction(OUT).limit(20).edges().iterator();
    for (Edge e : (Iterable<TitanEdge>) v.query().labels("connect").direction(OUT).limit(10).edges()) {
        assertEquals(e, outer.next());
    }
    evaluateQuery(v.query().labels("connect").direction(OUT).interval("time", 3, 31), EDGE, 10, 1, new boolean[] { true, true });
    evaluateQuery(v.query().labels("connect").direction(OUT).has("time", 15).has("weight", 3.5), EDGE, 1, 1, new boolean[] { false, true });
    evaluateQuery(u.query().labels("connectDesc").direction(OUT).interval("time", 3, 31), EDGE, 10, 1, new boolean[] { true, true });
    assertEquals(10, v.query().labels("connect").direction(IN).interval("time", 3, 31).edgeCount());
    assertEquals(10, u.query().labels("connectDesc").direction(IN).interval("time", 3, 31).edgeCount());
    assertEquals(0, v.query().labels("connect").direction(OUT).has("time", null).edgeCount());
    assertEquals(10, v.query().labels("connect").direction(OUT).interval("time", 3, 31).vertexIds().size());
    assertEquals(edgesPerLabel - 10, v.query().labels("connect").direction(OUT).has("time", Cmp.GREATER_THAN, 31).count());
    assertEquals(10, size(v.query().labels("connect").direction(OUT).interval("time", 3, 31).vertices()));
    assertEquals(3, v.query().labels("friend").direction(OUT).limit(3).count());
    evaluateQuery(v.query().labels("friend").direction(OUT).has("weight", 0.5).limit(3), EDGE, 3, 1, new boolean[] { true, true });
    evaluateQuery(v.query().labels("friend").direction(OUT).interval("time", 3, 33).has("weight", 0.5), EDGE, 3, 1, new boolean[] { true, true });
    evaluateQuery(v.query().labels("friend").direction(OUT).interval("time", 3, 33).has("weight", Contain.IN, ImmutableList.of(0.5)), EDGE, 3, 1, new boolean[] { true, true });
    evaluateQuery(v.query().labels("friend").direction(OUT).has("weight", Contain.IN, ImmutableList.of(0.5, 1.5, 2.5)).interval("time", 3, 33), EDGE, 7, 3, new boolean[] { true, true });
    evaluateQuery(v.query().labels("friend").direction(OUT).has("weight", Contain.IN, ImmutableList.of(0.5, 1.5)), EDGE, 1667, 2, new boolean[] { true, true });
    assertEquals(3, u.query().labels("friendDesc").direction(OUT).interval("time", 3, 33).has("weight", 0.5).edgeCount());
    assertEquals(1, v.query().labels("friend").direction(OUT).has("weight", 0.5).interval("time", 4, 10).edgeCount());
    assertEquals(1, u.query().labels("friendDesc").direction(OUT).has("weight", 0.5).interval("time", 4, 10).edgeCount());
    assertEquals(3, v.query().labels("friend").direction(OUT).interval("time", 3, 33).has("weight", 0.5).edgeCount());
    assertEquals(4, v.query().labels("friend").direction(OUT).has("time", Cmp.LESS_THAN_EQUAL, 10).edgeCount());
    assertEquals(edgesPerLabel - 4, v.query().labels("friend").direction(OUT).has("time", Cmp.GREATER_THAN, 10).edgeCount());
    assertEquals(20, v.query().labels("friend", "connect").direction(OUT).interval("time", 3, 33).edgeCount());
    assertEquals((int) Math.ceil(edgesPerLabel / 5.0), v.query().labels("knows").direction(OUT).has("number", 0).edgeCount());
    assertEquals((int) Math.ceil(edgesPerLabel / 5.0), v.query().labels("knows").direction(OUT).has("number", 0).interval("weight", 0.0, 4.0).edgeCount());
    assertEquals((int) Math.ceil(edgesPerLabel / (5.0 * 2)), v.query().labels("knows").direction(OUT).has("number", 0).interval("weight", 0.0, 2.0).edgeCount());
    assertEquals((int) Math.floor(edgesPerLabel / (5.0 * 2)), v.query().labels("knows").direction(OUT).has("number", 0).interval("weight", 2.1, 4.0).edgeCount());
    assertEquals(20, size(v.query().labels("connect", "friend").direction(OUT).interval("time", 3, 33).vertices()));
    assertEquals(20, size(v.query().labels("connect", "friend").direction(OUT).interval("time", 3, 33).vertexIds()));
    assertEquals(30, v.query().labels("friend", "connect", "knows").direction(OUT).interval("time", 3, 33).edgeCount());
    assertEquals(noVertices - 2, v.query().labels("friend", "connect", "knows").direction(OUT).has("time", Cmp.NOT_EQUAL, 10).edgeCount());
    assertEquals(0, v.query().has("age", null).labels("undefined").direction(OUT).edgeCount());
    assertEquals(1, v.query().labels("connect").direction(OUT).adjacent(vs[6]).has("time", 6).edgeCount());
    assertEquals(1, v.query().labels("knows").direction(OUT).adjacent(vs[11]).edgeCount());
    assertEquals(1, v.query().labels("knows").direction(IN).adjacent(vs[11]).edgeCount());
    assertEquals(2, v.query().labels("knows").direction(BOTH).adjacent(vs[11]).edgeCount());
    assertEquals(1, v.query().labels("knows").direction(OUT).adjacent(vs[11]).has("weight", 3.5).edgeCount());
    assertEquals(2, v.query().labels("connect").adjacent(vs[6]).has("time", 6).edgeCount());
    assertEquals(0, v.query().labels("connect").adjacent(vs[8]).has("time", 8).edgeCount());
    assertEquals(edgesPerLabel, v.query().labels("connect").direction(OUT).edgeCount());
    assertEquals(edgesPerLabel, v.query().labels("connect").direction(IN).edgeCount());
    assertEquals(2 * edgesPerLabel, v.query().labels("connect").direction(BOTH).edgeCount());
    assertEquals(edgesPerLabel, v.query().labels("connect").has("undefined", null).direction(OUT).edgeCount());
    assertEquals(2 * (int) Math.ceil((noVertices - 1) / 4.0), size(v.query().labels("connect", "friend", "knows").has("weight", 1.5).vertexIds()));
    assertEquals(1, v.query().direction(IN).has("time", 1).edgeCount());
    assertEquals(10, v.query().direction(OUT).interval("time", 4, 14).edgeCount());
    assertEquals(9, v.query().direction(IN).interval("time", 4, 14).has("time", Cmp.NOT_EQUAL, 10).edgeCount());
    assertEquals(9, v.query().direction(OUT).interval("time", 4, 14).has("time", Cmp.NOT_EQUAL, 10).edgeCount());
    assertEquals(noVertices - 1, size(v.query().direction(OUT).vertices()));
    assertEquals(noVertices - 1, size(v.query().direction(IN).vertices()));
    for (Direction dir : new Direction[] { IN, OUT }) {
        vl = v.query().labels().direction(dir).interval("time", 3, 31).vertexIds();
        vl.sort();
        for (int i = 0; i < vl.size(); i++) assertEquals(vidsubset[i], vl.getID(i));
    }
    assertCount(2 * (noVertices - 1), v.query().direction(Direction.BOTH).edges());
    //Property queries
    assertEquals(1, size(v.query().properties()));
    assertEquals(1, size(v.query().keys("name").properties()));
    //MultiQueries
    results = tx.multiQuery(qvs).direction(IN).labels("connect").edges();
    for (Iterable<TitanEdge> result : results.values()) assertEquals(1, size(result));
    results = tx.multiQuery(Sets.newHashSet(qvs)).labels("connect").edges();
    for (Iterable<TitanEdge> result : results.values()) assertEquals(2, size(result));
    results = tx.multiQuery(qvs).labels("knows").edges();
    for (Iterable<TitanEdge> result : results.values()) assertEquals(0, size(result));
    results = tx.multiQuery(qvs).edges();
    for (Iterable<TitanEdge> result : results.values()) assertEquals(4, size(result));
    results2 = tx.multiQuery(qvs).properties();
    for (Iterable<TitanVertexProperty> result : results2.values()) assertEquals(1, size(result));
    results2 = tx.multiQuery(qvs).keys("name").properties();
    for (Iterable<TitanVertexProperty> result : results2.values()) assertEquals(1, size(result));
    //##################################################
    //End copied queries
    //##################################################
    newTx();
    v = getOnlyElement(tx.query().has("name", "v").vertices());
    assertNotNull(v);
    assertEquals(2, v.query().has("weight", 1.5).interval("time", 10, 30).limit(2).vertexIds().size());
    assertEquals(10, v.query().has("weight", 1.5).interval("time", 10, 30).vertexIds().size());
    newTx();
    v = getOnlyElement(tx.query().has("name", "v").vertices());
    assertNotNull(v);
    assertEquals(2, v.query().has("weight", 1.5).interval("time", 10, 30).limit(2).edgeCount());
    assertEquals(10, v.query().has("weight", 1.5).interval("time", 10, 30).edgeCount());
    newTx();
    //Test partially new vertex queries
    TitanVertex[] qvs2 = new TitanVertex[qvs.length + 2];
    qvs2[0] = tx.addVertex();
    for (int i = 0; i < qvs.length; i++) qvs2[i + 1] = getV(tx, qvs[i].longId());
    qvs2[qvs2.length - 1] = tx.addVertex();
    qvs2[0].addEdge("connect", qvs2[qvs2.length - 1]);
    qvs2[qvs2.length - 1].addEdge("connect", qvs2[0]);
    results = tx.multiQuery(qvs2).direction(IN).labels("connect").edges();
    for (Iterable<TitanEdge> result : results.values()) assertEquals(1, size(result));
}
Also used : TitanVertex(com.thinkaurelius.titan.core.TitanVertex) EdgeLabel(com.thinkaurelius.titan.core.EdgeLabel) Direction(org.apache.tinkerpop.gremlin.structure.Direction) TitanVertexProperty(com.thinkaurelius.titan.core.TitanVertexProperty) StandardEdgeLabelMaker(com.thinkaurelius.titan.graphdb.types.StandardEdgeLabelMaker) TitanEdge(com.thinkaurelius.titan.core.TitanEdge) Edge(org.apache.tinkerpop.gremlin.structure.Edge) PropertyKey(com.thinkaurelius.titan.core.PropertyKey) TitanEdge(com.thinkaurelius.titan.core.TitanEdge) VertexList(com.thinkaurelius.titan.core.VertexList) Test(org.junit.Test)

Example 14 with EdgeLabel

use of com.thinkaurelius.titan.core.EdgeLabel in project titan by thinkaurelius.

the class TitanGraphTest method testSchemaTypes.

/* ==================================================================================
                            SCHEMA TESTS
     ==================================================================================*/
/**
     * Test the definition and inspection of various schema types and ensure their correct interpretation
     * within the graph
     */
@Test
public void testSchemaTypes() {
    // ---------- PROPERTY KEYS ----------------
    //Normal single-valued property key
    PropertyKey weight = makeKey("weight", Float.class);
    //Indexed unique property key
    PropertyKey uid = makeVertexIndexedUniqueKey("uid", String.class);
    //Indexed but not unique
    PropertyKey someid = makeVertexIndexedKey("someid", Object.class);
    //Set-valued property key
    PropertyKey name = mgmt.makePropertyKey("name").dataType(String.class).cardinality(Cardinality.SET).make();
    //List-valued property key with signature
    PropertyKey value = mgmt.makePropertyKey("value").dataType(Double.class).signature(weight).cardinality(Cardinality.LIST).make();
    // ---------- EDGE LABELS ----------------
    //Standard edge label
    EdgeLabel friend = mgmt.makeEdgeLabel("friend").make();
    //Unidirected
    EdgeLabel link = mgmt.makeEdgeLabel("link").unidirected().multiplicity(Multiplicity.MANY2ONE).make();
    //Signature label
    EdgeLabel connect = mgmt.makeEdgeLabel("connect").signature(uid).multiplicity(Multiplicity.SIMPLE).make();
    //Edge labels with different cardinalities
    EdgeLabel parent = mgmt.makeEdgeLabel("parent").multiplicity(Multiplicity.MANY2ONE).make();
    EdgeLabel child = mgmt.makeEdgeLabel("child").multiplicity(Multiplicity.ONE2MANY).make();
    EdgeLabel spouse = mgmt.makeEdgeLabel("spouse").multiplicity(Multiplicity.ONE2ONE).make();
    // ---------- VERTEX LABELS ----------------
    VertexLabel person = mgmt.makeVertexLabel("person").make();
    VertexLabel tag = mgmt.makeVertexLabel("tag").make();
    VertexLabel tweet = mgmt.makeVertexLabel("tweet").setStatic().make();
    long[] sig;
    // ######### INSPECTION & FAILURE ############
    assertTrue(mgmt.isOpen());
    assertEquals("weight", weight.toString());
    assertTrue(mgmt.containsRelationType("weight"));
    assertTrue(mgmt.containsPropertyKey("weight"));
    assertFalse(mgmt.containsEdgeLabel("weight"));
    assertTrue(mgmt.containsEdgeLabel("connect"));
    assertFalse(mgmt.containsPropertyKey("connect"));
    assertFalse(mgmt.containsRelationType("bla"));
    assertNull(mgmt.getPropertyKey("bla"));
    assertNull(mgmt.getEdgeLabel("bla"));
    assertNotNull(mgmt.getPropertyKey("weight"));
    assertNotNull(mgmt.getEdgeLabel("connect"));
    assertTrue(weight.isPropertyKey());
    assertFalse(weight.isEdgeLabel());
    assertEquals(Cardinality.SINGLE, weight.cardinality());
    assertEquals(Cardinality.SINGLE, someid.cardinality());
    assertEquals(Cardinality.SET, name.cardinality());
    assertEquals(Cardinality.LIST, value.cardinality());
    assertEquals(Object.class, someid.dataType());
    assertEquals(Float.class, weight.dataType());
    sig = ((InternalRelationType) value).getSignature();
    assertEquals(1, sig.length);
    assertEquals(weight.longId(), sig[0]);
    assertTrue(mgmt.getGraphIndex(uid.name()).isUnique());
    assertFalse(mgmt.getGraphIndex(someid.name()).isUnique());
    assertEquals("friend", friend.name());
    assertTrue(friend.isEdgeLabel());
    assertFalse(friend.isPropertyKey());
    assertEquals(Multiplicity.ONE2ONE, spouse.multiplicity());
    assertEquals(Multiplicity.ONE2MANY, child.multiplicity());
    assertEquals(Multiplicity.MANY2ONE, parent.multiplicity());
    assertEquals(Multiplicity.MULTI, friend.multiplicity());
    assertEquals(Multiplicity.SIMPLE, connect.multiplicity());
    assertTrue(link.isUnidirected());
    assertFalse(link.isDirected());
    assertFalse(child.isUnidirected());
    assertTrue(spouse.isDirected());
    assertFalse(((InternalRelationType) friend).isInvisibleType());
    assertTrue(((InternalRelationType) friend).isInvisible());
    assertEquals(0, ((InternalRelationType) friend).getSignature().length);
    sig = ((InternalRelationType) connect).getSignature();
    assertEquals(1, sig.length);
    assertEquals(uid.longId(), sig[0]);
    assertEquals(0, ((InternalRelationType) friend).getSortKey().length);
    assertEquals(Order.DEFAULT, ((InternalRelationType) friend).getSortOrder());
    assertEquals(SchemaStatus.ENABLED, ((InternalRelationType) friend).getStatus());
    assertEquals(5, Iterables.size(mgmt.getRelationTypes(PropertyKey.class)));
    assertEquals(6, Iterables.size(mgmt.getRelationTypes(EdgeLabel.class)));
    assertEquals(11, Iterables.size(mgmt.getRelationTypes(RelationType.class)));
    assertEquals(3, Iterables.size(mgmt.getVertexLabels()));
    assertEquals("tweet", tweet.name());
    assertTrue(mgmt.containsVertexLabel("person"));
    assertFalse(mgmt.containsVertexLabel("bla"));
    assertFalse(person.isPartitioned());
    assertFalse(person.isStatic());
    assertFalse(tag.isPartitioned());
    assertTrue(tweet.isStatic());
    //Failures
    try {
        //No datatype
        mgmt.makePropertyKey("fid").make();
        fail();
    } catch (IllegalArgumentException e) {
    }
    try {
        //Already exists
        mgmt.makeEdgeLabel("link").unidirected().make();
        fail();
    } catch (SchemaViolationException e) {
    }
    try {
        //signature and sort-key collide
        ((StandardEdgeLabelMaker) mgmt.makeEdgeLabel("other")).sortKey(someid, weight).signature(someid).make();
        fail();
    } catch (IllegalArgumentException e) {
    }
    //        } catch (IllegalArgumentException e) {}
    try {
        //sort key requires the label to be non-constrained
        ((StandardEdgeLabelMaker) mgmt.makeEdgeLabel("other")).multiplicity(Multiplicity.SIMPLE).sortKey(weight).make();
        fail();
    } catch (IllegalArgumentException e) {
    }
    try {
        //sort key requires the label to be non-constrained
        ((StandardEdgeLabelMaker) mgmt.makeEdgeLabel("other")).multiplicity(Multiplicity.MANY2ONE).sortKey(weight).make();
        fail();
    } catch (IllegalArgumentException e) {
    }
    try {
        //Already exists
        mgmt.makeVertexLabel("tweet").make();
        fail();
    } catch (SchemaViolationException e) {
    }
    try {
        //signature key must have non-generic data type
        mgmt.makeEdgeLabel("test").signature(someid).make();
        fail();
    } catch (IllegalArgumentException e) {
    }
    // ######### END INSPECTION ############
    finishSchema();
    clopen();
    //Load schema types into current transaction
    weight = mgmt.getPropertyKey("weight");
    uid = mgmt.getPropertyKey("uid");
    someid = mgmt.getPropertyKey("someid");
    name = mgmt.getPropertyKey("name");
    value = mgmt.getPropertyKey("value");
    friend = mgmt.getEdgeLabel("friend");
    link = mgmt.getEdgeLabel("link");
    connect = mgmt.getEdgeLabel("connect");
    parent = mgmt.getEdgeLabel("parent");
    child = mgmt.getEdgeLabel("child");
    spouse = mgmt.getEdgeLabel("spouse");
    person = mgmt.getVertexLabel("person");
    tag = mgmt.getVertexLabel("tag");
    tweet = mgmt.getVertexLabel("tweet");
    // ######### INSPECTION & FAILURE (COPIED FROM ABOVE) ############
    assertTrue(mgmt.isOpen());
    assertEquals("weight", weight.toString());
    assertTrue(mgmt.containsRelationType("weight"));
    assertTrue(mgmt.containsPropertyKey("weight"));
    assertFalse(mgmt.containsEdgeLabel("weight"));
    assertTrue(mgmt.containsEdgeLabel("connect"));
    assertFalse(mgmt.containsPropertyKey("connect"));
    assertFalse(mgmt.containsRelationType("bla"));
    assertNull(mgmt.getPropertyKey("bla"));
    assertNull(mgmt.getEdgeLabel("bla"));
    assertNotNull(mgmt.getPropertyKey("weight"));
    assertNotNull(mgmt.getEdgeLabel("connect"));
    assertTrue(weight.isPropertyKey());
    assertFalse(weight.isEdgeLabel());
    assertEquals(Cardinality.SINGLE, weight.cardinality());
    assertEquals(Cardinality.SINGLE, someid.cardinality());
    assertEquals(Cardinality.SET, name.cardinality());
    assertEquals(Cardinality.LIST, value.cardinality());
    assertEquals(Object.class, someid.dataType());
    assertEquals(Float.class, weight.dataType());
    sig = ((InternalRelationType) value).getSignature();
    assertEquals(1, sig.length);
    assertEquals(weight.longId(), sig[0]);
    assertTrue(mgmt.getGraphIndex(uid.name()).isUnique());
    assertFalse(mgmt.getGraphIndex(someid.name()).isUnique());
    assertEquals("friend", friend.name());
    assertTrue(friend.isEdgeLabel());
    assertFalse(friend.isPropertyKey());
    assertEquals(Multiplicity.ONE2ONE, spouse.multiplicity());
    assertEquals(Multiplicity.ONE2MANY, child.multiplicity());
    assertEquals(Multiplicity.MANY2ONE, parent.multiplicity());
    assertEquals(Multiplicity.MULTI, friend.multiplicity());
    assertEquals(Multiplicity.SIMPLE, connect.multiplicity());
    assertTrue(link.isUnidirected());
    assertFalse(link.isDirected());
    assertFalse(child.isUnidirected());
    assertTrue(spouse.isDirected());
    assertFalse(((InternalRelationType) friend).isInvisibleType());
    assertTrue(((InternalRelationType) friend).isInvisible());
    assertEquals(0, ((InternalRelationType) friend).getSignature().length);
    sig = ((InternalRelationType) connect).getSignature();
    assertEquals(1, sig.length);
    assertEquals(uid.longId(), sig[0]);
    assertEquals(0, ((InternalRelationType) friend).getSortKey().length);
    assertEquals(Order.DEFAULT, ((InternalRelationType) friend).getSortOrder());
    assertEquals(SchemaStatus.ENABLED, ((InternalRelationType) friend).getStatus());
    assertEquals(5, Iterables.size(mgmt.getRelationTypes(PropertyKey.class)));
    assertEquals(6, Iterables.size(mgmt.getRelationTypes(EdgeLabel.class)));
    assertEquals(11, Iterables.size(mgmt.getRelationTypes(RelationType.class)));
    assertEquals(3, Iterables.size(mgmt.getVertexLabels()));
    assertEquals("tweet", tweet.name());
    assertTrue(mgmt.containsVertexLabel("person"));
    assertFalse(mgmt.containsVertexLabel("bla"));
    assertFalse(person.isPartitioned());
    assertFalse(person.isStatic());
    assertFalse(tag.isPartitioned());
    assertTrue(tweet.isStatic());
    //Failures
    try {
        //No datatype
        mgmt.makePropertyKey("fid").make();
        fail();
    } catch (IllegalArgumentException e) {
    }
    try {
        //Already exists
        mgmt.makeEdgeLabel("link").unidirected().make();
        fail();
    } catch (SchemaViolationException e) {
    }
    try {
        //signature and sort-key collide
        ((StandardEdgeLabelMaker) mgmt.makeEdgeLabel("other")).sortKey(someid, weight).signature(someid).make();
        fail();
    } catch (IllegalArgumentException e) {
    }
    //        } catch (IllegalArgumentException e) {}
    try {
        //sort key requires the label to be non-constrained
        ((StandardEdgeLabelMaker) mgmt.makeEdgeLabel("other")).multiplicity(Multiplicity.SIMPLE).sortKey(weight).make();
        fail();
    } catch (IllegalArgumentException e) {
    }
    try {
        //sort key requires the label to be non-constrained
        ((StandardEdgeLabelMaker) mgmt.makeEdgeLabel("other")).multiplicity(Multiplicity.MANY2ONE).sortKey(weight).make();
        fail();
    } catch (IllegalArgumentException e) {
    }
    try {
        //Already exists
        mgmt.makeVertexLabel("tweet").make();
        fail();
    } catch (SchemaViolationException e) {
    }
    try {
        //signature key must have non-generic data type
        mgmt.makeEdgeLabel("test").signature(someid).make();
        fail();
    } catch (IllegalArgumentException e) {
    }
    // ######### END INSPECTION ############
    /*
          ####### Make sure schema semantics are honored in transactions ######
        */
    clopen();
    TitanTransaction tx2;
    //shouldn't exist
    assertEmpty(tx.query().has("uid", "v1").vertices());
    TitanVertex v = tx.addVertex();
    //test property keys
    v.property("uid", "v1");
    v.property("weight", 1.5);
    v.property("someid", "Hello");
    v.property("name", "Bob");
    v.property("name", "John");
    VertexProperty p = v.property("value", 11);
    p.property("weight", 22);
    v.property("value", 33.3, "weight", 66.6);
    //same values are supported for list-properties
    v.property("value", 11, "weight", 22);
    //test edges
    TitanVertex v12 = tx.addVertex("person"), v13 = tx.addVertex("person");
    v12.property("uid", "v12");
    v13.property("uid", "v13");
    v12.addEdge("parent", v, "weight", 4.5);
    v13.addEdge("parent", v, "weight", 4.5);
    v.addEdge("child", v12);
    v.addEdge("child", v13);
    v.addEdge("spouse", v12);
    v.addEdge("friend", v12);
    //supports multi edges
    v.addEdge("friend", v12);
    v.addEdge("connect", v12, "uid", "e1");
    v.addEdge("link", v13);
    TitanVertex v2 = tx.addVertex("tweet");
    v2.addEdge("link", v13);
    v12.addEdge("connect", v2);
    TitanEdge edge;
    // ######### INSPECTION & FAILURE ############
    assertEquals(v, (Vertex) getOnlyElement(tx.query().has("uid", Cmp.EQUAL, "v1").vertices()));
    v = getOnlyVertex(tx.query().has("uid", Cmp.EQUAL, "v1"));
    v12 = getOnlyVertex(tx.query().has("uid", Cmp.EQUAL, "v12"));
    v13 = getOnlyVertex(tx.query().has("uid", Cmp.EQUAL, "v13"));
    try {
        //Invalid data type
        v.property("weight", "x");
        fail();
    } catch (SchemaViolationException e) {
    }
    try {
        //Only one "John" should be allowed
        v.property(VertexProperty.Cardinality.list, "name", "John");
        fail();
    } catch (SchemaViolationException e) {
    }
    try {
        //Cannot set a property as edge
        v.property("link", v);
        fail();
    } catch (IllegalArgumentException e) {
    }
    //Only one property for weight allowed
    v.property(single, "weight", 1.0);
    assertCount(1, v.properties("weight"));
    v.property(VertexProperty.Cardinality.single, "weight", 0.5);
    assertEquals(0.5, v.<Float>value("weight").doubleValue(), 0.00001);
    assertEquals("v1", v.value("uid"));
    assertCount(2, v.properties("name"));
    for (TitanVertexProperty<String> prop : v.query().labels("name").properties()) {
        String nstr = prop.value();
        assertTrue(nstr.equals("Bob") || nstr.equals("John"));
    }
    assertTrue(size(v.properties("value")) >= 3);
    for (TitanVertexProperty<Double> prop : v.query().labels("value").properties()) {
        double prec = prop.value().doubleValue();
        assertEquals(prec * 2, prop.<Number>value("weight").doubleValue(), 0.00001);
    }
    //Ensure we can add additional values
    p = v.property("value", 44.4, "weight", 88.8);
    assertEquals(v, (Vertex) getOnlyElement(tx.query().has("someid", Cmp.EQUAL, "Hello").vertices()));
    //------- EDGES -------
    try {
        //multiplicity violation
        v12.addEdge("parent", v13);
        fail();
    } catch (SchemaViolationException e) {
    }
    try {
        //multiplicity violation
        v13.addEdge("child", v12);
        fail();
    } catch (SchemaViolationException e) {
    }
    try {
        //multiplicity violation
        v13.addEdge("spouse", v12);
        fail();
    } catch (SchemaViolationException e) {
    }
    try {
        //multiplicity violation
        v.addEdge("spouse", v13);
        fail();
    } catch (SchemaViolationException e) {
    }
    assertCount(2, v.query().direction(Direction.IN).labels("parent").edges());
    assertCount(1, v12.query().direction(Direction.OUT).labels("parent").has("weight").edges());
    assertCount(1, v13.query().direction(Direction.OUT).labels("parent").has("weight").edges());
    assertEquals(v12, getOnlyElement(v.query().direction(Direction.OUT).labels("spouse").vertices()));
    edge = getOnlyElement(v.query().direction(Direction.BOTH).labels("connect").edges());
    assertEquals(1, edge.keys().size());
    assertEquals("e1", edge.value("uid"));
    try {
        //connect is simple
        v.addEdge("connect", v12);
        fail();
    } catch (SchemaViolationException e) {
    }
    //Make sure "link" is unidirected
    assertCount(1, v.query().direction(Direction.BOTH).labels("link").edges());
    assertCount(0, v13.query().direction(Direction.BOTH).labels("link").edges());
    //Assert we can add more friendships
    v.addEdge("friend", v12);
    v2 = getOnlyElement(v12.query().direction(Direction.OUT).labels("connect").vertices());
    assertEquals(v13, getOnlyElement(v2.query().direction(Direction.OUT).labels("link").vertices()));
    assertEquals(BaseVertexLabel.DEFAULT_VERTEXLABEL.name(), v.label());
    assertEquals("person", v12.label());
    assertEquals("person", v13.label());
    assertCount(4, tx.query().vertices());
    // ######### END INSPECTION & FAILURE ############
    clopen();
    // ######### INSPECTION & FAILURE (copied from above) ############
    assertEquals(v, getOnlyVertex(tx.query().has("uid", Cmp.EQUAL, "v1")));
    v = getOnlyVertex(tx.query().has("uid", Cmp.EQUAL, "v1"));
    v12 = getOnlyVertex(tx.query().has("uid", Cmp.EQUAL, "v12"));
    v13 = getOnlyVertex(tx.query().has("uid", Cmp.EQUAL, "v13"));
    try {
        //Invalid data type
        v.property("weight", "x");
        fail();
    } catch (SchemaViolationException e) {
    }
    try {
        //Only one "John" should be allowed
        v.property(VertexProperty.Cardinality.list, "name", "John");
        fail();
    } catch (SchemaViolationException e) {
    }
    try {
        //Cannot set a property as edge
        v.property("link", v);
        fail();
    } catch (IllegalArgumentException e) {
    }
    //Only one property for weight allowed
    v.property(VertexProperty.Cardinality.single, "weight", 1.0);
    assertCount(1, v.properties("weight"));
    v.property(VertexProperty.Cardinality.single, "weight", 0.5);
    assertEquals(0.5, v.<Float>value("weight").doubleValue(), 0.00001);
    assertEquals("v1", v.value("uid"));
    assertCount(2, v.properties("name"));
    for (TitanVertexProperty<String> prop : v.query().labels("name").properties()) {
        String nstr = prop.value();
        assertTrue(nstr.equals("Bob") || nstr.equals("John"));
    }
    assertTrue(Iterables.size(v.query().labels("value").properties()) >= 3);
    for (TitanVertexProperty<Double> prop : v.query().labels("value").properties()) {
        double prec = prop.value().doubleValue();
        assertEquals(prec * 2, prop.<Number>value("weight").doubleValue(), 0.00001);
    }
    //Ensure we can add additional values
    p = v.property("value", 44.4, "weight", 88.8);
    assertEquals(v, (Vertex) getOnlyElement(tx.query().has("someid", Cmp.EQUAL, "Hello").vertices()));
    //------- EDGES -------
    try {
        //multiplicity violation
        v12.addEdge("parent", v13);
        fail();
    } catch (SchemaViolationException e) {
    }
    try {
        //multiplicity violation
        v13.addEdge("child", v12);
        fail();
    } catch (SchemaViolationException e) {
    }
    try {
        //multiplicity violation
        v13.addEdge("spouse", v12);
        fail();
    } catch (SchemaViolationException e) {
    }
    try {
        //multiplicity violation
        v.addEdge("spouse", v13);
        fail();
    } catch (SchemaViolationException e) {
    }
    assertCount(2, v.query().direction(Direction.IN).labels("parent").edges());
    assertCount(1, v12.query().direction(Direction.OUT).labels("parent").has("weight").edges());
    assertCount(1, v13.query().direction(Direction.OUT).labels("parent").has("weight").edges());
    assertEquals(v12, getOnlyElement(v.query().direction(Direction.OUT).labels("spouse").vertices()));
    edge = getOnlyElement(v.query().direction(Direction.BOTH).labels("connect").edges());
    assertEquals(1, edge.keys().size());
    assertEquals("e1", edge.value("uid"));
    try {
        //connect is simple
        v.addEdge("connect", v12);
        fail();
    } catch (SchemaViolationException e) {
    }
    //Make sure "link" is unidirected
    assertCount(1, v.query().direction(Direction.BOTH).labels("link").edges());
    assertCount(0, v13.query().direction(Direction.BOTH).labels("link").edges());
    //Assert we can add more friendships
    v.addEdge("friend", v12);
    v2 = getOnlyElement(v12.query().direction(Direction.OUT).labels("connect").vertices());
    assertEquals(v13, getOnlyElement(v2.query().direction(Direction.OUT).labels("link").vertices()));
    assertEquals(BaseVertexLabel.DEFAULT_VERTEXLABEL.name(), v.label());
    assertEquals("person", v12.label());
    assertEquals("person", v13.label());
    assertCount(4, tx.query().vertices());
    // ######### END INSPECTION & FAILURE ############
    //Ensure index uniqueness enforcement
    tx2 = graph.newTransaction();
    try {
        TitanVertex vx = tx2.addVertex();
        try {
            //property is unique
            vx.property(VertexProperty.Cardinality.single, "uid", "v1");
            fail();
        } catch (SchemaViolationException e) {
        }
        vx.property(VertexProperty.Cardinality.single, "uid", "unique");
        TitanVertex vx2 = tx2.addVertex();
        try {
            //property unique
            vx2.property(VertexProperty.Cardinality.single, "uid", "unique");
            fail();
        } catch (SchemaViolationException e) {
        }
    } finally {
        tx2.rollback();
    }
    //Ensure that v2 is really static
    v2 = getV(tx, v2);
    assertEquals("tweet", v2.label());
    try {
        v2.property(VertexProperty.Cardinality.single, "weight", 11);
        fail();
    } catch (SchemaViolationException e) {
    }
    try {
        v2.addEdge("friend", v12);
        fail();
    } catch (SchemaViolationException e) {
    }
    //Ensure that unidirected edges keep pointing to deleted vertices
    getV(tx, v13).remove();
    assertCount(1, v.query().direction(Direction.BOTH).labels("link").edges());
    //Finally, test the schema container
    SchemaContainer schemaContainer = new SchemaContainer(graph);
    assertTrue(schemaContainer.containsRelationType("weight"));
    assertTrue(schemaContainer.containsRelationType("friend"));
    assertTrue(schemaContainer.containsVertexLabel("person"));
    VertexLabelDefinition vld = schemaContainer.getVertexLabel("tag");
    assertFalse(vld.isPartitioned());
    assertFalse(vld.isStatic());
    PropertyKeyDefinition pkd = schemaContainer.getPropertyKey("name");
    assertEquals(Cardinality.SET, pkd.getCardinality());
    assertEquals(String.class, pkd.getDataType());
    EdgeLabelDefinition eld = schemaContainer.getEdgeLabel("child");
    assertEquals("child", eld.getName());
    assertEquals(child.longId(), eld.getLongId());
    assertEquals(Multiplicity.ONE2MANY, eld.getMultiplicity());
    assertFalse(eld.isUnidirected());
}
Also used : SchemaContainer(com.thinkaurelius.titan.graphdb.schema.SchemaContainer) TitanVertex(com.thinkaurelius.titan.core.TitanVertex) PropertyKeyDefinition(com.thinkaurelius.titan.graphdb.schema.PropertyKeyDefinition) EdgeLabelDefinition(com.thinkaurelius.titan.graphdb.schema.EdgeLabelDefinition) EdgeLabel(com.thinkaurelius.titan.core.EdgeLabel) TitanTransaction(com.thinkaurelius.titan.core.TitanTransaction) StandardEdgeLabelMaker(com.thinkaurelius.titan.graphdb.types.StandardEdgeLabelMaker) BaseVertexLabel(com.thinkaurelius.titan.graphdb.types.system.BaseVertexLabel) VertexLabel(com.thinkaurelius.titan.core.VertexLabel) InternalRelationType(com.thinkaurelius.titan.graphdb.internal.InternalRelationType) SchemaViolationException(com.thinkaurelius.titan.core.SchemaViolationException) TitanVertexProperty(com.thinkaurelius.titan.core.TitanVertexProperty) VertexProperty(org.apache.tinkerpop.gremlin.structure.VertexProperty) PropertyKey(com.thinkaurelius.titan.core.PropertyKey) TitanEdge(com.thinkaurelius.titan.core.TitanEdge) VertexLabelDefinition(com.thinkaurelius.titan.graphdb.schema.VertexLabelDefinition) Test(org.junit.Test)

Example 15 with EdgeLabel

use of com.thinkaurelius.titan.core.EdgeLabel in project titan by thinkaurelius.

the class TitanGraphTest method testIndexUpdatesWithReindexAndRemove.

@Test
public void testIndexUpdatesWithReindexAndRemove() throws InterruptedException, ExecutionException {
    clopen(option(LOG_SEND_DELAY, MANAGEMENT_LOG), Duration.ofMillis(0), option(KCVSLog.LOG_READ_LAG_TIME, MANAGEMENT_LOG), Duration.ofMillis(50), option(LOG_READ_INTERVAL, MANAGEMENT_LOG), Duration.ofMillis(250));
    //Types without index
    PropertyKey time = mgmt.makePropertyKey("time").dataType(Integer.class).make();
    PropertyKey name = mgmt.makePropertyKey("name").dataType(String.class).cardinality(Cardinality.SET).make();
    EdgeLabel friend = mgmt.makeEdgeLabel("friend").multiplicity(Multiplicity.MULTI).make();
    PropertyKey sensor = mgmt.makePropertyKey("sensor").dataType(Double.class).cardinality(Cardinality.LIST).make();
    finishSchema();
    RelationTypeIndex pindex, eindex;
    TitanGraphIndex gindex;
    //Add some sensor & friend data
    TitanVertex v = tx.addVertex();
    for (int i = 0; i < 10; i++) {
        v.property("sensor", i, "time", i);
        v.property("name", "v" + i);
        TitanVertex o = tx.addVertex();
        v.addEdge("friend", o, "time", i);
    }
    newTx();
    //Indexes should not yet be in use
    v = getV(tx, v);
    evaluateQuery(v.query().keys("sensor").interval("time", 1, 5).orderBy("time", decr), PROPERTY, 4, 1, new boolean[] { false, false }, tx.getPropertyKey("time"), Order.DESC);
    evaluateQuery(v.query().keys("sensor").interval("time", 101, 105).orderBy("time", decr), PROPERTY, 0, 1, new boolean[] { false, false }, tx.getPropertyKey("time"), Order.DESC);
    evaluateQuery(v.query().labels("friend").direction(OUT).interval("time", 1, 5).orderBy("time", decr), EDGE, 4, 1, new boolean[] { false, false }, tx.getPropertyKey("time"), Order.DESC);
    evaluateQuery(v.query().labels("friend").direction(OUT).interval("time", 101, 105).orderBy("time", decr), EDGE, 0, 1, new boolean[] { false, false }, tx.getPropertyKey("time"), Order.DESC);
    evaluateQuery(tx.query().has("name", "v5"), ElementCategory.VERTEX, 1, new boolean[] { false, true });
    evaluateQuery(tx.query().has("name", "v105"), ElementCategory.VERTEX, 0, new boolean[] { false, true });
    newTx();
    //Create indexes after the fact
    finishSchema();
    sensor = mgmt.getPropertyKey("sensor");
    time = mgmt.getPropertyKey("time");
    name = mgmt.getPropertyKey("name");
    friend = mgmt.getEdgeLabel("friend");
    mgmt.buildPropertyIndex(sensor, "byTime", decr, time);
    mgmt.buildEdgeIndex(friend, "byTime", Direction.OUT, decr, time);
    mgmt.buildIndex("bySensorReading", Vertex.class).addKey(name).buildCompositeIndex();
    finishSchema();
    newTx();
    //Add some sensor & friend data that should already be indexed even though index is not yet enabled
    v = getV(tx, v);
    for (int i = 100; i < 110; i++) {
        v.property("sensor", i, "time", i);
        v.property("name", "v" + i);
        TitanVertex o = tx.addVertex();
        v.addEdge("friend", o, "time", i);
    }
    tx.commit();
    //Should not yet be able to enable since not yet registered
    pindex = mgmt.getRelationIndex(mgmt.getRelationType("sensor"), "byTime");
    eindex = mgmt.getRelationIndex(mgmt.getRelationType("friend"), "byTime");
    gindex = mgmt.getGraphIndex("bySensorReading");
    try {
        mgmt.updateIndex(pindex, SchemaAction.ENABLE_INDEX);
        fail();
    } catch (IllegalArgumentException e) {
    }
    try {
        mgmt.updateIndex(eindex, SchemaAction.ENABLE_INDEX);
        fail();
    } catch (IllegalArgumentException e) {
    }
    try {
        mgmt.updateIndex(gindex, SchemaAction.ENABLE_INDEX);
        fail();
    } catch (IllegalArgumentException e) {
    }
    mgmt.commit();
    ManagementUtil.awaitVertexIndexUpdate(graph, "byTime", "sensor", 10, ChronoUnit.SECONDS);
    ManagementUtil.awaitGraphIndexUpdate(graph, "bySensorReading", 5, ChronoUnit.SECONDS);
    finishSchema();
    //Verify new status
    pindex = mgmt.getRelationIndex(mgmt.getRelationType("sensor"), "byTime");
    eindex = mgmt.getRelationIndex(mgmt.getRelationType("friend"), "byTime");
    gindex = mgmt.getGraphIndex("bySensorReading");
    assertEquals(SchemaStatus.REGISTERED, pindex.getIndexStatus());
    assertEquals(SchemaStatus.REGISTERED, eindex.getIndexStatus());
    assertEquals(SchemaStatus.REGISTERED, gindex.getIndexStatus(gindex.getFieldKeys()[0]));
    finishSchema();
    //Simply enable without reindex
    eindex = mgmt.getRelationIndex(mgmt.getRelationType("friend"), "byTime");
    mgmt.updateIndex(eindex, SchemaAction.ENABLE_INDEX);
    finishSchema();
    assertTrue(ManagementSystem.awaitRelationIndexStatus(graph, "byTime", "friend").status(SchemaStatus.ENABLED).timeout(10L, ChronoUnit.SECONDS).call().getSucceeded());
    //Reindex the other two
    pindex = mgmt.getRelationIndex(mgmt.getRelationType("sensor"), "byTime");
    ScanMetrics reindexSensorByTime = mgmt.updateIndex(pindex, SchemaAction.REINDEX).get();
    finishSchema();
    gindex = mgmt.getGraphIndex("bySensorReading");
    ScanMetrics reindexBySensorReading = mgmt.updateIndex(gindex, SchemaAction.REINDEX).get();
    finishSchema();
    assertNotEquals(0, reindexSensorByTime.getCustom(IndexRepairJob.ADDED_RECORDS_COUNT));
    assertNotEquals(0, reindexBySensorReading.getCustom(IndexRepairJob.ADDED_RECORDS_COUNT));
    //Every index should now be enabled
    pindex = mgmt.getRelationIndex(mgmt.getRelationType("sensor"), "byTime");
    eindex = mgmt.getRelationIndex(mgmt.getRelationType("friend"), "byTime");
    gindex = mgmt.getGraphIndex("bySensorReading");
    assertEquals(SchemaStatus.ENABLED, eindex.getIndexStatus());
    assertEquals(SchemaStatus.ENABLED, pindex.getIndexStatus());
    assertEquals(SchemaStatus.ENABLED, gindex.getIndexStatus(gindex.getFieldKeys()[0]));
    //Add some more sensor & friend data
    newTx();
    v = getV(tx, v);
    for (int i = 200; i < 210; i++) {
        v.property("sensor", i, "time", i);
        v.property("name", "v" + i);
        TitanVertex o = tx.addVertex();
        v.addEdge("friend", o, "time", i);
    }
    newTx();
    //Use indexes now but only see new data for property and graph index
    v = getV(tx, v);
    evaluateQuery(v.query().keys("sensor").interval("time", 1, 5).orderBy("time", decr), PROPERTY, 4, 1, new boolean[] { true, true }, tx.getPropertyKey("time"), Order.DESC);
    evaluateQuery(v.query().keys("sensor").interval("time", 101, 105).orderBy("time", decr), PROPERTY, 4, 1, new boolean[] { true, true }, tx.getPropertyKey("time"), Order.DESC);
    evaluateQuery(v.query().keys("sensor").interval("time", 201, 205).orderBy("time", decr), PROPERTY, 4, 1, new boolean[] { true, true }, tx.getPropertyKey("time"), Order.DESC);
    evaluateQuery(v.query().labels("friend").direction(OUT).interval("time", 1, 5).orderBy("time", decr), EDGE, 0, 1, new boolean[] { true, true }, tx.getPropertyKey("time"), Order.DESC);
    evaluateQuery(v.query().labels("friend").direction(OUT).interval("time", 101, 105).orderBy("time", decr), EDGE, 4, 1, new boolean[] { true, true }, tx.getPropertyKey("time"), Order.DESC);
    evaluateQuery(v.query().labels("friend").direction(OUT).interval("time", 201, 205).orderBy("time", decr), EDGE, 4, 1, new boolean[] { true, true }, tx.getPropertyKey("time"), Order.DESC);
    evaluateQuery(tx.query().has("name", "v5"), ElementCategory.VERTEX, 1, new boolean[] { true, true }, "bySensorReading");
    evaluateQuery(tx.query().has("name", "v105"), ElementCategory.VERTEX, 1, new boolean[] { true, true }, "bySensorReading");
    evaluateQuery(tx.query().has("name", "v205"), ElementCategory.VERTEX, 1, new boolean[] { true, true }, "bySensorReading");
    finishSchema();
    eindex = mgmt.getRelationIndex(mgmt.getRelationType("friend"), "byTime");
    ScanMetrics reindexFriendByTime = mgmt.updateIndex(eindex, SchemaAction.REINDEX).get();
    finishSchema();
    assertNotEquals(0, reindexFriendByTime.getCustom(IndexRepairJob.ADDED_RECORDS_COUNT));
    finishSchema();
    newTx();
    //It should now have all the answers
    v = getV(tx, v);
    evaluateQuery(v.query().labels("friend").direction(OUT).interval("time", 1, 5).orderBy("time", decr), EDGE, 4, 1, new boolean[] { true, true }, tx.getPropertyKey("time"), Order.DESC);
    evaluateQuery(v.query().labels("friend").direction(OUT).interval("time", 101, 105).orderBy("time", decr), EDGE, 4, 1, new boolean[] { true, true }, tx.getPropertyKey("time"), Order.DESC);
    evaluateQuery(v.query().labels("friend").direction(OUT).interval("time", 201, 205).orderBy("time", decr), EDGE, 4, 1, new boolean[] { true, true }, tx.getPropertyKey("time"), Order.DESC);
    pindex = mgmt.getRelationIndex(mgmt.getRelationType("sensor"), "byTime");
    gindex = mgmt.getGraphIndex("bySensorReading");
    mgmt.updateIndex(pindex, SchemaAction.DISABLE_INDEX);
    mgmt.updateIndex(gindex, SchemaAction.DISABLE_INDEX);
    mgmt.commit();
    tx.commit();
    ManagementUtil.awaitVertexIndexUpdate(graph, "byTime", "sensor", 10, ChronoUnit.SECONDS);
    ManagementUtil.awaitGraphIndexUpdate(graph, "bySensorReading", 5, ChronoUnit.SECONDS);
    finishSchema();
    pindex = mgmt.getRelationIndex(mgmt.getRelationType("sensor"), "byTime");
    gindex = mgmt.getGraphIndex("bySensorReading");
    assertEquals(SchemaStatus.DISABLED, pindex.getIndexStatus());
    assertEquals(SchemaStatus.DISABLED, gindex.getIndexStatus(gindex.getFieldKeys()[0]));
    finishSchema();
    newTx();
    //The two disabled indexes should force full scans
    v = getV(tx, v);
    evaluateQuery(v.query().keys("sensor").interval("time", 1, 5).orderBy("time", decr), PROPERTY, 4, 1, new boolean[] { false, false }, tx.getPropertyKey("time"), Order.DESC);
    evaluateQuery(v.query().keys("sensor").interval("time", 101, 105).orderBy("time", decr), PROPERTY, 4, 1, new boolean[] { false, false }, tx.getPropertyKey("time"), Order.DESC);
    evaluateQuery(v.query().keys("sensor").interval("time", 201, 205).orderBy("time", decr), PROPERTY, 4, 1, new boolean[] { false, false }, tx.getPropertyKey("time"), Order.DESC);
    evaluateQuery(v.query().labels("friend").direction(OUT).interval("time", 1, 5).orderBy("time", decr), EDGE, 4, 1, new boolean[] { true, true }, tx.getPropertyKey("time"), Order.DESC);
    evaluateQuery(v.query().labels("friend").direction(OUT).interval("time", 101, 105).orderBy("time", decr), EDGE, 4, 1, new boolean[] { true, true }, tx.getPropertyKey("time"), Order.DESC);
    evaluateQuery(v.query().labels("friend").direction(OUT).interval("time", 201, 205).orderBy("time", decr), EDGE, 4, 1, new boolean[] { true, true }, tx.getPropertyKey("time"), Order.DESC);
    evaluateQuery(tx.query().has("name", "v5"), ElementCategory.VERTEX, 1, new boolean[] { false, true });
    evaluateQuery(tx.query().has("name", "v105"), ElementCategory.VERTEX, 1, new boolean[] { false, true });
    evaluateQuery(tx.query().has("name", "v205"), ElementCategory.VERTEX, 1, new boolean[] { false, true });
    tx.commit();
    finishSchema();
    pindex = mgmt.getRelationIndex(mgmt.getRelationType("sensor"), "byTime");
    gindex = mgmt.getGraphIndex("bySensorReading");
    ScanMetrics pmetrics = mgmt.updateIndex(pindex, SchemaAction.REMOVE_INDEX).get();
    ScanMetrics gmetrics = mgmt.updateIndex(gindex, SchemaAction.REMOVE_INDEX).get();
    finishSchema();
    assertEquals(30, pmetrics.getCustom(IndexRemoveJob.DELETED_RECORDS_COUNT));
    assertEquals(30, gmetrics.getCustom(IndexRemoveJob.DELETED_RECORDS_COUNT));
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TitanVertex(com.thinkaurelius.titan.core.TitanVertex) EdgeLabel(com.thinkaurelius.titan.core.EdgeLabel) ScanMetrics(com.thinkaurelius.titan.diskstorage.keycolumnvalue.scan.ScanMetrics) RelationTypeIndex(com.thinkaurelius.titan.core.schema.RelationTypeIndex) TitanGraphIndex(com.thinkaurelius.titan.core.schema.TitanGraphIndex) PropertyKey(com.thinkaurelius.titan.core.PropertyKey) Test(org.junit.Test)

Aggregations

EdgeLabel (com.thinkaurelius.titan.core.EdgeLabel)23 PropertyKey (com.thinkaurelius.titan.core.PropertyKey)18 TitanVertex (com.thinkaurelius.titan.core.TitanVertex)18 Test (org.junit.Test)18 TitanEdge (com.thinkaurelius.titan.core.TitanEdge)8 Edge (org.apache.tinkerpop.gremlin.structure.Edge)8 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 TitanTransaction (com.thinkaurelius.titan.core.TitanTransaction)5 TitanVertexProperty (com.thinkaurelius.titan.core.TitanVertexProperty)5 TitanGraphIndex (com.thinkaurelius.titan.core.schema.TitanGraphIndex)5 VertexLabel (com.thinkaurelius.titan.core.VertexLabel)4 RelationTypeIndex (com.thinkaurelius.titan.core.schema.RelationTypeIndex)4 BaseVertexLabel (com.thinkaurelius.titan.graphdb.types.system.BaseVertexLabel)4 Vertex (org.apache.tinkerpop.gremlin.structure.Vertex)4 VertexProperty (org.apache.tinkerpop.gremlin.structure.VertexProperty)4 InternalRelationType (com.thinkaurelius.titan.graphdb.internal.InternalRelationType)3 StandardEdgeLabelMaker (com.thinkaurelius.titan.graphdb.types.StandardEdgeLabelMaker)3 SchemaViolationException (com.thinkaurelius.titan.core.SchemaViolationException)2 VertexList (com.thinkaurelius.titan.core.VertexList)2 Change (com.thinkaurelius.titan.core.log.Change)2