Search in sources :

Example 6 with JanusGraphIndex

use of org.janusgraph.core.schema.JanusGraphIndex in project janusgraph by JanusGraph.

the class ConfigurationManagementGraph method createIndexIfDoesNotExist.

private void createIndexIfDoesNotExist(String indexName, String propertyKeyName, Class dataType, boolean unique) {
    graph.tx().rollback();
    JanusGraphManagement management = graph.openManagement();
    if (null == management.getGraphIndex(indexName)) {
        final PropertyKey key;
        boolean propertyKeyAlreadyExisted = false;
        if (null == management.getPropertyKey(propertyKeyName)) {
            key = management.makePropertyKey(propertyKeyName).dataType(dataType).make();
        } else {
            key = management.getPropertyKey(propertyKeyName);
            propertyKeyAlreadyExisted = true;
        }
        final JanusGraphIndex index;
        if (unique)
            index = management.buildIndex(indexName, Vertex.class).addKey(key).unique().buildCompositeIndex();
        else
            index = management.buildIndex(indexName, Vertex.class).addKey(key).buildCompositeIndex();
        try {
            if (index.getIndexStatus(key) == INSTALLED) {
                management.commit();
                ManagementSystem.awaitGraphIndexStatus(graph, indexName).call();
                management = graph.openManagement();
                if (propertyKeyAlreadyExisted) {
                    management.updateIndex(management.getGraphIndex(indexName), REINDEX).get();
                } else {
                    management.updateIndex(management.getGraphIndex(indexName), ENABLE_INDEX).get();
                }
            } else if (index.getIndexStatus(key) == REGISTERED) {
                if (propertyKeyAlreadyExisted) {
                    management.updateIndex(management.getGraphIndex(indexName), REINDEX).get();
                } else {
                    management.updateIndex(management.getGraphIndex(indexName), ENABLE_INDEX).get();
                }
            }
        } catch (InterruptedException | ExecutionException e) {
            log.warn("Failed to create index {} for ConfigurationManagementGraph with exception: {}", indexName, e);
            management.rollback();
            graph.tx().rollback();
        }
        management.commit();
        graph.tx().commit();
    } else {
        management.rollback();
        graph.tx().rollback();
    }
}
Also used : JanusGraphManagement(org.janusgraph.core.schema.JanusGraphManagement) Vertex(org.apache.tinkerpop.gremlin.structure.Vertex) JanusGraphIndex(org.janusgraph.core.schema.JanusGraphIndex) ExecutionException(java.util.concurrent.ExecutionException) PropertyKey(org.janusgraph.core.PropertyKey)

Example 7 with JanusGraphIndex

use of org.janusgraph.core.schema.JanusGraphIndex in project janusgraph by JanusGraph.

the class JanusGraphTest method testConcurrentConsistencyEnforcement.

/**
 * Execute multiple identical transactions concurrently. Note that since these transactions are running in the same process,
 * {@link org.janusgraph.diskstorage.locking.LocalLockMediator} is used to resolve lock contentions. If there is only
 * one lock needed in the whole transaction, exactly one transaction shall succeed and others shall fail due to local
 * lock contention. If there is more than one lock needed in the transaction, at most one transaction shall succeed
 * and others shall fail due to local lock contention.
 * @throws Exception
 */
