Java Code Examples for com.thinkaurelius.titan.core.TitanVertex

The following are top voted examples for showing how to use com.thinkaurelius.titan.core.TitanVertex. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: titan1withtp3.1   File: TitanGraphTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testArrayEqualityUsingImplicitKey() {
    TitanVertex v = graph.addVertex();

    byte singleDimension[] = new byte[]{127, 0, 0, 1};
    byte singleDimensionCopy[] = new byte[]{127, 0, 0, 1};
    final String singlePropName = "single";

    v.property(singlePropName, singleDimension);

    assertEquals(1, Iterables.size(graph.query().has(singlePropName, singleDimension).vertices()));
    assertEquals(1, Iterables.size(graph.query().has(singlePropName, singleDimensionCopy).vertices()));

    graph.tx().commit();

    assertEquals(1, Iterables.size(graph.query().has(singlePropName, singleDimension).vertices()));
    assertEquals(1, Iterables.size(graph.query().has(singlePropName, singleDimensionCopy).vertices()));
}
 
Example 2
Project: titan1withtp3.1   File: TitanGraphTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testStaleVertex() {
    PropertyKey name = mgmt.makePropertyKey("name").dataType(String.class).make();
    PropertyKey age = mgmt.makePropertyKey("age").dataType(Integer.class).make();
    mgmt.buildIndex("byName", Vertex.class).addKey(name).unique().buildCompositeIndex();
    finishSchema();


    TitanVertex cartman = graph.addVertex("name", "cartman", "age", 10);
    TitanVertex stan = graph.addVertex("name", "stan", "age", 8);

    graph.tx().commit();

    cartman = getOnlyElement(graph.query().has("name", "cartman").vertices());

    graph.tx().commit();

    TitanVertexProperty p = (TitanVertexProperty) cartman.properties().next();
    assertTrue(((Long) p.longId()) > 0);
    graph.tx().commit();
}
 
Example 3
Project: titan1withtp3.1   File: TitanGraphTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testEdgesExceedCacheSize() {
    // Add a vertex with as many edges as the tx-cache-size. (20000 by default)
    int numEdges = graph.getConfiguration().getTxVertexCacheSize();
    TitanVertex parentVertex = graph.addVertex();
    for (int i = 0; i < numEdges; i++) {
        TitanVertex childVertex = graph.addVertex();
        parentVertex.addEdge("friend", childVertex);
    }
    graph.tx().commit();
    assertCount(numEdges, parentVertex.query().direction(Direction.OUT).edges());

    // Remove an edge.
    parentVertex.query().direction(OUT).edges().iterator().next().remove();

    // Check that getEdges returns one fewer.
    assertCount(numEdges - 1, parentVertex.query().direction(Direction.OUT).edges());

    // Run the same check one more time.
    // This fails! (Expected: 19999. Actual: 20000.)
    assertCount(numEdges - 1, parentVertex.query().direction(Direction.OUT).edges());
}
 
Example 4
Project: titan0.5.4-hbase1.1.1-custom   File: VertexLongList.java   Source Code and License 6 votes vote down vote up
@Override
public Iterator<TitanVertex> iterator() {
    return new Iterator<TitanVertex>() {

        private int pos = -1;

        @Override
        public boolean hasNext() {
            return (pos + 1) < size();
        }

        @Override
        public TitanVertex next() {
            if (!hasNext()) throw new NoSuchElementException();
            pos++;
            return get(pos);
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException("Vertices cannot be removed from neighborhood list");
        }

    };
}
 
Example 5
Project: titan1withtp3.1   File: TitanGraphTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testLargeJointIndexRetrieval() {
    makeVertexIndexedKey("sid", Integer.class);
    makeVertexIndexedKey("color", String.class);
    finishSchema();

    int sids = 17;
    String[] colors = {"blue", "red", "yellow", "brown", "green", "orange", "purple"};
    int multiplier = 200;
    int numV = sids * colors.length * multiplier;
    for (int i = 0; i < numV; i++) {
        TitanVertex v = graph.addVertex(
                "color", colors[i % colors.length],
                "sid", i % sids);
    }
    clopen();

    assertCount(numV / sids, graph.query().has("sid", 8).vertices());
    assertCount(numV / colors.length, graph.query().has("color", colors[2]).vertices());

    assertCount(multiplier, graph.query().has("sid", 11).has("color", colors[3]).vertices());
}
 
Example 6
Project: titan1.0.1.kafka   File: VertexMapJob.java   Source Code and License 6 votes vote down vote up
@Override
public void process(TitanVertex vertex, ScanMetrics metrics) {
    PreloadedVertex v = (PreloadedVertex) vertex;
    if (vertexMemory != null) {
        VertexMemoryHandler vh = new VertexMemoryHandler(vertexMemory, v);
        v.setPropertyMixing(vh);
    }
    v.setAccessCheck(MAPREDUCE_CHECK);
    if (idManager.isPartitionedVertex(v.longId()) && !idManager.isCanonicalVertexId(v.longId())) {
        return; //Only consider the canonical partition vertex representative
    } else {
        for (Map.Entry<MapReduce, FulgoraMapEmitter> mapJob : mapJobs.entrySet()) {
            MapReduce job = mapJob.getKey();
            try {
                job.map(v, mapJob.getValue());
                metrics.incrementCustom(MAP_JOB_SUCCESS);
            } catch (Throwable ex) {
                log.error("Encountered exception executing map job [" + job + "] on vertex [" + vertex + "]:", ex);
                metrics.incrementCustom(MAP_JOB_FAILURE);
            }
        }
    }
}
 
Example 7
Project: titan1.0.1.kafka   File: TitanIndexTest.java   Source Code and License 6 votes vote down vote up
/**
 * Tests indexing using _all virtual field
 */
@Test
public void testWidcardQuery() {
    if (supportsWildcardQuery()) {
        PropertyKey p1 = makeKey("p1", String.class);
        PropertyKey p2 = makeKey("p2", String.class);
        mgmt.buildIndex("mixedIndex", Vertex.class).addKey(p1).addKey(p2).buildMixedIndex(INDEX);

        finishSchema();
        clopen();

        TitanVertex v1 = graph.addVertex();
        v1.property("p1", "test1");
        v1.property("p2", "test2");

        clopen();//Flush the index
        assertEquals(v1, graph.indexQuery("mixedIndex", "v.*:\"test1\"").vertices().iterator().next().getElement());
        assertEquals(v1, graph.indexQuery("mixedIndex", "v.*:\"test2\"").vertices().iterator().next().getElement());
    }

}
 
