org.neo4j.procedure.Mode Java Examples

The following examples show how to use org.neo4j.procedure.Mode. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Init.java    From neo4j-versioner-core with Apache License 2.0 6 votes vote down vote up
@Procedure(value = "graph.versioner.init", mode = Mode.WRITE)
@Description("graph.versioner.init(entityLabel, {key:value,...}, {key:value,...}, additionalLabel, date) - Create an Entity node with an optional initial State.")
public Stream<NodeOutput> init(
        @Name("entityLabel") String entityLabel,
        @Name(value = "entityProps", defaultValue = "{}") Map<String, Object> entityProps,
        @Name(value = "stateProps", defaultValue = "{}") Map<String, Object> stateProps,
        @Name(value = "additionalLabel", defaultValue = "") String additionalLabel,
        @Name(value = "date", defaultValue = "null") LocalDateTime date) {

    Node entity = createNode(entityProps, singletonList(entityLabel));

    Node state = createNode(stateProps, getStateLabels(additionalLabel));

    connectWithCurrentRelationship(entity, state, date);

    log.info(LOGGER_TAG + "Created a new Entity with label {} and id {}", entityLabel, entity.getId());

    createRNodeAndAssociateTo(entity);

    return streamOfNodes(entity);
}
 
Example #2
Source File: RelationshipProcedure.java    From neo4j-versioner-core with Apache License 2.0 6 votes vote down vote up
@Procedure(value = "graph.versioner.relationship.create", mode = Mode.WRITE)
@Description("graph.versioner.relationship.create(entityA, entityB, type, relProps, date) - Create a relationship from entitySource to entityDestination with the given type and/or properties for the specified date.")
public Stream<RelationshipOutput> relationshipCreate(
        @Name("entitySource") Node entitySource,
        @Name("entityDestination") Node entityDestination,
        @Name(value = "type") String type,
        @Name(value = "relProps", defaultValue = "{}") Map<String, Object> relProps,
        @Name(value = "date", defaultValue = "null") LocalDateTime date) {

    isEntityOrThrowException(entitySource);
    isEntityOrThrowException(entityDestination);

    Optional<Node> sourceCurrentState = createNewSourceState(entitySource, defaultToNow(date));
    Optional<Node> destinationRNode = getRNode(entityDestination);

    if (sourceCurrentState.isPresent() && destinationRNode.isPresent()) {
        return streamOfRelationships(createRelationship(sourceCurrentState.get(), destinationRNode.get(), type, relProps));
    } else {
        return Stream.empty();
    }
}
 
Example #3
Source File: LR.java    From ml-models with Apache License 2.0 5 votes vote down vote up
@Procedure(value = "regression.linear.train", mode = Mode.READ)
@Description("Trains the model and returns stream containing the model's name (model), type (framework), whether " +
        "it containes a constant term (hasConstant), number of independent variables (numVars), state (state), " +
        "number of observations (N), and information (info).")
public Stream<ModelResult> train(@Name("model") String model) {
    return Stream.of(LRModel.from(model).train().asResult());
}
 
Example #4
Source File: Update.java    From neo4j-versioner-core with Apache License 2.0 5 votes vote down vote up
@Procedure(value = "graph.versioner.patch.from", mode = Mode.WRITE)
@Description("graph.versioner.patch.from(entity, state, useCurrentRel, date) - Add a new State to the given Entity, starting from the given one. It will update all the properties, not asLabels. If useCurrentRel is false, it will replace the current rels to Rs with the state ones.")
public Stream<NodeOutput> patchFrom(
        @Name("entity") Node entity,
        @Name("state") Node state,
        @Name(value = "useCurrentRel", defaultValue = "true") Boolean useCurrentRel,
        @Name(value = "date", defaultValue = "null") LocalDateTime date) {

    LocalDateTime instantDate = defaultToNow(date);
    List<String> labels = streamOfIterable(state.getLabels()).map(Label::name).collect(Collectors.toList());

    checkRelationship(entity, state);

    Optional<Relationship> currentRelationshipOpt = getCurrentRelationship(entity);

    Node newState = currentRelationshipOpt
            .map(currentRelationship -> createPatchedState(state.getAllProperties(), labels, instantDate, currentRelationship))
            .orElseThrow(() -> new VersionerCoreException("Can't find any current State node for the given entity."));

    //Copy all the relationships
    if (useCurrentRel) {
        currentRelationshipOpt.ifPresent(rel -> connectStateToRs(rel.getEndNode()   , newState));
    } else {
        connectStateToRs(state, newState);
    }

    log.info(LOGGER_TAG + "Patched Entity with id {}, adding a State with id {}", entity.getId(), newState.getId());

    return Stream.of(new NodeOutput(newState));
}
 