@Test
public void testConcurrentConsistencyEnforcement() throws Exception {
    PropertyKey name = mgmt.makePropertyKey("name").dataType(String.class).cardinality(Cardinality.SINGLE).make();
    JanusGraphIndex nameIndex = mgmt.buildIndex("name", Vertex.class).addKey(name).unique().buildCompositeIndex();
    mgmt.setConsistency(nameIndex, ConsistencyModifier.LOCK);
    EdgeLabel married = mgmt.makeEdgeLabel("married").multiplicity(Multiplicity.ONE2ONE).make();
    mgmt.setConsistency(married, ConsistencyModifier.LOCK);
    mgmt.makeEdgeLabel("friend").multiplicity(Multiplicity.MULTI).make();
    finishSchema();
    JanusGraphVertex baseV = tx.addVertex("name", "base");
    newTx();
    final long baseVid = getId(baseV);
    final String nameA = "a", nameB = "b";
    final int parallelThreads = 4;
    // Only one lock is needed
    int[] results = executeParallelTransactions(tx -> {
        final JanusGraphVertex a = tx.addVertex();
        final JanusGraphVertex base = getV(tx, baseVid);
        base.addEdge("married", a);
    }, parallelThreads);
    int numOfSuccess = results[0];
    int numOfLockContentions = results[1];
    assertEquals(1, numOfSuccess);
    assertEquals(parallelThreads - 1, numOfLockContentions);
    // Two locks are needed. Note that the order of adding/modifying/deleting elements might not be consistent with
    // the order of real mutations during commit. Thus, it can be the case that one thread gets one lock and another
    // thread gets another, and both fail because they are unable to get the other lock.
    results = executeParallelTransactions(tx -> {
        tx.addVertex("name", nameA);
        final JanusGraphVertex b = tx.addVertex("name", nameB);
        b.addEdge("friend", b);
    }, parallelThreads);
    numOfSuccess = results[0];
    numOfLockContentions = results[1];
    assertTrue(numOfSuccess <= 1);
    assertEquals(parallelThreads - numOfSuccess, numOfLockContentions);
    newTx();
    final long numA = Iterables.size(tx.query().has("name", nameA).vertices());
    final long numB = Iterables.size(tx.query().has("name", nameB).vertices());
    assertTrue(numA <= 1);
    assertTrue(numB <= 1);
}
Also used : ManagementUtil(org.janusgraph.core.util.ManagementUtil) PredicateCondition(org.janusgraph.graphdb.query.condition.PredicateCondition) CacheVertex(org.janusgraph.graphdb.vertices.CacheVertex) BasicVertexCentricQueryBuilder(org.janusgraph.graphdb.query.vertex.BasicVertexCentricQueryBuilder) DisableDefaultSchemaMaker(org.janusgraph.core.schema.DisableDefaultSchemaMaker) JanusGraphAssert.getStepMetrics(org.janusgraph.testutil.JanusGraphAssert.getStepMetrics) Cardinality(org.janusgraph.core.Cardinality) Serializer(org.janusgraph.graphdb.database.serialize.Serializer) JanusGraphVertexStep(org.janusgraph.graphdb.tinkerpop.optimize.step.JanusGraphVertexStep) Duration(java.time.Duration) Map(java.util.Map) JanusGraphAssert.assertNotContains(org.janusgraph.testutil.JanusGraphAssert.assertNotContains) Path(java.nio.file.Path) Metrics(org.apache.tinkerpop.gremlin.process.traversal.util.Metrics) EnumSet(java.util.EnumSet) IndexRepairJob(org.janusgraph.graphdb.olap.job.IndexRepairJob) PropertyKey(org.janusgraph.core.PropertyKey) OUT(org.apache.tinkerpop.gremlin.structure.Direction.OUT) JanusGraphPredicateUtils(org.janusgraph.graphdb.query.JanusGraphPredicateUtils) EdgeSerializer(org.janusgraph.graphdb.database.EdgeSerializer) Arguments(org.junit.jupiter.params.provider.Arguments) VERBOSE_TX_RECOVERY(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.VERBOSE_TX_RECOVERY) CountDownLatch(java.util.concurrent.CountDownLatch) Stream(java.util.stream.Stream) LogProcessorFramework(org.janusgraph.core.log.LogProcessorFramework) ADJUST_LIMIT(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.ADJUST_LIMIT) RELATION(org.janusgraph.graphdb.internal.RelationCategory.RELATION) SCHEMA_CONSTRAINTS(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.SCHEMA_CONSTRAINTS) Assertions.fail(org.junit.jupiter.api.Assertions.fail) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) MultiCondition(org.janusgraph.graphdb.query.condition.MultiCondition) FORCE_INDEX_USAGE(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.FORCE_INDEX_USAGE) CUSTOM_ATTRIBUTE_CLASS(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.CUSTOM_ATTRIBUTE_CLASS) JanusGraphAssert.assertCount(org.janusgraph.testutil.JanusGraphAssert.assertCount) TestGraphConfigs(org.janusgraph.testutil.TestGraphConfigs) Supplier(java.util.function.Supplier) Lists(com.google.common.collect.Lists) Change(org.janusgraph.core.log.Change) GhostVertexRemover(org.janusgraph.graphdb.olap.job.GhostVertexRemover) StreamSupport(java.util.stream.StreamSupport) QueryUtil(org.janusgraph.graphdb.query.QueryUtil) LOG_SEND_DELAY(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.LOG_SEND_DELAY) ALLOW_STALE_CONFIG(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.ALLOW_STALE_CONFIG) T(org.apache.tinkerpop.gremlin.structure.T) ExecutionException(java.util.concurrent.ExecutionException) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) IDS_STORE_NAME(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.IDS_STORE_NAME) JanusGraphVertexQuery(org.janusgraph.core.JanusGraphVertexQuery) Preconditions(com.google.common.base.Preconditions) VertexLabel(org.janusgraph.core.VertexLabel) JanusGraphConfigurationException(org.janusgraph.core.JanusGraphConfigurationException) Log(org.janusgraph.diskstorage.log.Log) Date(java.util.Date) Assertions.assertNotEquals(org.junit.jupiter.api.Assertions.assertNotEquals) Random(java.util.Random) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SchemaStatus(org.janusgraph.core.schema.SchemaStatus) NotImplementedException(org.apache.commons.lang.NotImplementedException) AbstractEdge(org.janusgraph.graphdb.relations.AbstractEdge) TextP(org.apache.tinkerpop.gremlin.process.traversal.TextP) MethodSource(org.junit.jupiter.params.provider.MethodSource) Multiplicity(org.janusgraph.core.Multiplicity) RelationType(org.janusgraph.core.RelationType) ElementLifeCycle(org.janusgraph.graphdb.internal.ElementLifeCycle) FeatureFlag(org.janusgraph.testutil.FeatureFlag) Collection(java.util.Collection) LogTxMeta(org.janusgraph.graphdb.database.log.LogTxMeta) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) JanusGraphAssert.assertEmpty(org.janusgraph.testutil.JanusGraphAssert.assertEmpty) TestCategory(org.janusgraph.TestCategory) Test(org.junit.jupiter.api.Test) Objects(java.util.Objects) RelationIdentifier(org.janusgraph.graphdb.relations.RelationIdentifier) ImplicitKey(org.janusgraph.graphdb.types.system.ImplicitKey) InternalRelationType(org.janusgraph.graphdb.internal.InternalRelationType) STORAGE_BATCH(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.STORAGE_BATCH) Order.desc(org.apache.tinkerpop.gremlin.process.traversal.Order.desc) STORAGE_BACKEND(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.STORAGE_BACKEND) JanusGraphFeature(org.janusgraph.testutil.JanusGraphFeature) JanusGraphQuery(org.janusgraph.core.JanusGraphQuery) HashSet(java.util.HashSet) VertexProperty(org.apache.tinkerpop.gremlin.structure.VertexProperty) ImmutableList(com.google.common.collect.ImmutableList) Message(org.janusgraph.diskstorage.log.Message) TRANSACTION_LOG(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.TRANSACTION_LOG) RelationCategory(org.janusgraph.graphdb.internal.RelationCategory) Arguments.arguments(org.junit.jupiter.params.provider.Arguments.arguments) GraphOfTheGodsFactory(org.janusgraph.example.GraphOfTheGodsFactory) Logger(org.slf4j.Logger) BaseVertexLabel(org.janusgraph.graphdb.types.system.BaseVertexLabel) VertexList(org.janusgraph.core.VertexList) GraphTraversal(org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal) Contain(org.janusgraph.core.attribute.Contain) JanusGraphVertex(org.janusgraph.core.JanusGraphVertex) Arrays(java.util.Arrays) JanusGraphAssert.assertNotEmpty(org.janusgraph.testutil.JanusGraphAssert.assertNotEmpty) MessageReader(org.janusgraph.diskstorage.log.MessageReader) Geoshape(org.janusgraph.core.attribute.Geoshape) EDGE(org.janusgraph.graphdb.internal.RelationCategory.EDGE) JanusGraphTransaction(org.janusgraph.core.JanusGraphTransaction) WriteConfiguration(org.janusgraph.diskstorage.configuration.WriteConfiguration) StaticBuffer(org.janusgraph.diskstorage.StaticBuffer) Tag(org.junit.jupiter.api.Tag) LogTxStatus(org.janusgraph.graphdb.database.log.LogTxStatus) USE_MULTIQUERY(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.USE_MULTIQUERY) JanusGraphSchemaType(org.janusgraph.core.schema.JanusGraphSchemaType) JanusGraphFactory(org.janusgraph.core.JanusGraphFactory) EnumMap(java.util.EnumMap) TimestampProvider(org.janusgraph.diskstorage.util.time.TimestampProvider) StandardJanusGraph(org.janusgraph.graphdb.database.StandardJanusGraph) Set(java.util.Set) Vertex(org.apache.tinkerpop.gremlin.structure.Vertex) EdgeLabel(org.janusgraph.core.EdgeLabel) JanusGraphVertexProperty(org.janusgraph.core.JanusGraphVertexProperty) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) JanusGraphEdgeVertexStep(org.janusgraph.graphdb.tinkerpop.optimize.step.JanusGraphEdgeVertexStep) INITIAL_JANUSGRAPH_VERSION(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.INITIAL_JANUSGRAPH_VERSION) RelationTypeIndex(org.janusgraph.core.schema.RelationTypeIndex) GraphTraversalSource(org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) Iterables(com.google.common.collect.Iterables) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) SimpleQueryProfiler(org.janusgraph.graphdb.query.profile.SimpleQueryProfiler) PermanentLockingException(org.janusgraph.diskstorage.locking.PermanentLockingException) ArrayList(java.util.ArrayList) StandardTransactionLogProcessor(org.janusgraph.graphdb.log.StandardTransactionLogProcessor) ScanMetrics(org.janusgraph.diskstorage.keycolumnvalue.scan.ScanMetrics) Cmp(org.janusgraph.core.attribute.Cmp) ConsistencyModifier(org.janusgraph.core.schema.ConsistencyModifier) JanusGraphException(org.janusgraph.core.JanusGraphException) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) StandardEdgeLabelMaker(org.janusgraph.graphdb.types.StandardEdgeLabelMaker) MAX_COMMIT_TIME(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.MAX_COMMIT_TIME) JanusGraphElement(org.janusgraph.core.JanusGraphElement) TransactionLogHeader(org.janusgraph.graphdb.database.log.TransactionLogHeader) ValueSource(org.junit.jupiter.params.provider.ValueSource) TX_CACHE_SIZE(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.TX_CACHE_SIZE) File(java.io.File) Assertions.assertArrayEquals(org.junit.jupiter.api.Assertions.assertArrayEquals) ScanJobFuture(org.janusgraph.diskstorage.keycolumnvalue.scan.ScanJobFuture) Direction(org.apache.tinkerpop.gremlin.structure.Direction) SYSTEM_LOG_TRANSACTIONS(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.SYSTEM_LOG_TRANSACTIONS) ChronoUnit(java.time.temporal.ChronoUnit) HARD_MAX_LIMIT(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.HARD_MAX_LIMIT) Traversal(org.apache.tinkerpop.gremlin.process.traversal.Traversal) GraphDatabaseConfiguration(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration) TraversalMetrics(org.apache.tinkerpop.gremlin.process.traversal.util.TraversalMetrics) SpecialIntSerializer(org.janusgraph.graphdb.serializer.SpecialIntSerializer) StandardJanusGraphTx(org.janusgraph.graphdb.transaction.StandardJanusGraphTx) LoggerFactory(org.slf4j.LoggerFactory) ConfigOption(org.janusgraph.diskstorage.configuration.ConfigOption) JanusGraphEdge(org.janusgraph.core.JanusGraphEdge) SchemaAction(org.janusgraph.core.schema.SchemaAction) Order.asc(org.apache.tinkerpop.gremlin.process.traversal.Order.asc) OrderList(org.janusgraph.graphdb.internal.OrderList) BATCH_PROPERTY_PREFETCHING(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.BATCH_PROPERTY_PREFETCHING) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) JanusGraphManagement(org.janusgraph.core.schema.JanusGraphManagement) JanusGraphIndex(org.janusgraph.core.schema.JanusGraphIndex) IndexSelectionUtil(org.janusgraph.graphdb.query.index.IndexSelectionUtil) P(org.apache.tinkerpop.gremlin.process.traversal.P) BOTH(org.apache.tinkerpop.gremlin.structure.Direction.BOTH) TransactionRecovery(org.janusgraph.core.log.TransactionRecovery) USER_LOG(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.USER_LOG) Property(org.apache.tinkerpop.gremlin.structure.Property) SchemaViolationException(org.janusgraph.core.SchemaViolationException) Mapping(org.janusgraph.core.schema.Mapping) ImmutableMap(com.google.common.collect.ImmutableMap) IndexRemoveJob(org.janusgraph.graphdb.olap.job.IndexRemoveJob) StandardPropertyKeyMaker(org.janusgraph.graphdb.types.StandardPropertyKeyMaker) Sets(com.google.common.collect.Sets) LOG_READ_INTERVAL(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.LOG_READ_INTERVAL) List(java.util.List) TempDir(org.junit.jupiter.api.io.TempDir) JanusGraphDefaultSchemaMaker(org.janusgraph.core.schema.JanusGraphDefaultSchemaMaker) GraphCentricQueryBuilder(org.janusgraph.graphdb.query.graph.GraphCentricQueryBuilder) CUSTOM_SERIALIZER_CLASS(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.CUSTOM_SERIALIZER_CLASS) AUTO_TYPE(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.AUTO_TYPE) HashMap(java.util.HashMap) LIMIT_BATCH_SIZE(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.LIMIT_BATCH_SIZE) JanusGraphAssert.assertContains(org.janusgraph.testutil.JanusGraphAssert.assertContains) Backend(org.janusgraph.diskstorage.Backend) Iterators(com.google.common.collect.Iterators) SpecialInt(org.janusgraph.graphdb.serializer.SpecialInt) ConfigElement(org.janusgraph.diskstorage.configuration.ConfigElement) DB_CACHE(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.DB_CACHE) LOG_BACKEND(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.LOG_BACKEND) IgnorePropertySchemaMaker(org.janusgraph.core.schema.IgnorePropertySchemaMaker) Edge(org.apache.tinkerpop.gremlin.structure.Edge) BackendException(org.janusgraph.diskstorage.BackendException) MANAGEMENT_LOG(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.MANAGEMENT_LOG) QueryProfiler(org.janusgraph.graphdb.query.profile.QueryProfiler) KCVSLog(org.janusgraph.diskstorage.log.kcvs.KCVSLog) Iterator(java.util.Iterator) org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__(org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__) STORAGE_READONLY(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.STORAGE_READONLY) JanusGraph(org.janusgraph.core.JanusGraph) IN(org.apache.tinkerpop.gremlin.structure.Direction.IN) ElementCategory(org.janusgraph.graphdb.internal.ElementCategory) Order(org.janusgraph.graphdb.internal.Order) PROPERTY(org.janusgraph.graphdb.internal.RelationCategory.PROPERTY) TimeUnit(java.util.concurrent.TimeUnit) JanusGraphAssert.queryProfilerAnnotationIsPresent(org.janusgraph.testutil.JanusGraphAssert.queryProfilerAnnotationIsPresent) ManagementSystem(org.janusgraph.graphdb.database.management.ManagementSystem) ReadMarker(org.janusgraph.diskstorage.log.ReadMarker) Collections(java.util.Collections) CacheVertex(org.janusgraph.graphdb.vertices.CacheVertex) JanusGraphVertex(org.janusgraph.core.JanusGraphVertex) Vertex(org.apache.tinkerpop.gremlin.structure.Vertex) JanusGraphVertex(org.janusgraph.core.JanusGraphVertex) EdgeLabel(org.janusgraph.core.EdgeLabel) JanusGraphIndex(org.janusgraph.core.schema.JanusGraphIndex) PropertyKey(org.janusgraph.core.PropertyKey) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Test(org.junit.jupiter.api.Test)