Example 8
Project: titan1.0.1.kafka   File: ManagementSystem.java   Source Code and License 6 votes vote down vote up
@Override
public <T extends RelationType> Iterable<T> getRelationTypes(Class<T> clazz) {
    Preconditions.checkNotNull(clazz);
    Iterable<? extends TitanVertex> types = null;
    if (PropertyKey.class.equals(clazz)) {
        types = QueryUtil.getVertices(transaction, BaseKey.SchemaCategory, TitanSchemaCategory.PROPERTYKEY);
    } else if (EdgeLabel.class.equals(clazz)) {
        types = QueryUtil.getVertices(transaction, BaseKey.SchemaCategory, TitanSchemaCategory.EDGELABEL);
    } else if (RelationType.class.equals(clazz)) {
        types = Iterables.concat(getRelationTypes(EdgeLabel.class), getRelationTypes(PropertyKey.class));
    } else throw new IllegalArgumentException("Unknown type class: " + clazz);
    return Iterables.filter(Iterables.filter(types, clazz), new Predicate<T>() {
        @Override
        public boolean apply(@Nullable T t) {
            //Filter out all relation type indexes
            return ((InternalRelationType) t).getBaseType() == null;
        }
    });
}
 
Example 9
Project: titan0.5.4-hbase1.1.1-custom   File: LoaderScriptWrapper.java   Source Code and License 6 votes vote down vote up
public TitanEdge getEdge(FaunusEdge faunusEdge, TitanVertex in, TitanVertex out, TitanGraph graph, Mapper.Context context) {
    Bindings bindings = new SimpleBindings();
    bindings.put("faunusEdge", faunusEdge);
    bindings.put("inVertex", in);
    bindings.put("outVertex", out);
    bindings.put("graph", graph);
    bindings.put("context", context);
    bindings.put("log", LOGGER);
    DEFAULT_COMPAT.incrementContextCounter(context, Counters.EDGE_LOADER_SCRIPT_CALLS, 1L);
    try {
        TitanEdge edge = (TitanEdge)edgeMethod.eval(bindings);
        LOGGER.debug("Compiled edge method returned {}", edge);
        DEFAULT_COMPAT.incrementContextCounter(context, Counters.EDGE_LOADER_SCRIPT_RETURNS, 1L);
        return edge;
    } catch (ScriptException e) {
        DEFAULT_COMPAT.incrementContextCounter(context, Counters.EDGE_LOADER_SCRIPT_EXCEPTIONS, 1L);
        throw new RuntimeException(e);
    }
}
 
Example 10
Project: titan1withtp3.1   File: TitanIndexTest.java   Source Code and License 6 votes vote down vote up
private void testInstant(Instant firstTimestamp, Instant secondTimestamp, TitanVertex v1, TitanVertex v2) {
    assertEquals(v1, getOnlyVertex(graph.query().has("instant", Cmp.EQUAL, firstTimestamp)));
    assertEquals(v2, getOnlyVertex(graph.query().has("instant", Cmp.GREATER_THAN, firstTimestamp)));
    assertEquals(Sets.newHashSet(v1, v2), Sets.newHashSet(graph.query().has("instant", Cmp.GREATER_THAN_EQUAL, firstTimestamp).vertices()));
    assertEquals(v1, getOnlyVertex(graph.query().has("instant", Cmp.LESS_THAN, secondTimestamp)));
    assertEquals(Sets.newHashSet(v1, v2), Sets.newHashSet(graph.query().has("instant", Cmp.LESS_THAN_EQUAL, secondTimestamp).vertices()));
    assertEquals(v2, getOnlyVertex(graph.query().has("instant", Cmp.NOT_EQUAL, firstTimestamp)));


    clopen();//Flush the index
    assertEquals(v1, getOnlyVertex(graph.query().has("instant", Cmp.EQUAL, firstTimestamp)));
    assertEquals(v2, getOnlyVertex(graph.query().has("instant", Cmp.GREATER_THAN, firstTimestamp)));
    assertEquals(Sets.newHashSet(v1, v2), Sets.newHashSet(graph.query().has("instant", Cmp.GREATER_THAN_EQUAL, firstTimestamp).vertices()));
    assertEquals(v1, getOnlyVertex(graph.query().has("instant", Cmp.LESS_THAN, secondTimestamp)));
    assertEquals(Sets.newHashSet(v1, v2), Sets.newHashSet(graph.query().has("instant", Cmp.LESS_THAN_EQUAL, secondTimestamp).vertices()));
    assertEquals(v2, getOnlyVertex(graph.query().has("instant", Cmp.NOT_EQUAL, firstTimestamp)));
}
 
Example 11
Project: titan1withtp3.1   File: TitanIndexTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testIndexQueryWithScore() throws InterruptedException {
    PropertyKey textKey = mgmt.makePropertyKey("text").dataType(String.class).make();
    mgmt.buildIndex("store1", Vertex.class).addKey(textKey).buildMixedIndex(INDEX);
    mgmt.commit();

    TitanVertex v1 = tx.addVertex();
    TitanVertex v2 = tx.addVertex();
    TitanVertex v3 = tx.addVertex();

    v1.property("text", "Hello Hello Hello Hello Hello Hello Hello Hello");
    v2.property("text", "Hello abab abab fsdfsd sfdfsd sdffs fsdsdf fdf fsdfsd aera fsad abab abab fsdfsd sfdf");
    v3.property("text", "Hello");

    tx.commit();

    Thread.sleep(5000);

    Set<Double> scores = new HashSet<Double>();
    for (TitanIndexQuery.Result<TitanVertex> r : graph.indexQuery("store1", "v.text:(Hello)").vertices()) {
        scores.add(r.getScore());
    }

    Assert.assertEquals(3, scores.size());
}
 