Example #5
Source File: Update.java    From neo4j-versioner-core with Apache License 2.0 5 votes vote down vote up
@Procedure(value = "graph.versioner.patch", mode = Mode.WRITE)
@Description("graph.versioner.patch(entity, {key:value,...}, additionalLabel, date) - Add a new State to the given Entity, starting from the previous one. It will update all the properties, not asLabels.")
public Stream<NodeOutput> patch(
        @Name("entity") Node entity,
        @Name(value = "stateProps", defaultValue = "{}") Map<String, Object> stateProps,
        @Name(value = "additionalLabel", defaultValue = "") String additionalLabel,
        @Name(value = "date", defaultValue = "null") LocalDateTime date) {

    List<String> labelNames = getStateLabels(additionalLabel);
    LocalDateTime instantDate = defaultToNow(date);
    Optional<Relationship> currentRelationshipOpt = getCurrentRelationship(entity);

    // Creating the new current state
    Node newState = currentRelationshipOpt
            .map(currentRelationship -> createPatchedState(stateProps, labelNames, instantDate, currentRelationship))
            .orElseGet(() -> {
                Node result = setProperties(db.createNode(asLabels(labelNames)), stateProps);
                addCurrentState(result, entity, instantDate);
                return result;
            });

    //Copy all the relationships
    currentRelationshipOpt.ifPresent(rel -> connectStateToRs(rel.getEndNode(), newState));

    log.info(LOGGER_TAG + "Patched Entity with id {}, adding a State with id {}", entity.getId(), newState.getId());

    return Stream.of(new NodeOutput(newState));
}
 
Example #6
Source File: RelationshipProcedure.java    From neo4j-versioner-core with Apache License 2.0 5 votes vote down vote up
@Procedure(value = "graph.versioner.relationship.delete", mode = Mode.WRITE)
@Description("graph.versioner.relationship.delete(entityA, entityB, type, date) - Delete a custom type relationship from entitySource's current State to entityDestination for the specified date.")
public Stream<BooleanOutput> relationshipDelete(
        @Name("entitySource") Node entitySource,
        @Name("entityDestination") Node entityDestination,
        @Name(value = "type") String type,
        @Name(value = "date", defaultValue = "null") LocalDateTime date) {

    isEntityOrThrowException(entitySource);
    isEntityOrThrowException(entityDestination);
    if (isSystemType(type)) {
        throw new VersionerCoreException("It's not possible to delete a System Relationship like " + type + ".");
    }

    Optional<Node> sourceCurrentState = createNewSourceState(entitySource, defaultToNow(date));
    Optional<Node> destinationRNode = getRNode(entityDestination);

    Update updateProcedure = new UpdateBuilder().withLog(log).withDb(db).build().orElseThrow(() -> new VersionerCoreException("Unable to initialize update procedure"));

    if (sourceCurrentState.isPresent() && destinationRNode.isPresent()) {
        updateProcedure.update(entitySource, sourceCurrentState.get().getAllProperties(), "", null);
        getCurrentRelationship(entitySource).ifPresent(rel -> rel.getEndNode().getRelationships(RelationshipType.withName(type), Direction.OUTGOING).forEach(Relationship::delete));
        return Stream.of(new BooleanOutput(Boolean.TRUE));
    } else {
        return Stream.of(new BooleanOutput(Boolean.FALSE));
    }
}
 
