Search in sources :

Example 11 with JanusGraphManagement

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

the class AbstractIndexManagementIT method testRemoveRelationIndex.

@Test
public void testRemoveRelationIndex() throws InterruptedException, BackendException, ExecutionException {
    tx.commit();
    mgmt.commit();
    // Load the "Graph of the Gods" sample data
    GraphOfTheGodsFactory.loadWithoutMixedIndex(graph, true);
    // Disable the "battlesByTime" index
    JanusGraphManagement m = graph.openManagement();
    RelationType battled = m.getRelationType("battled");
    RelationTypeIndex battlesByTime = m.getRelationIndex(battled, "battlesByTime");
    m.updateIndex(battlesByTime, SchemaAction.DISABLE_INDEX);
    m.commit();
    graph.tx().commit();
    // Block until the SchemaStatus transitions to DISABLED
    assertTrue(ManagementSystem.awaitRelationIndexStatus(graph, "battlesByTime", "battled").status(SchemaStatus.DISABLED).call().getSucceeded());
    // Remove index
    MapReduceIndexManagement mri = new MapReduceIndexManagement(graph);
    m = graph.openManagement();
    battled = m.getRelationType("battled");
    battlesByTime = m.getRelationIndex(battled, "battlesByTime");
    ScanMetrics metrics = mri.updateIndex(battlesByTime, SchemaAction.REMOVE_INDEX).get();
    assertEquals(6, metrics.getCustom(IndexRemoveJob.DELETED_RECORDS_COUNT));
}
Also used : JanusGraphManagement(org.janusgraph.core.schema.JanusGraphManagement) RelationType(org.janusgraph.core.RelationType) ScanMetrics(org.janusgraph.diskstorage.keycolumnvalue.scan.ScanMetrics) RelationTypeIndex(org.janusgraph.core.schema.RelationTypeIndex) Test(org.junit.Test) JanusGraphBaseTest(org.janusgraph.graphdb.JanusGraphBaseTest)

Example 12 with JanusGraphManagement

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

the class AbstractJanusGraphProvider method createIndices.