Example 12
Project: titan1withtp3.1   File: TitanIndexTest.java   Source Code and License 6 votes vote down vote up
@Test
// this tests a case when there as AND with a single CONTAINS condition inside AND(name:(was here))
// which (in case of Solr) spans multiple conditions such as AND(AND(name:was, name:here))
// so we need to make sure that we don't apply AND twice.
public void testContainsWithMultipleValues() throws Exception {
    PropertyKey name = makeKey("name", String.class);

    mgmt.buildIndex("store1", Vertex.class).addKey(name).buildMixedIndex(INDEX);
    mgmt.commit();

    TitanVertex v1 = tx.addVertex();
    v1.property("name", "hercules was here");

    tx.commit();

    Thread.sleep(2000);

    TitanVertex r = Iterables.<TitanVertex>get(graph.query().has("name", Text.CONTAINS, "hercules here").vertices(), 0);
    Assert.assertEquals(r.property("name").value(), "hercules was here");
}
 
Example 13
Project: titan1withtp3.1   File: TitanIndexTest.java   Source Code and License 6 votes vote down vote up
/**
 * Tests indexing using _all virtual field
 */
@Test
public void testWidcardQuery() {
    if (supportsWildcardQuery()) {
        PropertyKey p1 = makeKey("p1", String.class);
        PropertyKey p2 = makeKey("p2", String.class);
        mgmt.buildIndex("mixedIndex", Vertex.class).addKey(p1).addKey(p2).buildMixedIndex(INDEX);

        finishSchema();
        clopen();

        TitanVertex v1 = graph.addVertex();
        v1.property("p1", "test1");
        v1.property("p2", "test2");

        clopen();//Flush the index
        assertEquals(v1, graph.indexQuery("mixedIndex", "v.*:\"test1\"").vertices().iterator().next().getElement());
        assertEquals(v1, graph.indexQuery("mixedIndex", "v.*:\"test2\"").vertices().iterator().next().getElement());
    }

}
 
Example 14
Project: titan1.0.1.kafka   File: TitanGraphTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testForceIndexUsage() {
    PropertyKey age = makeKey("age", Integer.class);
    PropertyKey time = makeKey("time", Long.class);
    mgmt.buildIndex("time", Vertex.class).addKey(time).buildCompositeIndex();
    finishSchema();

    for (int i = 1; i <= 10; i++) {
        TitanVertex v = tx.addVertex("time", i, "age", i);
    }

    //Graph query with and with-out index support
    assertCount(1, tx.query().has("time", 5).vertices());
    assertCount(1, tx.query().has("age", 6).vertices());

    clopen(option(FORCE_INDEX_USAGE), true);
    //Query with-out index support should now throw exception
    assertCount(1, tx.query().has("time", 5).vertices());
    try {
        assertCount(1, tx.query().has("age", 6).vertices());
        fail();
    } catch (Exception e) {
    }
}
 
Example 15
Project: titan1.0.1.kafka   File: PartitionedVertexProgramExecutor.java   Source Code and License 6 votes vote down vote up
@Override
public void run() {
    try {
        TitanVertex vertex = tx.getInternalVertex(vertexId);
        Preconditions.checkArgument(vertex instanceof PreloadedVertex,
                "The bounding transaction is not configured correctly");
        PreloadedVertex v = (PreloadedVertex)vertex;
        v.setAccessCheck(PreloadedVertex.OPENSTAR_CHECK);
        v.addToQueryCache(VertexProgramScanJob.SYSTEM_PROPS_QUERY,preloaded);
        VertexMemoryHandler.Partition<M> vh = new VertexMemoryHandler.Partition<M>(vertexMemory,v);
        v.setPropertyMixing(vh);
        vertexProgram.execute(v,vh,memory);
        metrics.incrementCustom(PARTITION_VERTEX_POSTSUCCESS);
    } catch (Throwable e) {
        metrics.incrementCustom(PARTITION_VERTEX_POSTFAIL);
        log.error("Error post-processing partition vertex: " + vertexId,e);
    }
}
 
Example 16
Project: titan1.0.1.kafka   File: VertexLongList.java   Source Code and License 6 votes vote down vote up
@Override
public Iterator<TitanVertex> iterator() {
    return new Iterator<TitanVertex>() {

        private int pos = -1;

        @Override
        public boolean hasNext() {
            return (pos + 1) < size();
        }

        @Override
        public TitanVertex next() {
            if (!hasNext()) throw new NoSuchElementException();
            pos++;
            return get(pos);
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException("Vertices cannot be removed from neighborhood list");
        }

    };
}
 
Example 17
Project: titan0.5.4-hbase1.1.1-custom   File: EdgeSerializerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testValueOrdering() {
    StandardTitanGraph graph = (StandardTitanGraph) StorageSetup.getInMemoryGraph();
    TitanManagement mgmt = graph.getManagementSystem();
    EdgeLabel father = mgmt.makeEdgeLabel("father").multiplicity(Multiplicity.MANY2ONE).make();
    for (int i=1;i<=5;i++) mgmt.makePropertyKey("key" + i).dataType(Integer.class).make();
    mgmt.commit();

    TitanVertex v1 = graph.addVertex(null), v2 = graph.addVertex(null);
    TitanEdge e1 = v1.addEdge("father",v2);
    for (int i=1;i<=5;i++) e1.setProperty("key"+i,i);

    graph.commit();

    e1.remove();
    graph.commit();

}
 
Example 18
Project: titan1withtp3.1   File: PropertyPlacementStrategy.java   Source Code and License 6 votes vote down vote up
private int getPartitionIDbyKey(TitanVertex vertex) {
    Preconditions.checkState(idManager!=null && key!=null,"PropertyPlacementStrategy has not been initialized correctly");
    assert idManager.getPartitionBound()<=Integer.MAX_VALUE;
    int partitionBound = (int)idManager.getPartitionBound();
    TitanVertexProperty p = (TitanVertexProperty)Iterables.getFirst(vertex.query().keys(key).properties(),null);
    if (p==null) return -1;
    int hashPid = Math.abs(p.value().hashCode())%partitionBound;
    assert hashPid>=0 && hashPid<partitionBound;
    if (isExhaustedPartition(hashPid)) {
        //We keep trying consecutive partition ids until we find a non-exhausted one
        int newPid=hashPid;
        do {
            newPid = (newPid+1)%partitionBound;
            if (newPid==hashPid) //We have gone full circle - no more ids to try
                throw new IDPoolExhaustedException("Could not find non-exhausted partition");
        } while (isExhaustedPartition(newPid));
        return newPid;
    } else return hashPid;
}
 