Example #7
Source File: LR.java    From ml-models with Apache License 2.0 5 votes vote down vote up
@Procedure(value = "regression.linear.load", mode = Mode.READ)
@Description("This procedure loads the model stored in data into the procedure's memory under the name 'model'. " +
        "The model must be of type 'Simple' and 'data' must be a byte array. Returns a stream containing the model's " +
        "name (model), type (framework), whether it containes a constant term (hasConstant), number of independent " +
        "variables (numVars), state (state), number of observations (N), and information (info).")
public Stream<ModelResult> load(@Name("model") String model, @Name("data") Object data, @Name("framework") String framework) {
    return Stream.of(LRModel.load(model, data, framework).asResult());
}
 
Example #8
Source File: LR.java    From ml-models with Apache License 2.0 5 votes vote down vote up
@Procedure(value = "regression.linear.delete", mode = Mode.READ)
@Description("Deletes 'model' from storage. Returns a stream containing the model's name (model), type (framework), " +
        "whether it containes a constant term (hasConstant), number of independent variables (numVars), state (state), " +
        "number of observations (N), and information (info).")
public Stream<ModelResult> delete(@Name("model") String model) {
    return Stream.of(LRModel.removeModel(model));
}
 
Example #9
Source File: LR.java    From ml-models with Apache License 2.0 5 votes vote down vote up
@Procedure(value = "regression.linear.info", mode = Mode.READ)
@Description("Return a stream containing the model's name (model), type (framework), whether it containes a constant term " +
        "(hasConstant), number of independent variables (numVars), state (state), number of observations (N), and information " +
        "(info). If the model is in state 'ready' info will contain parameters and statistics about the trained model.")
public Stream<ModelResult> info(@Name("model") String model) {
    return Stream.of(LRModel.from(model).asResult());
}
 
Example #10
Source File: Schema.java    From decision_trees_with_rules with MIT License 5 votes vote down vote up
@Procedure(name = "com.maxdemarzi.schema.generate", mode = Mode.SCHEMA)
@Description("CALL com.maxdemarzi.schema.generate() - generate schema")

public Stream<StringResult> generate() throws IOException {
    org.neo4j.graphdb.schema.Schema schema = db.schema();
    if (!schema.getIndexes(Labels.Tree).iterator().hasNext()) {
        schema.constraintFor(Labels.Tree)
                .assertPropertyIsUnique("id")
                .create();
    }
    return Stream.of(new StringResult("Schema Generated"));
}
 
Example #11
Source File: LR.java    From ml-models with Apache License 2.0 5 votes vote down vote up
@Procedure(value = "regression.linear.removeM", mode = Mode.READ)
@Description("Void procedure which removes multiple observations (given[i], expected[i]) from 'model'. Indicate whether to " +
        "remove data from training or testing dataset.")
public void removeM(@Name("model") String model, @Name("given") List<List<Double>> given, @Name("expected") List<Double> expected,
@Name(value = "type", defaultValue = "train") String type) {
    LRModel.from(model).removeMany(given, expected, type, log);
}
 
Example #12
Source File: LR.java    From ml-models with Apache License 2.0 5 votes vote down vote up
@Procedure(value = "regression.linear.remove", mode = Mode.READ)
@Description("Void procedure which removes a single observation of type 'type' from 'model'. Throws runtime error if model is not of " +
        "framework 'Simple'.")
public void remove(@Name("model") String model, @Name("given") List<Double> given, @Name("expected") double expected,
                   @Name(value="type", defaultValue = "train") String type) {
    LRModel.from(model).remove(given, expected, type, log);
}
 
Example #13
Source File: LR.java    From ml-models with Apache License 2.0 5 votes vote down vote up
@Procedure(value = "regression.linear.addM", mode = Mode.READ)
@Description("Void procedure which adds multiple observations (given[i], expected[i]) to 'model'. Indicate whether data is for " +
        "training or testing the model.")
public void addM(@Name("model") String model, @Name("given") List<List<Double>> given, @Name("expected") List<Double> expected,
                 @Name(value="type", defaultValue="train") String type) {
    LRModel.from(model).addMany(given, expected, type, log);
}
 