private void createIndices(final JanusGraph g, final LoadGraphWith.GraphData graphData) {
    JanusGraphManagement management = g.openManagement();
    if (graphData.equals(LoadGraphWith.GraphData.GRATEFUL)) {
        VertexLabel artist = management.makeVertexLabel("artist").make();
        VertexLabel song = management.makeVertexLabel("song").make();
        PropertyKey name = management.makePropertyKey("name").cardinality(Cardinality.LIST).dataType(String.class).make();
        PropertyKey songType = management.makePropertyKey("songType").cardinality(Cardinality.LIST).dataType(String.class).make();
        PropertyKey performances = management.makePropertyKey("performances").cardinality(Cardinality.LIST).dataType(Integer.class).make();
        management.buildIndex("artistByName", Vertex.class).addKey(name).indexOnly(artist).buildCompositeIndex();
        management.buildIndex("songByName", Vertex.class).addKey(name).indexOnly(song).buildCompositeIndex();
        management.buildIndex("songByType", Vertex.class).addKey(songType).indexOnly(song).buildCompositeIndex();
        management.buildIndex("songByPerformances", Vertex.class).addKey(performances).indexOnly(song).buildCompositeIndex();
    } else if (graphData.equals(LoadGraphWith.GraphData.MODERN)) {
        VertexLabel person = management.makeVertexLabel("person").make();
        VertexLabel software = management.makeVertexLabel("software").make();
        PropertyKey name = management.makePropertyKey("name").cardinality(Cardinality.LIST).dataType(String.class).make();
        PropertyKey lang = management.makePropertyKey("lang").cardinality(Cardinality.LIST).dataType(String.class).make();
        PropertyKey age = management.makePropertyKey("age").cardinality(Cardinality.LIST).dataType(Integer.class).make();
        management.buildIndex("personByName", Vertex.class).addKey(name).indexOnly(person).buildCompositeIndex();
        management.buildIndex("softwareByName", Vertex.class).addKey(name).indexOnly(software).buildCompositeIndex();
        management.buildIndex("personByAge", Vertex.class).addKey(age).indexOnly(person).buildCompositeIndex();
        management.buildIndex("softwareByLang", Vertex.class).addKey(lang).indexOnly(software).buildCompositeIndex();
    } else if (graphData.equals(LoadGraphWith.GraphData.CLASSIC)) {
        PropertyKey name = management.makePropertyKey("name").cardinality(Cardinality.LIST).dataType(String.class).make();
        PropertyKey lang = management.makePropertyKey("lang").cardinality(Cardinality.LIST).dataType(String.class).make();
        PropertyKey age = management.makePropertyKey("age").cardinality(Cardinality.LIST).dataType(Integer.class).make();
        management.buildIndex("byName", Vertex.class).addKey(name).buildCompositeIndex();
        management.buildIndex("byAge", Vertex.class).addKey(age).buildCompositeIndex();
        management.buildIndex("byLang", Vertex.class).addKey(lang).buildCompositeIndex();
    } else {
    // TODO: add CREW work here.
    // TODO: add meta_property indices when meta_property graph is provided
    // throw new RuntimeException("Could not load graph with " + graphData);
    }
    management.commit();
}
Also used : JanusGraphManagement(org.janusgraph.core.schema.JanusGraphManagement) CacheVertex(org.janusgraph.graphdb.vertices.CacheVertex) EdgeLabelVertex(org.janusgraph.graphdb.types.vertices.EdgeLabelVertex) VertexLabelVertex(org.janusgraph.graphdb.types.VertexLabelVertex) PreloadedVertex(org.janusgraph.graphdb.vertices.PreloadedVertex) StandardVertex(org.janusgraph.graphdb.vertices.StandardVertex) PropertyKeyVertex(org.janusgraph.graphdb.types.vertices.PropertyKeyVertex) JanusGraphSchemaVertex(org.janusgraph.graphdb.types.vertices.JanusGraphSchemaVertex) Vertex(org.apache.tinkerpop.gremlin.structure.Vertex) EmptyVertex(org.janusgraph.graphdb.types.system.EmptyVertex) VertexLabel(org.janusgraph.core.VertexLabel) PropertyKey(org.janusgraph.core.PropertyKey)

Example 13 with JanusGraphManagement

use of org.janusgraph.core.schema.JanusGraphManagement 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 = management.makePropertyKey(propertyKeyName).dataType(dataType).make();
        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();
                management.updateIndex(index, ENABLE_INDEX).get();
            } else if (index.getIndexStatus(key) == REGISTERED) {
                management.updateIndex(index, ENABLE_INDEX).get();
            }
        } catch (InterruptedException | ExecutionException e) {
            log.warn("Failed to create index {} for ConfigurationManagementGraph with exception: {}", indexName, e.toString());
            management.rollback();
            graph.tx().rollback();
        }
        management.commit();
        graph.tx().commit();
    }
}
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 14 with JanusGraphManagement

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

the class FulgoraGraphComputer method submit.