Example 19
Project: titan0.5.4-hbase1.1.1-custom   File: LoaderScriptWrapper.java   Source Code and License 6 votes vote down vote up
public TitanVertex getVertex(FaunusVertex faunusVertex, TitanGraph graph, Mapper.Context context) {
    Bindings bindings = new SimpleBindings();
    bindings.put("faunusVertex", faunusVertex);
    bindings.put("graph", graph);
    bindings.put("context", context);
    bindings.put("log", LOGGER);
    DEFAULT_COMPAT.incrementContextCounter(context, Counters.VERTEX_LOADER_SCRIPT_CALLS, 1L);
    try {
        TitanVertex tv = (TitanVertex)vertexMethod.eval(bindings);
        LOGGER.debug("Compiled vertex loader script returned {}", tv);
        DEFAULT_COMPAT.incrementContextCounter(context, Counters.VERTEX_LOADER_SCRIPT_RETURNS, 1L);
        return tv;
    } catch (ScriptException e) {
        DEFAULT_COMPAT.incrementContextCounter(context, Counters.VERTEX_LOADER_SCRIPT_EXCEPTIONS, 1L);
        throw new RuntimeException(e);
    }
}
 
Example 20
Project: titan1withtp3.1   File: ManagementSystem.java   Source Code and License 6 votes vote down vote up
@Override
public <T extends RelationType> Iterable<T> getRelationTypes(Class<T> clazz) {
    Preconditions.checkNotNull(clazz);
    Iterable<? extends TitanVertex> types = null;
    if (PropertyKey.class.equals(clazz)) {
        types = QueryUtil.getVertices(transaction, BaseKey.SchemaCategory, TitanSchemaCategory.PROPERTYKEY);
    } else if (EdgeLabel.class.equals(clazz)) {
        types = QueryUtil.getVertices(transaction, BaseKey.SchemaCategory, TitanSchemaCategory.EDGELABEL);
    } else if (RelationType.class.equals(clazz)) {
        types = Iterables.concat(getRelationTypes(EdgeLabel.class), getRelationTypes(PropertyKey.class));
    } else throw new IllegalArgumentException("Unknown type class: " + clazz);
    return Iterables.filter(Iterables.filter(types, clazz), new Predicate<T>() {
        @Override
        public boolean apply(@Nullable T t) {
            //Filter out all relation type indexes
            return ((InternalRelationType) t).getBaseType() == null;
        }
    });
}
 
Example 21
Project: titan1withtp3.1   File: ElementUtils.java   Source Code and License 6 votes vote down vote up
public static long getVertexId(Object id) {
    if (null == id) return 0;

    if (id instanceof TitanVertex) //allows vertices to be "re-attached" to the current transaction
        return ((TitanVertex) id).longId();
    if (id instanceof Long)
        return (Long) id;
    if (id instanceof Number)
        return ((Number) id).longValue();

    try {
        // handles the case of a user passing a "detached" Vertex (DetachedVertex, StarVertex, etc).
        if (id instanceof Vertex)
            return Long.parseLong(((Vertex) id).id().toString());
        else
            return Long.valueOf(id.toString()).longValue();
    } catch (NumberFormatException e) {
        return 0;
    }
}
 
Example 22
Project: titan1.0.1.kafka   File: ElementUtils.java   Source Code and License 6 votes vote down vote up
public static long getVertexId(Object id) {
    if (null == id) return 0;

    if (id instanceof TitanVertex) //allows vertices to be "re-attached" to the current transaction
        return ((TitanVertex) id).longId();
    if (id instanceof Long)
        return (Long) id;
    if (id instanceof Number)
        return ((Number) id).longValue();

    try {
        // handles the case of a user passing a "detached" Vertex (DetachedVertex, StarVertex, etc).
        if (id instanceof Vertex)
            return Long.parseLong(((Vertex) id).id().toString());
        else
            return Long.valueOf(id.toString()).longValue();
    } catch (NumberFormatException e) {
        return 0;
    }
}
 
Example 23
Project: incubator-atlas   File: Titan1IndexQuery.java   Source Code and License 6 votes vote down vote up
@Override
public Iterator<Result<Titan1Vertex, Titan1Edge>> vertices(int offset, int limit) {
    Preconditions.checkArgument(offset >=0, "Index offset should be greater than or equals to 0");
    Preconditions.checkArgument(limit >=0, "Index limit should be greater than or equals to 0");
    Iterator<TitanIndexQuery.Result<TitanVertex>> results = query
            .offset(offset)
            .limit(limit)
            .vertices().iterator();

    Function<TitanIndexQuery.Result<TitanVertex>, Result<Titan1Vertex, Titan1Edge>> function =
            new Function<TitanIndexQuery.Result<TitanVertex>, Result<Titan1Vertex, Titan1Edge>>() {

                @Override
                public Result<Titan1Vertex, Titan1Edge> apply(TitanIndexQuery.Result<TitanVertex> source) {
                    return new ResultImpl(source);
                }
            };

    return Iterators.transform(results, function);
}
 
Example 24
Project: titan1.0.1.kafka   File: PropertyPlacementStrategy.java   Source Code and License 6 votes vote down vote up
private int getPartitionIDbyKey(TitanVertex vertex) {
    Preconditions.checkState(idManager!=null && key!=null,"PropertyPlacementStrategy has not been initialized correctly");
    assert idManager.getPartitionBound()<=Integer.MAX_VALUE;
    int partitionBound = (int)idManager.getPartitionBound();
    TitanVertexProperty p = (TitanVertexProperty)Iterables.getFirst(vertex.query().keys(key).properties(),null);
    if (p==null) return -1;
    int hashPid = Math.abs(p.value().hashCode())%partitionBound;
    assert hashPid>=0 && hashPid<partitionBound;
    if (isExhaustedPartition(hashPid)) {
        //We keep trying consecutive partition ids until we find a non-exhausted one
        int newPid=hashPid;
        do {
            newPid = (newPid+1)%partitionBound;
            if (newPid==hashPid) //We have gone full circle - no more ids to try
                throw new IDPoolExhaustedException("Could not find non-exhausted partition");
        } while (isExhaustedPartition(newPid));
        return newPid;
    } else return hashPid;
}
 
