Search in sources :

Example 1 with Cardinality

use of org.janusgraph.core.Cardinality 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 2 with Cardinality

use of org.janusgraph.core.Cardinality in project janusgraph by JanusGraph.

the class ElasticSearchIndex method getParameters.

private List<Map<String, Object>> getParameters(KeyInformation.StoreRetriever storeRetriever, List<IndexEntry> entries, boolean deletion, Cardinality... cardinalitiesToSkip) {
    Set<Cardinality> cardinalityToSkipSet = Sets.newHashSet(cardinalitiesToSkip);
    List<Map<String, Object>> result = new ArrayList<>();
    for (IndexEntry entry : entries) {
        KeyInformation info = storeRetriever.get(entry.field);
        if (cardinalityToSkipSet.contains(info.getCardinality())) {
            continue;
        }
        Object jsValue = deletion && info.getCardinality() == Cardinality.SINGLE ? "" : convertToEsType(entry.value, Mapping.getMapping(info));
        result.add(ImmutableMap.of("name", entry.field, "value", jsValue, "cardinality", info.getCardinality().name()));
        if (hasDualStringMapping(info)) {
            result.add(ImmutableMap.of("name", getDualMappingName(entry.field), "value", jsValue, "cardinality", info.getCardinality().name()));
        }
    }
    return result;
}
Also used : Cardinality(org.janusgraph.core.Cardinality) ArrayList(java.util.ArrayList) IndexEntry(org.janusgraph.diskstorage.indexing.IndexEntry) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) KeyInformation(org.janusgraph.diskstorage.indexing.KeyInformation)

Example 3 with Cardinality

use of org.janusgraph.core.Cardinality in project janusgraph by JanusGraph.

the class StandardJanusGraphTx method addProperty.