Example #14
Source File: LR.java    From ml-models with Apache License 2.0 5 votes vote down vote up
@Procedure(value = "regression.linear.create", mode = Mode.READ)
@Description("Initialize a linear regression model with 'name' of type 'framework' and store in static memory. " +
        "Indicate whether to include a constant term. Accepted frameworks are 'Simple' and 'Multiple'.")
public Stream<ModelResult> create(@Name("name") String model, @Name("framework") String framework,
                                  @Name(value="include constant term?", defaultValue="true") boolean constant,
                                  @Name(value="# of independent vars", defaultValue="1") Long numVars) {
    return Stream.of(LRModel.create(model, framework, constant, numVars.intValue()).asResult());
}
 
Example #15
Source File: CustomerProcedures.java    From ongdb-lab-apoc with Apache License 2.0 5 votes vote down vote up
@Procedure(value = "zdr.index.search", mode = Mode.WRITE)
@Description("CALL zdr.index.search(String indexName, String query, long limit) YIELD node,执行LUCENE全文检索,返回前{limit个结果}")
public Stream<ChineseHit> search(@Name("indexName") String indexName, @Name("query") String query, @Name("limit") long limit) {
    if (!db.index().existsForNodes(indexName)) {
        log.debug("如果索引不存在则跳过本次查询:`%s`", indexName);
        return Stream.empty();
    }
    return db.index()
            .forNodes(indexName)
            .query(new QueryContext(query).sortByScore().top((int) limit))
            .stream()
            .map(ChineseHit::new);
}
 
Example #16
Source File: LR.java    From ml-models with Apache License 2.0 4 votes vote down vote up
@Procedure(value = "regression.linear.copy", mode = Mode.READ)
@Description("Copies training data from model 'source' into model 'dest'.")
public Stream<ModelResult> copy(@Name("source") String source, @Name("dest") String dest) {
    return Stream.of(LRModel.from(dest).copy(source).asResult());
}
 
Example #17
Source File: LR.java    From ml-models with Apache License 2.0 4 votes vote down vote up
@Procedure(value = "regression.linear.test", mode = Mode.READ)
@Description("Tests the fit of the model on test data and returns statistics.")
public Stream<ModelResult> test(@Name("model") String model) {
    return Stream.of(LRModel.from(model).test().asResult());
}
 
Example #18
Source File: LR.java    From ml-models with Apache License 2.0 4 votes vote down vote up
@Procedure(value = "regression.linear.add", mode = Mode.READ)
@Description("Void procedure which adds a single observation to the model. Indicate whether data is for training or testing the model.")
public void add(@Name("model") String model, @Name("given") List<Double> given, @Name("expected") double expected,
                @Name(value="type", defaultValue="train") String type) {
    LRModel.from(model).add(given, expected, type, log);
}
 
Example #19
Source File: LR.java    From ml-models with Apache License 2.0 4 votes vote down vote up
@Procedure(value = "regression.linear.clear", mode=Mode.READ)
@Description("If type is 'all' clear all data from 'model' and model returns to state 'created'. If type is 'test' only clear test data from 'model'.")
public Stream<ModelResult> clear(@Name("model") String model, @Name(value="type", defaultValue = "all") String type) {
    return Stream.of(LRModel.from(model).clear(type).asResult());
}
 