Example 25
Project: titan1.0.1.kafka   File: TitanGraphTest.java   Source Code and License 6 votes vote down vote up
/**
 * Tests that self-loop edges are handled and counted correctly
 */
@Test
public void testSelfLoop() {
    TitanVertex v = tx.addVertex();
    v.addEdge("self", v);
    assertCount(1, v.query().direction(Direction.OUT).labels("self").edges());
    assertCount(1, v.query().direction(Direction.IN).labels("self").edges());
    assertCount(2, v.query().direction(Direction.BOTH).labels("self").edges());
    clopen();
    v = getV(tx, v);
    assertNotNull(v);
    assertCount(1, v.query().direction(Direction.IN).labels("self").edges());
    assertCount(1, v.query().direction(Direction.OUT).labels("self").edges());
    assertCount(1, v.query().direction(Direction.IN).labels("self").edges());
    assertCount(2, v.query().direction(Direction.BOTH).labels("self").edges());
}
 
Example 26
Project: titan1withtp3.1   File: TitanGraphTest.java   Source Code and License 5 votes vote down vote up
/**
 * Very simple graph operation to ensure minimal functionality and cleanup
 */
@Test
public void testBasic() {

    PropertyKey uid = makeVertexIndexedUniqueKey("name", String.class);
    finishSchema();

    TitanVertex n1 = tx.addVertex();
    uid = tx.getPropertyKey("name");
    n1.property(uid.name(), "abcd");
    clopen();
    long nid = n1.longId();
    uid = tx.getPropertyKey("name");
    assertTrue(getV(tx, nid) != null);
    assertTrue(getV(tx, uid.longId()) != null);
    assertMissing(tx, nid + 64);
    uid = tx.getPropertyKey(uid.name());
    n1 = getV(tx, nid);
    assertEquals(n1, getOnlyVertex(tx.query().has(uid.name(), "abcd")));
    assertEquals(1, Iterables.size(n1.query().relations())); //TODO: how to expose relations?
    assertEquals("abcd", n1.value(uid.name()));
    assertCount(1, tx.query().vertices());
    close();
    TitanCleanup.clear(graph);
    open(config);
    assertEmpty(tx.query().vertices());
}
 
Example 27
Project: titan1withtp3.1   File: TitanGraphTest.java   Source Code and License 5 votes vote down vote up
/**
 * Adding a removing a vertex with index
 */
@Test
public void testVertexRemoval() {
    final String namen = "name";
    makeVertexIndexedUniqueKey(namen, String.class);
    finishSchema();

    TitanVertex v1 = graph.addVertex(namen, "v1");
    TitanVertex v2 = graph.addVertex(namen, "v2");
    v1.addEdge("knows", v2);
    assertCount(2, graph.query().vertices());
    assertCount(1, graph.query().has(namen, "v2").vertices());

    clopen();

    v1 = getV(graph, v1);
    v2 = getV(graph, v2);
    assertCount(1, v1.query().direction(BOTH).edges());
    assertCount(1, v2.query().direction(Direction.BOTH).edges());
    v2.remove();
    assertCount(0, v1.query().direction(Direction.BOTH).edges());
    try {
        assertCount(0, v2.query().direction(Direction.BOTH).edges());
        fail();
    } catch (IllegalStateException ex) {
    }
    assertCount(1, graph.query().vertices());
    assertCount(1, graph.query().has(namen, "v1").vertices());
    assertCount(0, graph.query().has(namen, "v2").vertices());
    graph.tx().commit();

    assertMissing(graph, v2);
    assertCount(1, graph.query().vertices());
    assertCount(1, graph.query().has(namen, "v1").vertices());
    assertCount(0, graph.query().has(namen, "v2").vertices());
}
 
Example 28
Project: titan1.0.1.kafka   File: TitanGraphTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testEdgeTTLWithTransactions() throws Exception {
    if (!features.hasCellTTL()) {
        return;
    }

    EdgeLabel label1 = mgmt.makeEdgeLabel("likes").make();
    mgmt.setTTL(label1, Duration.ofSeconds(1));
    assertEquals(Duration.ofSeconds(1), mgmt.getTTL(label1));
    mgmt.commit();

    TitanVertex v1 = graph.addVertex(), v2 = graph.addVertex();

    v1.addEdge("likes", v2);

    // pre-commit state of the edge.  It is not yet subject to TTL
    assertNotEmpty(v1.query().direction(Direction.OUT).vertices());

    Thread.sleep(1001);

    // the edge should have expired by now, but only if it had been committed
    assertNotEmpty(v1.query().direction(Direction.OUT).vertices());

    graph.tx().commit();

    // still here, because we have just committed the edge.  Its countdown starts at the commit
    assertNotEmpty(v1.query().direction(Direction.OUT).vertices());

    Thread.sleep(1001);

    // the edge has expired in Cassandra, but still appears alive in this transaction
    assertNotEmpty(v1.query().direction(Direction.OUT).vertices());

    // syncing with the data store, we see that the edge has expired
    graph.tx().rollback();
    assertEmpty(v1.query().direction(Direction.OUT).vertices());
}
 
Example 29
Project: titan1withtp3.1   File: TitanGraphTest.java   Source Code and License 5 votes vote down vote up
private void verifyVerticesRetrieval(long[] vids, List<TitanVertex> vs) {
    assertEquals(vids.length, vs.size());
    Set<Long> vset = new HashSet<>(vs.size());
    vs.forEach(v -> vset.add((Long) v.id()));
    for (int i = 0; i < vids.length; i++) {
        assertTrue(vset.contains(vids[i]));
    }
}
 
Example 30
Project: titan1.0.1.kafka   File: VisibilityFilterCondition.java   Source Code and License 5 votes vote down vote up
@Override
public boolean evaluate(E element) {
    switch(visibility) {
        case NORMAL: return !((InternalElement)element).isInvisible();
        case SYSTEM: return (element instanceof TitanRelation &&
                                ((TitanRelation)element).getType() instanceof SystemRelationType)
                || (element instanceof TitanVertex && element instanceof TitanSchemaElement);
        default: throw new AssertionError("Unrecognized visibility: " + visibility);
    }
}
 