@Override
public Future<ComputerResult> submit() {
    if (executed)
        throw Exceptions.computerHasAlreadyBeenSubmittedAVertexProgram();
    else
        executed = true;
    // it is not possible execute a computer if it has no vertex program nor map-reducers
    if (null == vertexProgram && mapReduces.isEmpty())
        throw GraphComputer.Exceptions.computerHasNoVertexProgramNorMapReducers();
    // it is possible to run map-reducers without a vertex program
    if (null != vertexProgram) {
        GraphComputerHelper.validateProgramOnComputer(this, vertexProgram);
        this.mapReduces.addAll(this.vertexProgram.getMapReducers());
    }
    // if the user didn't set desired persistence/resultgraph, then get from vertex program or else, no persistence
    this.persistMode = GraphComputerHelper.getPersistState(Optional.ofNullable(this.vertexProgram), Optional.ofNullable(this.persistMode));
    this.resultGraphMode = GraphComputerHelper.getResultGraphState(Optional.ofNullable(this.vertexProgram), Optional.ofNullable(this.resultGraphMode));
    // determine the legality persistence and result graph options
    if (!this.features().supportsResultGraphPersistCombination(this.resultGraphMode, this.persistMode))
        throw GraphComputer.Exceptions.resultGraphPersistCombinationNotSupported(this.resultGraphMode, this.persistMode);
    // ensure requested workers are not larger than supported workers
    if (this.numThreads > this.features().getMaxWorkers())
        throw GraphComputer.Exceptions.computerRequiresMoreWorkersThanSupported(this.numThreads, this.features().getMaxWorkers());
    memory = new FulgoraMemory(vertexProgram, mapReduces);
    return CompletableFuture.supplyAsync(() -> {
        final long time = System.currentTimeMillis();
        if (null != vertexProgram) {
            // ##### Execute vertex program
            vertexMemory = new FulgoraVertexMemory(expectedNumVertices, graph.getIDManager(), vertexProgram);
            // execute the vertex program
            vertexProgram.setup(memory);
            try (VertexProgramScanJob.Executor job = VertexProgramScanJob.getVertexProgramScanJob(graph, memory, vertexMemory, vertexProgram)) {
                for (int iteration = 1; ; iteration++) {
                    memory.completeSubRound();
                    vertexMemory.nextIteration(vertexProgram.getMessageScopes(memory));
                    jobId = name + "#" + iteration;
                    StandardScanner.Builder scanBuilder = graph.getBackend().buildEdgeScanJob();
                    scanBuilder.setJobId(jobId);
                    scanBuilder.setNumProcessingThreads(numThreads);
                    scanBuilder.setWorkBlockSize(readBatchSize);
                    scanBuilder.setJob(job);
                    PartitionedVertexProgramExecutor programExecutor = new PartitionedVertexProgramExecutor(graph, memory, vertexMemory, vertexProgram);
                    try {
                        // Iterates over all vertices and computes the vertex program on all non-partitioned vertices. For partitioned ones, the data is aggregated
                        ScanMetrics jobResult = scanBuilder.execute().get();
                        long failures = jobResult.get(ScanMetrics.Metric.FAILURE);
                        if (failures > 0) {
                            throw new JanusGraphException("Failed to process [" + failures + "] vertices in vertex program iteration [" + iteration + "]. Computer is aborting.");
                        }
                        // Runs the vertex program on all aggregated, partitioned vertices.
                        programExecutor.run(numThreads, jobResult);
                        failures = jobResult.getCustom(PartitionedVertexProgramExecutor.PARTITION_VERTEX_POSTFAIL);
                        if (failures > 0) {
                            throw new JanusGraphException("Failed to process [" + failures + "] partitioned vertices in vertex program iteration [" + iteration + "]. Computer is aborting.");
                        }
                    } catch (Exception e) {
                        throw new JanusGraphException(e);
                    }
                    vertexMemory.completeIteration();
                    memory.completeSubRound();
                    try {
                        if (this.vertexProgram.terminate(this.memory)) {
                            break;
                        }
                    } finally {
                        memory.incrIteration();
                    }
                }
            }
        }
        // ##### Execute map-reduce jobs
        // Collect map jobs
        Map<MapReduce, FulgoraMapEmitter> mapJobs = new HashMap<>(mapReduces.size());
        for (MapReduce mapReduce : mapReduces) {
            if (mapReduce.doStage(MapReduce.Stage.MAP)) {
                FulgoraMapEmitter mapEmitter = new FulgoraMapEmitter<>(mapReduce.doStage(MapReduce.Stage.REDUCE));
                mapJobs.put(mapReduce, mapEmitter);
            }
        }
        // Execute map jobs
        jobId = name + "#map";
        try (VertexMapJob.Executor job = VertexMapJob.getVertexMapJob(graph, vertexMemory, mapJobs)) {
            StandardScanner.Builder scanBuilder = graph.getBackend().buildEdgeScanJob();
            scanBuilder.setJobId(jobId);
            scanBuilder.setNumProcessingThreads(numThreads);
            scanBuilder.setWorkBlockSize(readBatchSize);
            scanBuilder.setJob(job);
            try {
                ScanMetrics jobResult = scanBuilder.execute().get();
                long failures = jobResult.get(ScanMetrics.Metric.FAILURE);
                if (failures > 0) {
                    throw new JanusGraphException("Failed to process [" + failures + "] vertices in map phase. Computer is aborting.");
                }
                failures = jobResult.getCustom(VertexMapJob.MAP_JOB_FAILURE);
                if (failures > 0) {
                    throw new JanusGraphException("Failed to process [" + failures + "] individual map jobs. Computer is aborting.");
                }
            } catch (Exception e) {
                throw new JanusGraphException(e);
            }
            // Execute reduce phase and add to memory
            for (Map.Entry<MapReduce, FulgoraMapEmitter> mapJob : mapJobs.entrySet()) {
                FulgoraMapEmitter<?, ?> mapEmitter = mapJob.getValue();
                MapReduce mapReduce = mapJob.getKey();
                // sort results if a map output sort is defined
                mapEmitter.complete(mapReduce);
                if (mapReduce.doStage(MapReduce.Stage.REDUCE)) {
                    final FulgoraReduceEmitter<?, ?> reduceEmitter = new FulgoraReduceEmitter<>();
                    try (WorkerPool workers = new WorkerPool(numThreads)) {
                        workers.submit(() -> mapReduce.workerStart(MapReduce.Stage.REDUCE));
                        for (final Map.Entry queueEntry : mapEmitter.reduceMap.entrySet()) {
                            if (null == queueEntry)
                                break;
                            workers.submit(() -> mapReduce.reduce(queueEntry.getKey(), ((Iterable) queueEntry.getValue()).iterator(), reduceEmitter));
                        }
                        workers.submit(() -> mapReduce.workerEnd(MapReduce.Stage.REDUCE));
                    } catch (Exception e) {
                        throw new JanusGraphException("Exception while executing reduce phase", e);
                    }
                    // mapEmitter.reduceMap.entrySet().parallelStream().forEach(entry -> mapReduce.reduce(entry.getKey(), entry.getValue().iterator(), reduceEmitter));
                    // sort results if a reduce output sort is defined
                    reduceEmitter.complete(mapReduce);
                    mapReduce.addResultToMemory(this.memory, reduceEmitter.reduceQueue.iterator());
                } else {
                    mapReduce.addResultToMemory(this.memory, mapEmitter.mapQueue.iterator());
                }
            }
        }
        memory.attachReferenceElements(graph);
        // #### Write mutated properties back into graph
        Graph resultgraph = graph;
        if (persistMode == Persist.NOTHING && resultGraphMode == ResultGraph.NEW) {
            resultgraph = EmptyGraph.instance();
        } else if (persistMode != Persist.NOTHING && vertexProgram != null && !vertexProgram.getVertexComputeKeys().isEmpty()) {
            // First, create property keys in graph if they don't already exist
            JanusGraphManagement management = graph.openManagement();
            try {
                for (VertexComputeKey key : vertexProgram.getVertexComputeKeys()) {
                    if (!management.containsPropertyKey(key.getKey()))
                        log.warn("Property key [{}] is not part of the schema and will be created. It is advised to initialize all keys.", key.getKey());
                    management.getOrCreatePropertyKey(key.getKey());
                }
                management.commit();
            } finally {
                if (management != null && management.isOpen())
                    management.rollback();
            }
            // TODO: Filter based on VertexProgram
            Map<Long, Map<String, Object>> mutatedProperties = Maps.transformValues(vertexMemory.getMutableVertexProperties(), new Function<Map<String, Object>, Map<String, Object>>() {

                @Nullable
                @Override
                public Map<String, Object> apply(final Map<String, Object> o) {
                    return Maps.filterKeys(o, s -> !VertexProgramHelper.isTransientVertexComputeKey(s, vertexProgram.getVertexComputeKeys()));
                }
            });
            if (resultGraphMode == ResultGraph.ORIGINAL) {
                AtomicInteger failures = new AtomicInteger(0);
                try (WorkerPool workers = new WorkerPool(numThreads)) {
                    List<Map.Entry<Long, Map<String, Object>>> subset = new ArrayList<>(writeBatchSize / vertexProgram.getVertexComputeKeys().size());
                    int currentSize = 0;
                    for (Map.Entry<Long, Map<String, Object>> entry : mutatedProperties.entrySet()) {
                        subset.add(entry);
                        currentSize += entry.getValue().size();
                        if (currentSize >= writeBatchSize) {
                            workers.submit(new VertexPropertyWriter(subset, failures));
                            subset = new ArrayList<>(subset.size());
                            currentSize = 0;
                        }
                    }
                    if (!subset.isEmpty())
                        workers.submit(new VertexPropertyWriter(subset, failures));
                } catch (Exception e) {
                    throw new JanusGraphException("Exception while attempting to persist result into graph", e);
                }
                if (failures.get() > 0)
                    throw new JanusGraphException("Could not persist program results to graph. Check log for details.");
            } else if (resultGraphMode == ResultGraph.NEW) {
                resultgraph = graph.newTransaction();
                for (Map.Entry<Long, Map<String, Object>> vertexProperty : mutatedProperties.entrySet()) {
                    Vertex v = resultgraph.vertices(vertexProperty.getKey()).next();
                    for (Map.Entry<String, Object> prop : vertexProperty.getValue().entrySet()) {
                        if (prop.getValue() instanceof List) {
                            ((List) prop.getValue()).forEach(value -> v.property(VertexProperty.Cardinality.list, prop.getKey(), value));
                        } else {
                            v.property(VertexProperty.Cardinality.single, prop.getKey(), prop.getValue());
                        }
                    }
                }
            }
        }
        // update runtime and return the newly computed graph
        this.memory.setRuntime(System.currentTimeMillis() - time);
        this.memory.complete();
        return new DefaultComputerResult(resultgraph, this.memory);
    });
}
Also used : JanusGraphManagement(org.janusgraph.core.schema.JanusGraphManagement) Vertex(org.apache.tinkerpop.gremlin.structure.Vertex) HashMap(java.util.HashMap) JanusGraphException(org.janusgraph.core.JanusGraphException) ArrayList(java.util.ArrayList) ScanMetrics(org.janusgraph.diskstorage.keycolumnvalue.scan.ScanMetrics) MapReduce(org.apache.tinkerpop.gremlin.process.computer.MapReduce) Function(com.google.common.base.Function) ArrayList(java.util.ArrayList) List(java.util.List) JanusGraphException(org.janusgraph.core.JanusGraphException) WorkerPool(org.janusgraph.graphdb.util.WorkerPool) Graph(org.apache.tinkerpop.gremlin.structure.Graph) StandardJanusGraph(org.janusgraph.graphdb.database.StandardJanusGraph) EmptyGraph(org.apache.tinkerpop.gremlin.structure.util.empty.EmptyGraph) StandardScanner(org.janusgraph.diskstorage.keycolumnvalue.scan.StandardScanner) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DefaultComputerResult(org.apache.tinkerpop.gremlin.process.computer.util.DefaultComputerResult) VertexComputeKey(org.apache.tinkerpop.gremlin.process.computer.VertexComputeKey) HashMap(java.util.HashMap) Map(java.util.Map)