Example 8 with JanusGraphIndex

use of org.janusgraph.core.schema.JanusGraphIndex in project janusgraph by JanusGraph.

the class JanusGraphTest 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();
    // Add some sensor & friend data
    JanusGraphVertex v = tx.addVertex();
    for (int i = 0; i < 10; i++) {
        v.property("sensor", i, "time", i);
        v.property("name", "v" + i);
        JanusGraphVertex 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", desc), PROPERTY, 4, 1, new boolean[] { false, false }, tx.getPropertyKey("time"), Order.DESC);
    evaluateQuery(v.query().keys("sensor").interval("time", 101, 105).orderBy("time", desc), 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", desc), 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", desc), 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", desc, time);
    mgmt.buildEdgeIndex(friend, "byTime", Direction.OUT, desc, 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);
        JanusGraphVertex o = tx.addVertex();
        v.addEdge("friend", o, "time", i);
    }
    tx.commit();
    // Should not yet be able to enable since not yet registered
    final RelationTypeIndex pindex = mgmt.getRelationIndex(mgmt.getRelationType("sensor"), "byTime");
    final RelationTypeIndex eindex = mgmt.getRelationIndex(mgmt.getRelationType("friend"), "byTime");
    final JanusGraphIndex graphIndex = mgmt.getGraphIndex("bySensorReading");
    assertThrows(IllegalArgumentException.class, () -> mgmt.updateIndex(pindex, SchemaAction.ENABLE_INDEX));
    assertThrows(IllegalArgumentException.class, () -> mgmt.updateIndex(eindex, SchemaAction.ENABLE_INDEX));
    assertThrows(IllegalArgumentException.class, () -> mgmt.updateIndex(graphIndex, SchemaAction.ENABLE_INDEX));
    mgmt.commit();
    ManagementUtil.awaitVertexIndexUpdate(graph, "byTime", "sensor", 10, ChronoUnit.SECONDS);
    ManagementUtil.awaitGraphIndexUpdate(graph, "bySensorReading", 5, ChronoUnit.SECONDS);
    finishSchema();
    // Verify new status
    RelationTypeIndex pindex2 = mgmt.getRelationIndex(mgmt.getRelationType("sensor"), "byTime");
    RelationTypeIndex eindex2 = mgmt.getRelationIndex(mgmt.getRelationType("friend"), "byTime");
    JanusGraphIndex graphIndex2 = mgmt.getGraphIndex("bySensorReading");
    assertEquals(SchemaStatus.REGISTERED, pindex2.getIndexStatus());
    assertEquals(SchemaStatus.REGISTERED, eindex2.getIndexStatus());
    assertEquals(SchemaStatus.REGISTERED, graphIndex2.getIndexStatus(graphIndex2.getFieldKeys()[0]));
    finishSchema();
    // Simply enable without reindex
    eindex2 = mgmt.getRelationIndex(mgmt.getRelationType("friend"), "byTime");
    mgmt.updateIndex(eindex2, SchemaAction.ENABLE_INDEX);
    finishSchema();
    assertTrue(ManagementSystem.awaitRelationIndexStatus(graph, "byTime", "friend").status(SchemaStatus.ENABLED).timeout(10L, ChronoUnit.SECONDS).call().getSucceeded());
    // Reindex the other two
    pindex2 = mgmt.getRelationIndex(mgmt.getRelationType("sensor"), "byTime");
    ScanMetrics reindexSensorByTime = mgmt.updateIndex(pindex2, SchemaAction.REINDEX).get();
    finishSchema();
    graphIndex2 = mgmt.getGraphIndex("bySensorReading");
    ScanMetrics reindexBySensorReading = mgmt.updateIndex(graphIndex2, 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
    pindex2 = mgmt.getRelationIndex(mgmt.getRelationType("sensor"), "byTime");
    eindex2 = mgmt.getRelationIndex(mgmt.getRelationType("friend"), "byTime");
    graphIndex2 = mgmt.getGraphIndex("bySensorReading");
    assertEquals(SchemaStatus.ENABLED, eindex2.getIndexStatus());
    assertEquals(SchemaStatus.ENABLED, pindex2.getIndexStatus());
    assertEquals(SchemaStatus.ENABLED, graphIndex2.getIndexStatus(graphIndex2.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);
        JanusGraphVertex 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", desc), PROPERTY, 4, 1, new boolean[] { true, true }, tx.getPropertyKey("time"), Order.DESC);
    evaluateQuery(v.query().keys("sensor").interval("time", 101, 105).orderBy("time", desc), PROPERTY, 4, 1, new boolean[] { true, true }, tx.getPropertyKey("time"), Order.DESC);
    evaluateQuery(v.query().keys("sensor").interval("time", 201, 205).orderBy("time", desc), 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", desc), 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", desc), 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", desc), 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();
    eindex2 = mgmt.getRelationIndex(mgmt.getRelationType("friend"), "byTime");
    ScanMetrics reindexFriendByTime = mgmt.updateIndex(eindex2, 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", desc), 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", desc), 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", desc), EDGE, 4, 1, new boolean[] { true, true }, tx.getPropertyKey("time"), Order.DESC);
    pindex2 = mgmt.getRelationIndex(mgmt.getRelationType("sensor"), "byTime");
    graphIndex2 = mgmt.getGraphIndex("bySensorReading");
    mgmt.updateIndex(pindex2, SchemaAction.DISABLE_INDEX);
    mgmt.updateIndex(graphIndex2, SchemaAction.DISABLE_INDEX);
    mgmt.commit();
    tx.commit();
    ManagementUtil.awaitVertexIndexUpdate(graph, "byTime", "sensor", 10, ChronoUnit.SECONDS);
    ManagementUtil.awaitGraphIndexUpdate(graph, "bySensorReading", 5, ChronoUnit.SECONDS);
    finishSchema();
    pindex2 = mgmt.getRelationIndex(mgmt.getRelationType("sensor"), "byTime");
    graphIndex2 = mgmt.getGraphIndex("bySensorReading");
    assertEquals(SchemaStatus.DISABLED, pindex2.getIndexStatus());
    assertEquals(SchemaStatus.DISABLED, graphIndex2.getIndexStatus(graphIndex2.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", desc), PROPERTY, 4, 1, new boolean[] { false, false }, tx.getPropertyKey("time"), Order.DESC);
    evaluateQuery(v.query().keys("sensor").interval("time", 101, 105).orderBy("time", desc), PROPERTY, 4, 1, new boolean[] { false, false }, tx.getPropertyKey("time"), Order.DESC);
    evaluateQuery(v.query().keys("sensor").interval("time", 201, 205).orderBy("time", desc), 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", desc), 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", desc), 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", desc), 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();
    pindex2 = mgmt.getRelationIndex(mgmt.getRelationType("sensor"), "byTime");
    graphIndex2 = mgmt.getGraphIndex("bySensorReading");
    ScanMetrics pmetrics = mgmt.updateIndex(pindex2, SchemaAction.REMOVE_INDEX).get();
    ScanMetrics graphIndexMetrics = mgmt.updateIndex(graphIndex2, SchemaAction.REMOVE_INDEX).get();
    finishSchema();
    assertEquals(30, pmetrics.getCustom(IndexRemoveJob.DELETED_RECORDS_COUNT));
    assertEquals(30, graphIndexMetrics.getCustom(IndexRemoveJob.DELETED_RECORDS_COUNT));
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) JanusGraphVertex(org.janusgraph.core.JanusGraphVertex) EdgeLabel(org.janusgraph.core.EdgeLabel) JanusGraphIndex(org.janusgraph.core.schema.JanusGraphIndex) ScanMetrics(org.janusgraph.diskstorage.keycolumnvalue.scan.ScanMetrics) RelationTypeIndex(org.janusgraph.core.schema.RelationTypeIndex) PropertyKey(org.janusgraph.core.PropertyKey) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Test(org.junit.jupiter.api.Test)

Example 9 with JanusGraphIndex

use of org.janusgraph.core.schema.JanusGraphIndex in project janusgraph by JanusGraph.

the class JanusGraphTest method testPropertyTTLTiming.

@Test
@Tag(TestCategory.BRITTLE_TESTS)
@FeatureFlag(feature = JanusGraphFeature.CellTtl)
public void testPropertyTTLTiming() throws Exception {
    PropertyKey name = mgmt.makePropertyKey("name").dataType(String.class).make();
    PropertyKey place = mgmt.makePropertyKey("place").dataType(String.class).make();
    mgmt.setTTL(name, Duration.ofSeconds(42));
    mgmt.setTTL(place, Duration.ofSeconds(1));
    final JanusGraphIndex index1 = mgmt.buildIndex("index1", Vertex.class).addKey(name).buildCompositeIndex();
    final JanusGraphIndex index2 = mgmt.buildIndex("index2", Vertex.class).addKey(name).addKey(place).buildCompositeIndex();
    VertexLabel label1 = mgmt.makeVertexLabel("event").setStatic().make();
    mgmt.setTTL(label1, Duration.ofSeconds(2));
    assertEquals(Duration.ofSeconds(42), mgmt.getTTL(name));
    assertEquals(Duration.ofSeconds(1), mgmt.getTTL(place));
    assertEquals(Duration.ofSeconds(2), mgmt.getTTL(label1));
    mgmt.commit();
    JanusGraphVertex v1 = tx.addVertex(T.label, "event", "name", "some event", "place", "somewhere");
    tx.commit();
    Object id = v1.id();
    v1 = getV(graph, id);
    assertNotNull(v1);
    assertNotEmpty(graph.query().has("name", "some event").has("place", "somewhere").vertices());
    assertNotEmpty(graph.query().has("name", "some event").vertices());
    Thread.sleep(1001);
    graph.tx().rollback();
    // short-lived property expires first
    v1 = getV(graph, id);
    assertNotNull(v1);
    assertEmpty(graph.query().has("name", "some event").has("place", "somewhere").vertices());
    assertNotEmpty(graph.query().has("name", "some event").vertices());
    Thread.sleep(1001);
    graph.tx().rollback();
    // vertex expires before defined TTL of the long-lived property
    assertEmpty(graph.query().has("name", "some event").has("place", "somewhere").vertices());
    assertEmpty(graph.query().has("name", "some event").vertices());
    v1 = getV(graph, id);
    assertNull(v1);
}
Also used : CacheVertex(org.janusgraph.graphdb.vertices.CacheVertex) JanusGraphVertex(org.janusgraph.core.JanusGraphVertex) Vertex(org.apache.tinkerpop.gremlin.structure.Vertex) VertexLabel(org.janusgraph.core.VertexLabel) BaseVertexLabel(org.janusgraph.graphdb.types.system.BaseVertexLabel) JanusGraphVertex(org.janusgraph.core.JanusGraphVertex) JanusGraphIndex(org.janusgraph.core.schema.JanusGraphIndex) PropertyKey(org.janusgraph.core.PropertyKey) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Test(org.junit.jupiter.api.Test) FeatureFlag(org.janusgraph.testutil.FeatureFlag) Tag(org.junit.jupiter.api.Tag)

Example 10 with JanusGraphIndex

use of org.janusgraph.core.schema.JanusGraphIndex in project janusgraph by JanusGraph.

the class JanusGraphTest method testIndexQueryWithLabelsAndContainsIN.

@Test
public void testIndexQueryWithLabelsAndContainsIN() {
    // This test is based on the steps to reproduce #882
    String labelName = "labelName";
    VertexLabel label = mgmt.makeVertexLabel(labelName).make();
    PropertyKey uid = mgmt.makePropertyKey("uid").dataType(String.class).make();
    JanusGraphIndex uidCompositeIndex = mgmt.buildIndex("uidIndex", Vertex.class).indexOnly(label).addKey(uid).unique().buildCompositeIndex();
    mgmt.setConsistency(uidCompositeIndex, ConsistencyModifier.LOCK);
    finishSchema();
    JanusGraphVertex foo = graph.addVertex(labelName);
    JanusGraphVertex bar = graph.addVertex(labelName);
    foo.property("uid", "foo");
    bar.property("uid", "bar");
    graph.tx().commit();
    Iterable<JanusGraphVertex> vertexes = graph.query().has("uid", Contain.IN, ImmutableList.of("foo", "bar")).has(LABEL_NAME, labelName).vertices();
    assertEquals(2, Iterables.size(vertexes));
    for (JanusGraphVertex v : vertexes) {
        assertEquals(labelName, v.vertexLabel().name());
    }
}
Also used : VertexLabel(org.janusgraph.core.VertexLabel) BaseVertexLabel(org.janusgraph.graphdb.types.system.BaseVertexLabel) JanusGraphVertex(org.janusgraph.core.JanusGraphVertex) JanusGraphIndex(org.janusgraph.core.schema.JanusGraphIndex) PropertyKey(org.janusgraph.core.PropertyKey) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Test(org.junit.jupiter.api.Test)

Aggregations

JanusGraphIndex (org.janusgraph.core.schema.JanusGraphIndex)55 PropertyKey (org.janusgraph.core.PropertyKey)42 Test (org.junit.jupiter.api.Test)25 JanusGraphVertex (org.janusgraph.core.JanusGraphVertex)20 Vertex (org.apache.tinkerpop.gremlin.structure.Vertex)19 JanusGraphManagement (org.janusgraph.core.schema.JanusGraphManagement)17 RelationTypeIndex (org.janusgraph.core.schema.RelationTypeIndex)14 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)11 HashMap (java.util.HashMap)10 VertexLabel (org.janusgraph.core.VertexLabel)10 JanusGraph (org.janusgraph.core.JanusGraph)9 JanusGraphException (org.janusgraph.core.JanusGraphException)9 RepeatedIfExceptionsTest (io.github.artsok.RepeatedIfExceptionsTest)8 EdgeLabel (org.janusgraph.core.EdgeLabel)8 BaseVertexLabel (org.janusgraph.graphdb.types.system.BaseVertexLabel)8 BackendException (org.janusgraph.diskstorage.BackendException)7 ScanMetrics (org.janusgraph.diskstorage.keycolumnvalue.scan.ScanMetrics)7 ManagementSystem (org.janusgraph.graphdb.database.management.ManagementSystem)7 CompositeIndexType (org.janusgraph.graphdb.types.CompositeIndexType)7 JanusGraphSchemaVertex (org.janusgraph.graphdb.types.vertices.JanusGraphSchemaVertex)7