public JanusGraphVertexProperty addProperty(VertexProperty.Cardinality cardinality, JanusGraphVertex vertex, PropertyKey key, Object value, Long id) {
    if (key.cardinality().convert() != cardinality && cardinality != VertexProperty.Cardinality.single)
        throw new SchemaViolationException("Key is defined for %s cardinality which conflicts with specified: %s", key.cardinality(), cardinality);
    verifyWriteAccess(vertex);
    Preconditions.checkArgument(!(key instanceof ImplicitKey), "Cannot create a property of implicit type: %s", key.name());
    vertex = ((InternalVertex) vertex).it();
    Preconditions.checkNotNull(key);
    checkPropertyConstraintForVertexOrCreatePropertyConstraint(vertex, key);
    final Object normalizedValue = verifyAttribute(key, value);
    Cardinality keyCardinality = key.cardinality();
    // Determine unique indexes
    final List<IndexLockTuple> uniqueIndexTuples = new ArrayList<>();
    for (CompositeIndexType index : TypeUtil.getUniqueIndexes(key)) {
        IndexSerializer.IndexRecords matches = IndexSerializer.indexMatches(vertex, index, key, normalizedValue);
        for (Object[] match : matches.getRecordValues()) uniqueIndexTuples.add(new IndexLockTuple(index, match));
    }
    TransactionLock uniqueLock = getUniquenessLock(vertex, (InternalRelationType) key, normalizedValue);
    // Add locks for unique indexes
    for (IndexLockTuple lockTuple : uniqueIndexTuples) uniqueLock = new CombinerLock(uniqueLock, getLock(lockTuple), times);
    uniqueLock.lock(LOCK_TIMEOUT);
    try {
        // //Check vertex-centric uniqueness -> this doesn't really make sense to check
        // if (config.hasVerifyUniqueness()) {
        // if (cardinality == Cardinality.SINGLE) {
        // if (!Iterables.isEmpty(query(vertex).type(key).properties()))
        // throw new SchemaViolationException("A property with the given key [%s] already exists on the vertex [%s] and the property key is defined as single-valued", key.name(), vertex);
        // }
        // if (cardinality == Cardinality.SET) {
        // if (!Iterables.isEmpty(Iterables.filter(query(vertex).type(key).properties(), new Predicate<JanusGraphVertexProperty>() {
        // @Override
        // public boolean apply(@Nullable JanusGraphVertexProperty janusgraphProperty) {
        // return normalizedValue.equals(janusgraphProperty.value());
        // }
        // })))
        // throw new SchemaViolationException("A property with the given key [%s] and value [%s] already exists on the vertex and the property key is defined as set-valued", key.name(), normalizedValue);
        // }
        // }
        long propId = id == null ? IDManager.getTemporaryRelationID(temporaryIds.nextID()) : id;
        StandardVertexProperty prop = new StandardVertexProperty(propId, key, (InternalVertex) vertex, normalizedValue, ElementLifeCycle.New);
        if (config.hasAssignIDsImmediately() && id == null)
            graph.assignID(prop);
        // Delete properties if the cardinality is restricted
        if (cardinality == VertexProperty.Cardinality.single || cardinality == VertexProperty.Cardinality.set) {
            Consumer<JanusGraphVertexProperty> propertyRemover = JanusGraphVertexProperty.getRemover(cardinality, normalizedValue);
            if ((!config.hasVerifyUniqueness() || ((InternalRelationType) key).getConsistencyModifier() != ConsistencyModifier.LOCK) && !TypeUtil.hasAnyIndex(key) && cardinality == keyCardinality.convert()) {
                // Only delete in-memory so as to not trigger a read from the database which isn't necessary because we will overwrite blindly
                // We need to label the new property as "upsert", so that in case property deletion happens, we not only delete this new
                // in-memory property, but also read from database to delete the old value (if exists)
                ((InternalVertex) vertex).getAddedRelations(p -> p.getType().equals(key)).forEach(p -> propertyRemover.accept((JanusGraphVertexProperty) p));
                prop.setUpsert(true);
            } else {
                ((InternalVertex) vertex).query().types(key).properties().forEach(propertyRemover);
            }
        }
        // Check index uniqueness
        if (config.hasVerifyUniqueness()) {
            // Check all unique indexes
            for (IndexLockTuple lockTuple : uniqueIndexTuples) {
                if (!Iterables.isEmpty(IndexHelper.getQueryResults(lockTuple.getIndex(), lockTuple.getAll(), this)))
                    throw new SchemaViolationException("Adding this property for key [%s] and value [%s] violates a uniqueness constraint [%s]", key.name(), normalizedValue, lockTuple.getIndex());
            }
        }
        connectRelation(prop);
        return prop;
    } finally {
        uniqueLock.unlock();
    }
}
Also used : InternalVertex(org.janusgraph.graphdb.internal.InternalVertex) PredicateCondition(org.janusgraph.graphdb.query.condition.PredicateCondition) CacheVertex(org.janusgraph.graphdb.vertices.CacheVertex) JanusGraphVertex(org.janusgraph.core.JanusGraphVertex) EdgeLabelVertex(org.janusgraph.graphdb.types.vertices.EdgeLabelVertex) StringUtils(org.apache.commons.lang3.StringUtils) AddedRelationsContainer(org.janusgraph.graphdb.transaction.addedrelations.AddedRelationsContainer) CombinerLock(org.janusgraph.graphdb.transaction.lock.CombinerLock) MixedIndexCountQuery(org.janusgraph.core.MixedIndexCountQuery) SystemTypeManager(org.janusgraph.graphdb.types.system.SystemTypeManager) Cardinality(org.janusgraph.core.Cardinality) TypeDefinitionCategory(org.janusgraph.graphdb.types.TypeDefinitionCategory) StandardVertex(org.janusgraph.graphdb.vertices.StandardVertex) InternalRelation(org.janusgraph.graphdb.internal.InternalRelation) Duration(java.time.Duration) Map(java.util.Map) IndexType(org.janusgraph.graphdb.types.IndexType) ConcurrentIndexCache(org.janusgraph.graphdb.transaction.indexcache.ConcurrentIndexCache) TransactionLock(org.janusgraph.graphdb.transaction.lock.TransactionLock) And(org.janusgraph.graphdb.query.condition.And) StandardVertexProperty(org.janusgraph.graphdb.relations.StandardVertexProperty) PropertyKey(org.janusgraph.core.PropertyKey) TimestampProvider(org.janusgraph.diskstorage.util.time.TimestampProvider) StandardJanusGraph(org.janusgraph.graphdb.database.StandardJanusGraph) BaseLabel(org.janusgraph.graphdb.types.system.BaseLabel) Set(java.util.Set) EdgeSerializer(org.janusgraph.graphdb.database.EdgeSerializer) EdgeLabel(org.janusgraph.core.EdgeLabel) JanusGraphVertexProperty(org.janusgraph.core.JanusGraphVertexProperty) EdgeLabelMaker(org.janusgraph.core.schema.EdgeLabelMaker) IndexCache(org.janusgraph.graphdb.transaction.indexcache.IndexCache) ProfiledIterator(org.janusgraph.graphdb.util.ProfiledIterator) IndexQueryBuilder(org.janusgraph.graphdb.query.graph.IndexQueryBuilder) JanusGraphRelation(org.janusgraph.core.JanusGraphRelation) FakeLock(org.janusgraph.graphdb.transaction.lock.FakeLock) LongArrayList(com.carrotsearch.hppc.LongArrayList) Iterables(com.google.common.collect.Iterables) IndexSerializer(org.janusgraph.graphdb.database.IndexSerializer) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) JanusGraphIndexQuery(org.janusgraph.core.JanusGraphIndexQuery) NonBlockingHashMap(org.jctools.maps.NonBlockingHashMap) SchemaInspector(org.janusgraph.core.schema.SchemaInspector) VertexCentricQueryBuilder(org.janusgraph.graphdb.query.vertex.VertexCentricQueryBuilder) Cmp(org.janusgraph.core.attribute.Cmp) ConsistencyModifier(org.janusgraph.core.schema.ConsistencyModifier) EntryList(org.janusgraph.diskstorage.EntryList) JanusGraphException(org.janusgraph.core.JanusGraphException) StandardEdgeLabelMaker(org.janusgraph.graphdb.types.StandardEdgeLabelMaker) EmptySubqueryCache(org.janusgraph.graphdb.transaction.subquerycache.EmptySubqueryCache) Nullable(javax.annotation.Nullable) JanusGraphElement(org.janusgraph.core.JanusGraphElement) IDPool(org.janusgraph.graphdb.database.idassigner.IDPool) QueryUtil(org.janusgraph.graphdb.query.QueryUtil) PropertyKeyVertex(org.janusgraph.graphdb.types.vertices.PropertyKeyVertex) JanusGraphMultiVertexQuery(org.janusgraph.core.JanusGraphMultiVertexQuery) SimpleAddedRelations(org.janusgraph.graphdb.transaction.addedrelations.SimpleAddedRelations) RelationIdentifierUtils(org.janusgraph.graphdb.relations.RelationIdentifierUtils) CompositeIndexType(org.janusgraph.graphdb.types.CompositeIndexType) JanusGraphSchemaCategory(org.janusgraph.graphdb.internal.JanusGraphSchemaCategory) RelationComparator(org.janusgraph.graphdb.relations.RelationComparator) TypeDefinitionDescription(org.janusgraph.graphdb.types.TypeDefinitionDescription) EmptyAddedRelations(org.janusgraph.graphdb.transaction.addedrelations.EmptyAddedRelations) SimpleIndexCache(org.janusgraph.graphdb.transaction.indexcache.SimpleIndexCache) AtomicLong(java.util.concurrent.atomic.AtomicLong) Direction(org.apache.tinkerpop.gremlin.structure.Direction) Retriever(org.janusgraph.util.datastructures.Retriever) InternalVertexLabel(org.janusgraph.graphdb.internal.InternalVertexLabel) ConcurrentAddedRelations(org.janusgraph.graphdb.transaction.addedrelations.ConcurrentAddedRelations) SubqueryIterator(org.janusgraph.graphdb.util.SubqueryIterator) LockTuple(org.janusgraph.graphdb.transaction.lock.LockTuple) Preconditions(com.google.common.base.Preconditions) VertexLabel(org.janusgraph.core.VertexLabel) GraphCentricQuery(org.janusgraph.graphdb.query.graph.GraphCentricQuery) VertexCentricQuery(org.janusgraph.graphdb.query.vertex.VertexCentricQuery) BaseKey(org.janusgraph.graphdb.types.system.BaseKey) TypeDefinitionMap(org.janusgraph.graphdb.types.TypeDefinitionMap) LoggerFactory(org.slf4j.LoggerFactory) VertexLabelMaker(org.janusgraph.core.schema.VertexLabelMaker) QueryExecutor(org.janusgraph.graphdb.query.QueryExecutor) MetricManager(org.janusgraph.util.stats.MetricManager) JanusGraphEdge(org.janusgraph.core.JanusGraphEdge) MixedIndexCountQueryBuilder(org.janusgraph.graphdb.query.graph.MixedIndexCountQueryBuilder) SystemRelationType(org.janusgraph.graphdb.types.system.SystemRelationType) JanusGraphSchemaElement(org.janusgraph.core.schema.JanusGraphSchemaElement) MetricsQueryExecutor(org.janusgraph.graphdb.query.MetricsQueryExecutor) ReentrantTransactionLock(org.janusgraph.graphdb.transaction.lock.ReentrantTransactionLock) AttributeHandler(org.janusgraph.graphdb.database.serialize.AttributeHandler) TypeInspector(org.janusgraph.graphdb.types.TypeInspector) Multiplicity(org.janusgraph.core.Multiplicity) RelationType(org.janusgraph.core.RelationType) Property(org.apache.tinkerpop.gremlin.structure.Property) ElementLifeCycle(org.janusgraph.graphdb.internal.ElementLifeCycle) SchemaViolationException(org.janusgraph.core.SchemaViolationException) VertexCache(org.janusgraph.graphdb.transaction.vertexcache.VertexCache) ImmutableMap(com.google.common.collect.ImmutableMap) PropertyKeyMaker(org.janusgraph.core.schema.PropertyKeyMaker) Collection(java.util.Collection) SliceQuery(org.janusgraph.diskstorage.keycolumnvalue.SliceQuery) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Connection(org.janusgraph.core.Connection) JanusGraphSchemaVertex(org.janusgraph.graphdb.types.vertices.JanusGraphSchemaVertex) StandardPropertyKeyMaker(org.janusgraph.graphdb.types.StandardPropertyKeyMaker) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) List(java.util.List) RelationIdentifier(org.janusgraph.graphdb.relations.RelationIdentifier) ImplicitKey(org.janusgraph.graphdb.types.system.ImplicitKey) GraphCentricQueryBuilder(org.janusgraph.graphdb.query.graph.GraphCentricQueryBuilder) InternalRelationType(org.janusgraph.graphdb.internal.InternalRelationType) IndexHelper(org.janusgraph.graphdb.util.IndexHelper) ConditionUtil(org.janusgraph.graphdb.query.condition.ConditionUtil) JointIndexQuery(org.janusgraph.graphdb.query.graph.JointIndexQuery) Condition(org.janusgraph.graphdb.query.condition.Condition) VertexCentricEdgeIterable(org.janusgraph.graphdb.util.VertexCentricEdgeIterable) IndexTransaction(org.janusgraph.diskstorage.indexing.IndexTransaction) BackendTransaction(org.janusgraph.diskstorage.BackendTransaction) IDManager(org.janusgraph.graphdb.idmanagement.IDManager) VertexLabelVertex(org.janusgraph.graphdb.types.VertexLabelVertex) PreloadedVertex(org.janusgraph.graphdb.vertices.PreloadedVertex) HashMap(java.util.HashMap) Function(java.util.function.Function) StandardEdge(org.janusgraph.graphdb.relations.StandardEdge) ConcurrentMap(java.util.concurrent.ConcurrentMap) VertexProperty(org.apache.tinkerpop.gremlin.structure.VertexProperty) StandardVertexLabelMaker(org.janusgraph.graphdb.types.StandardVertexLabelMaker) IndexLockTuple(org.janusgraph.graphdb.transaction.lock.IndexLockTuple) MultiVertexCentricQueryBuilder(org.janusgraph.graphdb.query.vertex.MultiVertexCentricQueryBuilder) RelationCategory(org.janusgraph.graphdb.internal.RelationCategory) IndexSelectionStrategy(org.janusgraph.graphdb.query.index.IndexSelectionStrategy) NoSuchElementException(java.util.NoSuchElementException) JanusGraphBlueprintsTransaction(org.janusgraph.graphdb.tinkerpop.JanusGraphBlueprintsTransaction) BackendException(org.janusgraph.diskstorage.BackendException) TypeUtil(org.janusgraph.graphdb.types.TypeUtil) EmptyVertexCache(org.janusgraph.graphdb.transaction.vertexcache.EmptyVertexCache) QueryProfiler(org.janusgraph.graphdb.query.profile.QueryProfiler) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) Query(org.janusgraph.graphdb.query.Query) BaseVertexLabel(org.janusgraph.graphdb.types.system.BaseVertexLabel) SubqueryCache(org.janusgraph.graphdb.transaction.subquerycache.SubqueryCache) ElementCategory(org.janusgraph.graphdb.internal.ElementCategory) Consumer(java.util.function.Consumer) EmptyIndexCache(org.janusgraph.graphdb.transaction.indexcache.EmptyIndexCache) GuavaVertexCache(org.janusgraph.graphdb.transaction.vertexcache.GuavaVertexCache) Collections(java.util.Collections) GuavaSubqueryCache(org.janusgraph.graphdb.transaction.subquerycache.GuavaSubqueryCache) ReadOnlyTransactionException(org.janusgraph.core.ReadOnlyTransactionException) Cardinality(org.janusgraph.core.Cardinality) IndexSerializer(org.janusgraph.graphdb.database.IndexSerializer) LongArrayList(com.carrotsearch.hppc.LongArrayList) ArrayList(java.util.ArrayList) StandardVertexProperty(org.janusgraph.graphdb.relations.StandardVertexProperty) IndexLockTuple(org.janusgraph.graphdb.transaction.lock.IndexLockTuple) JanusGraphVertexProperty(org.janusgraph.core.JanusGraphVertexProperty) CombinerLock(org.janusgraph.graphdb.transaction.lock.CombinerLock) CompositeIndexType(org.janusgraph.graphdb.types.CompositeIndexType) SchemaViolationException(org.janusgraph.core.SchemaViolationException) ImplicitKey(org.janusgraph.graphdb.types.system.ImplicitKey) TransactionLock(org.janusgraph.graphdb.transaction.lock.TransactionLock) ReentrantTransactionLock(org.janusgraph.graphdb.transaction.lock.ReentrantTransactionLock)