Example 15 with JanusGraphManagement

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

the class ManagementUtil method awaitIndexUpdate.

private static void awaitIndexUpdate(JanusGraph g, String indexName, String relationTypeName, long time, TemporalUnit unit) {
    Preconditions.checkArgument(g != null && g.isOpen(), "Need to provide valid, open graph instance");
    Preconditions.checkArgument(time > 0 && unit != null, "Need to provide valid time interval");
    Preconditions.checkArgument(StringUtils.isNotBlank(indexName), "Need to provide an index name");
    StandardJanusGraph graph = (StandardJanusGraph) g;
    TimestampProvider times = graph.getConfiguration().getTimestampProvider();
    Instant end = times.getTime().plus(Duration.of(time, unit));
    boolean isStable = false;
    while (times.getTime().isBefore(end)) {
        JanusGraphManagement management = graph.openManagement();
        try {
            if (StringUtils.isNotBlank(relationTypeName)) {
                RelationTypeIndex idx = management.getRelationIndex(management.getRelationType(relationTypeName), indexName);
                Preconditions.checkArgument(idx != null, "Index could not be found: %s @ %s", indexName, relationTypeName);
                isStable = idx.getIndexStatus().isStable();
            } else {
                JanusGraphIndex idx = management.getGraphIndex(indexName);
                Preconditions.checkArgument(idx != null, "Index could not be found: %s", indexName);
                isStable = true;
                for (PropertyKey key : idx.getFieldKeys()) {
                    if (!idx.getIndexStatus(key).isStable())
                        isStable = false;
                }
            }
        } finally {
            management.rollback();
        }
        if (isStable)
            break;
        try {
            times.sleepFor(Duration.ofMillis(500));
        } catch (InterruptedException ignored) {
        }
    }
    if (!isStable)
        throw new JanusGraphException("Index did not stabilize within the given amount of time. For sufficiently long " + "wait periods this is most likely caused by a failed/incorrectly shut down JanusGraph instance or a lingering transaction.");
}
Also used : JanusGraphManagement(org.janusgraph.core.schema.JanusGraphManagement) TimestampProvider(org.janusgraph.diskstorage.util.time.TimestampProvider) Instant(java.time.Instant) JanusGraphException(org.janusgraph.core.JanusGraphException) JanusGraphIndex(org.janusgraph.core.schema.JanusGraphIndex) RelationTypeIndex(org.janusgraph.core.schema.RelationTypeIndex) PropertyKey(org.janusgraph.core.PropertyKey) StandardJanusGraph(org.janusgraph.graphdb.database.StandardJanusGraph)