Example 31
Project: titan1withtp3.1   File: TitanGraphTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test the correct application of {@link com.thinkaurelius.titan.graphdb.types.system.ImplicitKey}
 * to vertices, edges, and properties.
 * <p/>
 * Additionally tests RelationIdentifier since this is closely related to ADJACENT and TITANID implicit keys.
 */
@Test
public void testImplicitKey() {
    TitanVertex v = graph.addVertex("name", "Dan"), u = graph.addVertex();
    Edge e = v.addEdge("knows", u);
    graph.tx().commit();
    RelationIdentifier eid = (RelationIdentifier) e.id();

    assertEquals(v.id(), v.value(ID_NAME));
    assertEquals(eid, e.value(ID_NAME));
    assertEquals("knows", e.value(LABEL_NAME));
    assertEquals(BaseVertexLabel.DEFAULT_VERTEXLABEL.name(), v.value(LABEL_NAME));
    assertCount(1, v.query().direction(Direction.BOTH).labels("knows").has(ID_NAME, eid).edges());
    assertCount(0, v.query().direction(Direction.BOTH).labels("knows").has(ID_NAME, RelationIdentifier.get(new long[]{4, 5, 6, 7})).edges());
    assertCount(1, v.query().direction(Direction.BOTH).labels("knows").has("~nid", eid.getRelationId()).edges());
    assertCount(0, v.query().direction(Direction.BOTH).labels("knows").has("~nid", 110111).edges());
    //Test edge retrieval
    assertNotNull(getE(graph, eid));
    assertEquals(eid, getE(graph, eid).id());
    //Test adjacent constraint
    assertEquals(1, v.query().direction(BOTH).has("~adjacent", u.id()).edgeCount());
    assertCount(1, v.query().direction(BOTH).has("~adjacent", (int) getId(u)).edges());
    try {
        //Not a valid vertex
        assertCount(0, v.query().direction(BOTH).has("~adjacent", 110111).edges());
        fail();
    } catch (IllegalArgumentException ex) {
    }

}
 
Example 32
Project: titan1withtp3.1   File: TitanGraphTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testVertexCentricIndexWithNull() {
    EdgeLabel bought = makeLabel("bought");
    PropertyKey time = makeKey("time", Long.class);
    mgmt.buildEdgeIndex(bought, "byTimeDesc", BOTH, decr, time);
    mgmt.buildEdgeIndex(bought, "byTimeIncr", BOTH, incr, time);
    finishSchema();

    TitanVertex v1 = tx.addVertex(), v2 = tx.addVertex();
    v1.addEdge("bought", v2).property("time", 1);
    v1.addEdge("bought", v2).property("time", 2);
    v1.addEdge("bought", v2).property("time", 3);
    v1.addEdge("bought", v2);
    v1.addEdge("bought", v2);

    assertEquals(5, v1.query().direction(OUT).labels("bought").edgeCount());
    assertEquals(1, v1.query().direction(OUT).labels("bought").has("time", 1).edgeCount());
    assertEquals(1, v1.query().direction(OUT).labels("bought").has("time", Cmp.LESS_THAN, 3).has("time", Cmp.GREATER_THAN, 1).edgeCount());
    assertEquals(3, v1.query().direction(OUT).labels("bought").has("time", Cmp.LESS_THAN, 5).edgeCount());
    assertEquals(3, v1.query().direction(OUT).labels("bought").has("time", Cmp.GREATER_THAN, 0).edgeCount());
    assertEquals(2, v1.query().direction(OUT).labels("bought").has("time", Cmp.LESS_THAN, 3).edgeCount());
    assertEquals(1, v1.query().direction(OUT).labels("bought").has("time", Cmp.GREATER_THAN, 2).edgeCount());
    assertEquals(2, v1.query().direction(OUT).labels("bought").hasNot("time").edgeCount());
    assertEquals(5, v1.query().direction(OUT).labels("bought").edgeCount());


    newTx();
    v1 = tx.getVertex(v1.longId());
    //Queries copied from above

    assertEquals(5, v1.query().direction(OUT).labels("bought").edgeCount());
    assertEquals(1, v1.query().direction(OUT).labels("bought").has("time", 1).edgeCount());
    assertEquals(1, v1.query().direction(OUT).labels("bought").has("time", Cmp.LESS_THAN, 3).has("time", Cmp.GREATER_THAN, 1).edgeCount());
    assertEquals(3, v1.query().direction(OUT).labels("bought").has("time", Cmp.LESS_THAN, 5).edgeCount());
    assertEquals(3, v1.query().direction(OUT).labels("bought").has("time", Cmp.GREATER_THAN, 0).edgeCount());
    assertEquals(2, v1.query().direction(OUT).labels("bought").has("time", Cmp.LESS_THAN, 3).edgeCount());
    assertEquals(1, v1.query().direction(OUT).labels("bought").has("time", Cmp.GREATER_THAN, 2).edgeCount());
    assertEquals(2, v1.query().direction(OUT).labels("bought").hasNot("time").edgeCount());
    assertEquals(5, v1.query().direction(OUT).labels("bought").edgeCount());
}
 
Example 33
Project: titan1withtp3.1   File: TitanGraphTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testEdgeTTLWithTransactions() throws Exception {
    if (!features.hasCellTTL()) {
        return;
    }

    EdgeLabel label1 = mgmt.makeEdgeLabel("likes").make();
    mgmt.setTTL(label1, Duration.ofSeconds(1));
    assertEquals(Duration.ofSeconds(1), mgmt.getTTL(label1));
    mgmt.commit();

    TitanVertex v1 = graph.addVertex(), v2 = graph.addVertex();

    v1.addEdge("likes", v2);

    // pre-commit state of the edge.  It is not yet subject to TTL
    assertNotEmpty(v1.query().direction(Direction.OUT).vertices());

    Thread.sleep(1001);

    // the edge should have expired by now, but only if it had been committed
    assertNotEmpty(v1.query().direction(Direction.OUT).vertices());

    graph.tx().commit();

    // still here, because we have just committed the edge.  Its countdown starts at the commit
    assertNotEmpty(v1.query().direction(Direction.OUT).vertices());

    Thread.sleep(1001);

    // the edge has expired in Cassandra, but still appears alive in this transaction
    assertNotEmpty(v1.query().direction(Direction.OUT).vertices());

    // syncing with the data store, we see that the edge has expired
    graph.tx().rollback();
    assertEmpty(v1.query().direction(Direction.OUT).vertices());
}
 