Example 4 with Cardinality

use of org.janusgraph.core.Cardinality in project atlas by apache.

the class AtlasJanusGraphManagement method makePropertyKey.

@Override
public AtlasPropertyKey makePropertyKey(String propertyName, Class propertyClass, AtlasCardinality cardinality) {
    if (cardinality.isMany()) {
        newMultProperties.add(propertyName);
    }
    PropertyKeyMaker propertyKeyBuilder = management.makePropertyKey(propertyName).dataType(propertyClass);
    if (cardinality != null) {
        Cardinality janusCardinality = AtlasJanusObjectFactory.createCardinality(cardinality);
        propertyKeyBuilder.cardinality(janusCardinality);
    }
    PropertyKey propertyKey = propertyKeyBuilder.make();
    return GraphDbObjectFactory.createPropertyKey(propertyKey);
}
Also used : PropertyKeyMaker(org.janusgraph.core.schema.PropertyKeyMaker) Cardinality(org.janusgraph.core.Cardinality) AtlasCardinality(org.apache.atlas.repository.graphdb.AtlasCardinality) AtlasPropertyKey(org.apache.atlas.repository.graphdb.AtlasPropertyKey) PropertyKey(org.janusgraph.core.PropertyKey)

Example 5 with Cardinality

use of org.janusgraph.core.Cardinality in project janusgraph by JanusGraph.