Example #20
Source File: Update.java    From neo4j-versioner-core with Apache License 2.0 4 votes vote down vote up
@Procedure(value = "graph.versioner.update", mode = Mode.WRITE)
@Description("graph.versioner.update(entity, {key:value,...}, additionalLabel, date) - Add a new State to the given Entity.")
public Stream<NodeOutput> update(
        @Name("entity") Node entity,
        @Name(value = "stateProps", defaultValue = "{}") Map<String, Object> stateProps,
        @Name(value = "additionalLabel", defaultValue = "") String additionalLabel,
        @Name(value = "date", defaultValue = "null") LocalDateTime date) {

    // Creating the new State
    List<String> labelNames = new ArrayList<>(Collections.singletonList(STATE_LABEL));
    if (!additionalLabel.isEmpty()) {
        labelNames.add(additionalLabel);
    }
    Node result = setProperties(db.createNode(asLabels(labelNames)), stateProps);

    LocalDateTime instantDate = defaultToNow(date);

    // Getting the CURRENT rel if it exist
    Spliterator<Relationship> currentRelIterator = entity.getRelationships(RelationshipType.withName(CURRENT_TYPE), Direction.OUTGOING).spliterator();
    StreamSupport.stream(currentRelIterator, false).forEach(currentRel -> {
        Node currentState = currentRel.getEndNode();

        LocalDateTime currentDate = (LocalDateTime) currentRel.getProperty("date");

        // Creating PREVIOUS relationship between the current and the new State
        result.createRelationshipTo(currentState, RelationshipType.withName(PREVIOUS_TYPE)).setProperty(DATE_PROP, currentDate);

        // Updating the HAS_STATE rel for the current node, adding endDate
        currentState.getRelationships(RelationshipType.withName(HAS_STATE_TYPE), Direction.INCOMING)
                .forEach(hasStatusRel -> hasStatusRel.setProperty(END_DATE_PROP, instantDate));

        // Refactoring current relationship and adding the new ones
        currentRel.delete();

        // Connecting the new current state to Rs
        connectStateToRs(currentState, result);
    });

    // Connecting the new current state to the Entity
    addCurrentState(result, entity, instantDate);

    log.info(LOGGER_TAG + "Updated Entity with id {}, adding a State with id {}", entity.getId(), result.getId());

    return Stream.of(new NodeOutput(result));
}
 
Example #21
Source File: DeepGLProc.java    From ml-models with Apache License 2.0 4 votes vote down vote up
@Procedure(value = "embedding.deepgl", mode = Mode.WRITE)
public Stream<DeepGLProcResult> deepGL(
        @Name(value = "label", defaultValue = "") String label,
        @Name(value = "relationship", defaultValue = "") String relationship,
        @Name(value = "config", defaultValue = "{}") Map<String, Object> config) {

    final ProcedureConfiguration configuration = ProcedureConfiguration.create(config);

    int iterations = configuration.getInt("iterations", 10);
    int diffusions = configuration.getInt("diffusions", 10);
    double pruningLambda = configuration.get("pruningLambda", 0.7);

    final DeepGLProcResult.Builder builder = DeepGLProcResult.builder();


    HeavyGraph graph;
    try (ProgressTimer timer = builder.timeLoad()) {
        graph = (HeavyGraph) new GraphLoader(api, Pools.DEFAULT)
                .init(log, label, relationship, configuration)
                .withoutNodeProperties()
                .withDirection(configuration.getDirection(Direction.BOTH))
                .withOptionalNodeProperties(extractNodeFeatures(config))
                .load(configuration.getGraphImpl());
    }

    builder.withNodeCount(graph.nodeCount());

    if (graph.nodeCount() == 0) {
        return Stream.empty();
    }

    final TerminationFlag terminationFlag = TerminationFlag.wrap(transaction);
    DeepGL algo = new DeepGL(graph, Pools.DEFAULT, configuration.getConcurrency(), iterations, pruningLambda, diffusions)
            .withProgressLogger(ProgressLogger.wrap(log, "DeepGL"))
            .withTerminationFlag(terminationFlag);

    builder.timeEval(algo::compute);
    graph.release();

    INDArray embedding = algo.embedding();
    builder.withEmbeddingSize(embedding.columns());
    builder.withFeatures(algo.features());
    builder.withLayers(algo.numberOfLayers());

    if (configuration.isWriteFlag()) {
        builder.timeWrite(() -> {
            final String writeProperty = configuration.getWriteProperty(DEFAULT_TARGET_PROPERTY);

            builder.withWriteProperty(writeProperty);

            Exporter.of(api, graph)
                    .withLog(log)
                    .parallel(Pools.DEFAULT, configuration.getConcurrency(), terminationFlag)
                    .build()
                    .write(writeProperty, embedding, new INDArrayPropertyTranslator());
        });
    }

    return Stream.of(builder.build());
}