Example 34
Project: titan1withtp3.1   File: TitanGraphTest.java   Source Code and License 5 votes vote down vote up
@Category({BrittleTests.class})
@Test
public void testEdgeTTLWithIndex() throws Exception {
    if (!features.hasCellTTL()) {
        return;
    }

    int ttl = 1; // artificially low TTL for test
    final PropertyKey time = mgmt.makePropertyKey("time").dataType(Integer.class).make();
    EdgeLabel wavedAt = mgmt.makeEdgeLabel("wavedAt").signature(time).make();
    mgmt.buildEdgeIndex(wavedAt, "timeindex", Direction.BOTH, decr, time);
    mgmt.buildIndex("edge-time", Edge.class).addKey(time).buildCompositeIndex();
    mgmt.setTTL(wavedAt, Duration.ofSeconds(ttl));
    assertEquals(Duration.ZERO, mgmt.getTTL(time));
    assertEquals(Duration.ofSeconds(ttl), mgmt.getTTL(wavedAt));
    mgmt.commit();

    TitanVertex v1 = graph.addVertex(), v2 = graph.addVertex();
    v1.addEdge("wavedAt", v2, "time", 42);

    assertTrue(v1.query().direction(Direction.OUT).interval("time", 0, 100).edges().iterator().hasNext());
    assertNotEmpty(v1.query().direction(Direction.OUT).edges());
    assertNotEmpty(graph.query().has("time", 42).edges());

    graph.tx().commit();
    long commitTime = System.currentTimeMillis();

    assertTrue(v1.query().direction(Direction.OUT).interval("time", 0, 100).edges().iterator().hasNext());
    assertNotEmpty(v1.query().direction(Direction.OUT).edges());
    assertNotEmpty(graph.query().has("time", 42).edges());

    Thread.sleep(commitTime + (ttl * 1000L + 100) - System.currentTimeMillis());
    graph.tx().rollback();

    assertFalse(v1.query().direction(Direction.OUT).interval("time", 0, 100).edges().iterator().hasNext());
    assertEmpty(v1.query().direction(Direction.OUT).edges());
    assertEmpty(graph.query().has("time", 42).edges());
}
 
Example 35
Project: titan1.0.1.kafka   File: TitanGraphTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testVertexTTLImplicitKey() throws Exception {
    Duration d;

    if (!features.hasCellTTL()) {
        return;
    }

    clopen(option(GraphDatabaseConfiguration.STORE_META_TTL, "edgestore"), true);

    int ttl1 = 1;
    VertexLabel label1 = mgmt.makeVertexLabel("event").setStatic().make();
    mgmt.setTTL(label1, Duration.ofSeconds(ttl1));
    assertEquals(Duration.ofSeconds(ttl1), mgmt.getTTL(label1));
    mgmt.commit();

    TitanVertex v1 = tx.addVertex("event");
    TitanVertex v2 = tx.addVertex();
    tx.commit();

    /* TODO: this fails
    d = v1.getProperty("~ttl");
    assertEquals(1, d);
    d = v2.getProperty("~ttl");
    assertEquals(0, d);
    */

    Object v1id = v1.id();
    Object v2id = v2.id();
    v1 = getV(graph, v1id);
    v2 = getV(graph, v2id);

    d = v1.value("~ttl");
    assertEquals(Duration.ofSeconds(1), d);
    d = v2.value("~ttl");
    assertEquals(Duration.ZERO, d);
}
 
Example 36
Project: titan1withtp3.1   File: TitanGraphTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testVertexTTLWithCompositeIndex() throws Exception {
    if (!features.hasCellTTL()) {
        return;
    }

    PropertyKey name = mgmt.makePropertyKey("name").dataType(String.class).make();
    PropertyKey time = mgmt.makePropertyKey("time").dataType(Long.class).make();
    TitanGraphIndex index1 = mgmt.buildIndex("index1", Vertex.class).addKey(name).buildCompositeIndex();
    TitanGraphIndex index2 = mgmt.buildIndex("index2", Vertex.class).addKey(name).addKey(time).buildCompositeIndex();
    VertexLabel label1 = mgmt.makeVertexLabel("event").setStatic().make();
    mgmt.setTTL(label1, Duration.ofSeconds(1));
    assertEquals(Duration.ZERO, mgmt.getTTL(name));
    assertEquals(Duration.ZERO, mgmt.getTTL(time));
    assertEquals(Duration.ofSeconds(1), mgmt.getTTL(label1));
    mgmt.commit();

    TitanVertex v1 = tx.addVertex(T.label, "event", "name", "some event", "time", System.currentTimeMillis());
    tx.commit();
    Object id = v1.id();

    v1 = getV(graph, id);
    assertNotNull(v1);
    assertNotEmpty(graph.query().has("name", "some event").vertices());

    Thread.sleep(1001);
    graph.tx().rollback();

    v1 = getV(graph, id);
    assertNull(v1);
    assertEmpty(graph.query().has("name", "some event").vertices());
}
 