the class ManagementSystem method createCompositeIndex.

private JanusGraphIndex createCompositeIndex(String indexName, ElementCategory elementCategory, boolean unique, JanusGraphSchemaType constraint, PropertyKey... keys) {
    checkIndexName(indexName);
    Preconditions.checkArgument(keys != null && keys.length > 0, "Need to provide keys to index [%s]", indexName);
    Preconditions.checkArgument(!unique || elementCategory == ElementCategory.VERTEX, "Unique indexes can only be created on vertices [%s]", indexName);
    boolean allSingleKeys = true;
    boolean oneNewKey = false;
    for (PropertyKey key : keys) {
        Preconditions.checkArgument(key != null && key instanceof PropertyKeyVertex, "Need to provide valid keys: %s", key);
        if (key.cardinality() != Cardinality.SINGLE)
            allSingleKeys = false;
        if (key.isNew())
            oneNewKey = true;
        else
            updatedTypes.add((PropertyKeyVertex) key);
    }
    Cardinality indexCardinality;
    if (unique)
        indexCardinality = Cardinality.SINGLE;
    else
        indexCardinality = (allSingleKeys ? Cardinality.SET : Cardinality.LIST);
    boolean canIndexBeEnabled = oneNewKey || (constraint != null && constraint.isNew());
    TypeDefinitionMap def = new TypeDefinitionMap();
    def.setValue(TypeDefinitionCategory.INTERNAL_INDEX, true);
    def.setValue(TypeDefinitionCategory.ELEMENT_CATEGORY, elementCategory);
    def.setValue(TypeDefinitionCategory.BACKING_INDEX, Token.INTERNAL_INDEX_NAME);
    def.setValue(TypeDefinitionCategory.INDEXSTORE_NAME, indexName);
    def.setValue(TypeDefinitionCategory.INDEX_CARDINALITY, indexCardinality);
    def.setValue(TypeDefinitionCategory.STATUS, canIndexBeEnabled ? SchemaStatus.ENABLED : SchemaStatus.INSTALLED);
    JanusGraphSchemaVertex indexVertex = transaction.makeSchemaVertex(JanusGraphSchemaCategory.GRAPHINDEX, indexName, def);
    for (int i = 0; i < keys.length; i++) {
        Parameter[] paras = { ParameterType.INDEX_POSITION.getParameter(i) };
        addSchemaEdge(indexVertex, keys[i], TypeDefinitionCategory.INDEX_FIELD, paras);
    }
    Preconditions.checkArgument(constraint == null || (elementCategory.isValidConstraint(constraint) && constraint instanceof JanusGraphSchemaVertex));
    if (constraint != null) {
        addSchemaEdge(indexVertex, (JanusGraphSchemaVertex) constraint, TypeDefinitionCategory.INDEX_SCHEMA_CONSTRAINT, null);
    }
    updateSchemaVertex(indexVertex);
    JanusGraphIndexWrapper index = new JanusGraphIndexWrapper(indexVertex.asIndexType());
    if (!canIndexBeEnabled)
        updateIndex(index, SchemaAction.REGISTER_INDEX);
    return index;
}
Also used : Cardinality(org.janusgraph.core.Cardinality) JanusGraphSchemaVertex(org.janusgraph.graphdb.types.vertices.JanusGraphSchemaVertex) Parameter(org.janusgraph.core.schema.Parameter) PropertyKeyVertex(org.janusgraph.graphdb.types.vertices.PropertyKeyVertex) TypeDefinitionMap(org.janusgraph.graphdb.types.TypeDefinitionMap) PropertyKey(org.janusgraph.core.PropertyKey)

Aggregations

Cardinality (org.janusgraph.core.Cardinality)6 PropertyKey (org.janusgraph.core.PropertyKey)5 ImmutableMap (com.google.common.collect.ImmutableMap)4 ArrayList (java.util.ArrayList)4 HashMap (java.util.HashMap)4 Map (java.util.Map)4 Preconditions (com.google.common.base.Preconditions)3 Iterables (com.google.common.collect.Iterables)3 Sets (com.google.common.collect.Sets)3 Duration (java.time.Duration)3 Collection (java.util.Collection)3 Collections (java.util.Collections)3 Iterator (java.util.Iterator)3 List (java.util.List)3 Set (java.util.Set)3 Supplier (java.util.function.Supplier)3 Collectors (java.util.stream.Collectors)3 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 Direction (org.apache.tinkerpop.gremlin.structure.Direction)2 Property (org.apache.tinkerpop.gremlin.structure.Property)2