Aggregations

JanusGraphManagement (org.janusgraph.core.schema.JanusGraphManagement)27 PropertyKey (org.janusgraph.core.PropertyKey)10 Test (org.junit.Test)10 JanusGraphIndex (org.janusgraph.core.schema.JanusGraphIndex)9 StandardJanusGraph (org.janusgraph.graphdb.database.StandardJanusGraph)8 JanusGraphBaseTest (org.janusgraph.graphdb.JanusGraphBaseTest)7 Vertex (org.apache.tinkerpop.gremlin.structure.Vertex)6 JanusGraph (org.janusgraph.core.JanusGraph)5 EdgeLabel (org.janusgraph.core.EdgeLabel)4 ScanMetrics (org.janusgraph.diskstorage.keycolumnvalue.scan.ScanMetrics)4 ResourceBundle (java.util.ResourceBundle)3 JanusGraphVertex (org.janusgraph.core.JanusGraphVertex)3 RelationType (org.janusgraph.core.RelationType)3 RelationTypeIndex (org.janusgraph.core.schema.RelationTypeIndex)3 HashMap (java.util.HashMap)2 Map (java.util.Map)2 GraphTraversalSource (org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource)2 JanusGraphException (org.janusgraph.core.JanusGraphException)2 Geoshape (org.janusgraph.core.attribute.Geoshape)2 SchemaStatus (org.janusgraph.core.schema.SchemaStatus)2