Example 37
Project: titan1.0.1.kafka   File: TitanGraphTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testVertexTTLWithCompositeIndex() throws Exception {
    if (!features.hasCellTTL()) {
        return;
    }

    PropertyKey name = mgmt.makePropertyKey("name").dataType(String.class).make();
    PropertyKey time = mgmt.makePropertyKey("time").dataType(Long.class).make();
    TitanGraphIndex index1 = mgmt.buildIndex("index1", Vertex.class).addKey(name).buildCompositeIndex();
    TitanGraphIndex index2 = mgmt.buildIndex("index2", Vertex.class).addKey(name).addKey(time).buildCompositeIndex();
    VertexLabel label1 = mgmt.makeVertexLabel("event").setStatic().make();
    mgmt.setTTL(label1, Duration.ofSeconds(1));
    assertEquals(Duration.ZERO, mgmt.getTTL(name));
    assertEquals(Duration.ZERO, mgmt.getTTL(time));
    assertEquals(Duration.ofSeconds(1), mgmt.getTTL(label1));
    mgmt.commit();

    TitanVertex v1 = tx.addVertex(T.label, "event", "name", "some event", "time", System.currentTimeMillis());
    tx.commit();
    Object id = v1.id();

    v1 = getV(graph, id);
    assertNotNull(v1);
    assertNotEmpty(graph.query().has("name", "some event").vertices());

    Thread.sleep(1001);
    graph.tx().rollback();

    v1 = getV(graph, id);
    assertNull(v1);
    assertEmpty(graph.query().has("name", "some event").vertices());
}
 
Example 38
Project: titan1.0.1.kafka   File: TitanGraphTest.java   Source Code and License 5 votes vote down vote up
@Category({BrittleTests.class})
@Test
public void testEdgeTTLWithIndex() throws Exception {
    if (!features.hasCellTTL()) {
        return;
    }

    int ttl = 1; // artificially low TTL for test
    final PropertyKey time = mgmt.makePropertyKey("time").dataType(Integer.class).make();
    EdgeLabel wavedAt = mgmt.makeEdgeLabel("wavedAt").signature(time).make();
    mgmt.buildEdgeIndex(wavedAt, "timeindex", Direction.BOTH, decr, time);
    mgmt.buildIndex("edge-time", Edge.class).addKey(time).buildCompositeIndex();
    mgmt.setTTL(wavedAt, Duration.ofSeconds(ttl));
    assertEquals(Duration.ZERO, mgmt.getTTL(time));
    assertEquals(Duration.ofSeconds(ttl), mgmt.getTTL(wavedAt));
    mgmt.commit();

    TitanVertex v1 = graph.addVertex(), v2 = graph.addVertex();
    v1.addEdge("wavedAt", v2, "time", 42);

    assertTrue(v1.query().direction(Direction.OUT).interval("time", 0, 100).edges().iterator().hasNext());
    assertNotEmpty(v1.query().direction(Direction.OUT).edges());
    assertNotEmpty(graph.query().has("time", 42).edges());

    graph.tx().commit();
    long commitTime = System.currentTimeMillis();

    assertTrue(v1.query().direction(Direction.OUT).interval("time", 0, 100).edges().iterator().hasNext());
    assertNotEmpty(v1.query().direction(Direction.OUT).edges());
    assertNotEmpty(graph.query().has("time", 42).edges());

    Thread.sleep(commitTime + (ttl * 1000L + 100) - System.currentTimeMillis());
    graph.tx().rollback();

    assertFalse(v1.query().direction(Direction.OUT).interval("time", 0, 100).edges().iterator().hasNext());
    assertEmpty(v1.query().direction(Direction.OUT).edges());
    assertEmpty(graph.query().has("time", 42).edges());
}
 
Example 39
Project: titan1withtp3.1   File: TitanIndexTest.java   Source Code and License 5 votes vote down vote up
/**
 * Tests indexing boolean
 */
@Test
public void testBooleanIndexing() {
    PropertyKey name = makeKey("visible", Boolean.class);
    mgmt.buildIndex("booleanIndex", Vertex.class).
            addKey(name).buildMixedIndex(INDEX);
    finishSchema();
    clopen();

    TitanVertex v1 = graph.addVertex();
    v1.property("visible", true);

    TitanVertex v2 = graph.addVertex();
    v2.property("visible", false);

    assertCount(2, graph.vertices());
    assertEquals(v1, getOnlyVertex(graph.query().has("visible", true)));
    assertEquals(v2, getOnlyVertex(graph.query().has("visible", false)));
    assertEquals(v2, getOnlyVertex(graph.query().has("visible", Cmp.NOT_EQUAL, true)));
    assertEquals(v1, getOnlyVertex(graph.query().has("visible", Cmp.NOT_EQUAL, false)));

    clopen();//Flush the index
    assertCount(2, graph.vertices());
    assertEquals(v1, getOnlyVertex(graph.query().has("visible", true)));
    assertEquals(v2, getOnlyVertex(graph.query().has("visible", false)));
    assertEquals(v2, getOnlyVertex(graph.query().has("visible", Cmp.NOT_EQUAL, true)));
    assertEquals(v1, getOnlyVertex(graph.query().has("visible", Cmp.NOT_EQUAL, false)));
}
 
Example 40
Project: titan1.0.1.kafka   File: RelationIdentifier.java   Source Code and License 5 votes vote down vote up
TitanRelation findRelation(TitanTransaction tx) {
    TitanVertex v = ((StandardTitanTx)tx).getInternalVertex(outVertexId);
    if (v == null || v.isRemoved()) return null;
    TitanVertex typeVertex = tx.getVertex(typeId);
    if (typeVertex == null) return null;
    if (!(typeVertex instanceof RelationType))
        throw new IllegalArgumentException("Invalid RelationIdentifier: typeID does not reference a type");

    RelationType type = (RelationType) typeVertex;
    Iterable<? extends TitanRelation> rels;
    if (((RelationType) typeVertex).isEdgeLabel()) {
        Direction dir = Direction.OUT;
        TitanVertex other = ((StandardTitanTx)tx).getInternalVertex(inVertexId);
        if (other==null || other.isRemoved()) return null;
        if (((StandardTitanTx) tx).isPartitionedVertex(v) && !((StandardTitanTx) tx).isPartitionedVertex(other)) { //Swap for likely better performance
            TitanVertex tmp = other;
            other = v;
            v = tmp;
            dir = Direction.IN;
        }
        rels = ((VertexCentricQueryBuilder) v.query()).noPartitionRestriction().types((EdgeLabel) type).direction(dir).adjacent(other).edges();
    } else {
        rels = ((VertexCentricQueryBuilder) v.query()).noPartitionRestriction().types((PropertyKey) type).properties();
    }

    for (TitanRelation r : rels) {
        //Find current or previous relation
        if (r.longId() == relationId ||
                ((r instanceof StandardRelation) && ((StandardRelation) r).getPreviousID() == relationId)) return r;
    }
    return null;
}