Java Code Examples for org.neo4j.procedure.Mode#WRITE

The following examples show how to use org.neo4j.procedure.Mode#WRITE . 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: 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 2
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 3
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 4
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 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: 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 7
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());
}
 
Example 8
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));
}