org.neo4j.procedure.Description Java Examples

The following examples show how to use org.neo4j.procedure.Description. 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: FreetextIK.java    From ongdb-lab-apoc with Apache License 2.0 6 votes vote down vote up
/**
 * @param text:待分词文本
 * @param useSmart:true 用智能分词,false 细粒度分词
 * @return
 * @Description: TODO(支持中英文本分词)
 */
@UserFunction(name = "zdr.index.iKAnalyzer")
@Description("Fulltext index iKAnalyzer - RETURN zdr.index.iKAnalyzer({text},true) AS words")
public List<String> iKAnalyzer(@Name("text") String text, @Name("useSmart") boolean useSmart) {

    PropertyConfigurator.configureAndWatch("dic" + File.separator + "log4j.properties");
    Configuration cfg = new Configuration(useSmart);

    StringReader input = new StringReader(text.trim());
    IKSegmenter ikSegmenter = new IKSegmenter(input, cfg);

    List<String> results = new ArrayList<>();
    try {
        for (Lexeme lexeme = ikSegmenter.next(); lexeme != null; lexeme = ikSegmenter.next()) {
            results.add(lexeme.getLexemeText());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return results;
}
 
Example #2
Source File: ZdrProcedures.java    From ongdb-lab-apoc with Apache License 2.0 6 votes vote down vote up
/**
 * @param
 * @return
 * @Description: TODO(百分比映射)
 */
@UserFunction(name = "zdr.apoc.scorePercentage")
@Description("Set node influence score percentage")
public Number percentageInfluenceScore(@Name("mapPara") Map<String, Object> mapPara) {

    double max = shiftDouble(mapPara.get("maxScore"));
    double min = shiftDouble(mapPara.get("minScore"));
    double current = shiftDouble(mapPara.get("currentScore"));

    // min-max标准化(Min-MaxNormalization)也称为离差标准化,是对原始数据的线性变换,使结果值映射到 [0 - 1] 之间
    double initialThreshold = 0.015;
    if (min <= current && current <= max && min != 0) {
        double percentage = (current - min) / (max - min);
        double percentageFormat = Double.parseDouble(String.format("%.6f", percentage));
        if (percentageFormat == 0) {
            return initialThreshold;
        }
        return percentageFormat;
    } else {
        return initialThreshold;
    }
}
 
Example #3
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 #4
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 #5
Source File: ZdrProcedures.java    From ongdb-lab-apoc with Apache License 2.0 6 votes vote down vote up
/**
 * @param
 * @return
 * @Description: TODO(是否包含某字符串 | | - 任意包含一个 & & - 全部包含)
 */
@UserFunction(name = "zdr.apoc.isContainsString")
@Description("Is contains string? &&-All contains ||-Or contains (Chinese||English Chinese&&English)")
public boolean isContainsString(@Name("mapPara") Map<String, Object> mapPara) {

    // 将输入拼接成一个STRING
    String original = removeNull(mapPara.get("original0")) + removeNull(mapPara.get("original1")) + removeNull(mapPara.get("original2")) +
            removeNull(mapPara.get("original3")) + removeNull(mapPara.get("original4")) + removeNull(mapPara.get("original5")) + removeNull(mapPara.get("original6")) +
            removeNull(mapPara.get("original7")) + removeNull(mapPara.get("original8")) + removeNull(mapPara.get("original9"));
    String input = (String) mapPara.get("input");

    if (original != null && !"".equals(original)) {
        String[] split;
        if (input.contains("||")) {
            split = input.split("\\|\\|");
            return Arrays.stream(split).parallel().anyMatch(v -> original.contains(v));
        } else if (input.contains("&&")) {
            split = input.split("&&");
            return Arrays.stream(split).parallel().allMatch(v -> original.contains(v));
        } else if (original.contains(input)) {
            return true;
        }
    }
    return false;
}
 
Example #6
Source File: ZdrProcedures.java    From ongdb-lab-apoc with Apache License 2.0 6 votes vote down vote up
/**
 * @param
 * @return
 * @Description: TODO(地理位置名称多字段检索 -)
 */
@UserFunction(name = "zdr.apoc.locMultiFieldsFullTextSearchCondition")
@Description("Location multi fields search- 找共同居住地的人 - EXAMPLE:location:`\"+location+\"`* OR location:`\"+location+\"`*")
public String locMultiFieldsFullTextSearchCondition(@Name("node") Node node, @Name("locMultiFields") List<String> locMultiFields) {

    StringBuilder builder = new StringBuilder();
    Map<String, Object> mapProperties = node.getAllProperties();
    locMultiFields.forEach(field -> {
        if (!"".equals(field) && field != null) {
            if (mapProperties.containsKey(field)) {
                Object value = node.getProperty(field);
                if (value instanceof String) {
                    if (value != null && !"".equals(value)) {
                        builder.append(field + ":`" + value + "`* OR ");
                    }
                }
            }
        }
    });
    if (builder != null && !"".equals(builder.toString())) {
        return builder.substring(0, builder.length() - 3);
    }
    return "`null`";
}
 
Example #7
Source File: ZdrProcedures.java    From ongdb-lab-apoc with Apache License 2.0 6 votes vote down vote up
/**
 * @param nLabels:节点集合
 * @param mLabels:节点集合
 * @param strictLabels:标签 分隔符号(||)
 * @return 两个集合同时包含某一个标签 返回TRUE
 * @Description: TODO(两个集合同时包含某一个标签)
 */
@UserFunction(name = "zdr.apoc.relatCalculateRestrict")
@Description("Graph relationships calculate restrict")
public boolean relatCalculateRestrict(@Name("nLabels") List<String> nLabels, @Name("mLabels") List<String> mLabels, @Name("restrictLabels") String strictLabels) {

    // ||包含其中一个
    if (strictLabels.contains("||")) {
        String[] strict = strictLabels.split("\\|\\|");
        for (int i = 0; i < strict.length; i++) {
            String label = strict[i];
            if (nLabels.contains(label) && mLabels.contains(label)) {
                return true;
            }
        }
    } else {
        if (nLabels.contains(strictLabels) && mLabels.contains(strictLabels)) {
            return true;
        }
    }

    return false;
}
 
Example #8
Source File: Get.java    From neo4j-versioner-core with Apache License 2.0 6 votes vote down vote up
@Procedure(value = "graph.versioner.get.all", mode = DEFAULT)
@Description("graph.versioner.get.all(entity) - Get all the State nodes for the given Entity.")
public Stream<PathOutput> getAllState(
        @Name("entity") Node entity) {

    PathImpl.Builder builder = new PathImpl.Builder(entity)
            .push(entity.getSingleRelationship(RelationshipType.withName(Utility.CURRENT_TYPE), Direction.OUTGOING));
    builder = StreamSupport.stream(entity.getRelationships(RelationshipType.withName(Utility.HAS_STATE_TYPE), Direction.OUTGOING).spliterator(), false)
            //.sorted((a, b) -> -1 * Long.compare((long)a.getProperty(START_DATE_PROP), (long)b.getProperty(START_DATE_PROP)))
            .reduce(
                    builder,
                    (build, rel) -> Optional.ofNullable(rel.getEndNode().getSingleRelationship(RelationshipType.withName(Utility.PREVIOUS_TYPE), Direction.OUTGOING))
                                        .map(build::push)
                                        .orElse(build),
                    (a, b) -> a);
    return Stream.of(new PathOutput(builder.build()));
}
 
Example #9
Source File: Rollback.java    From neo4j-versioner-core with Apache License 2.0 5 votes vote down vote up
@Procedure(value = "graph.versioner.rollback.nth", mode = WRITE)
@Description("graph.versioner.rollback.nth(entity, nth-state, date) - Rollback the given Entity to the nth previous State")
public Stream<NodeOutput> rollbackNth(
        @Name("entity") Node entity,
        @Name("state") long nthState,
        @Name(value = "date", defaultValue = "null") LocalDateTime date) {

    LocalDateTime instantDate = defaultToNow(date);

    return new GetBuilder().build()
            .flatMap(get -> get.getNthState(entity, nthState).findFirst())
            .map(state -> rollbackTo(entity, state.node, instantDate))
            .orElse(Stream.empty());
}
 
Example #10
Source File: ZdrProcedures.java    From ongdb-lab-apoc with Apache License 2.0 5 votes vote down vote up
/**
 * @param
 * @return
 * @Description: TODO(节点ID集合移除某些节点)
 */
@UserFunction(name = "zdr.apoc.removeIdsFromRawList")
@Description("Remove ids from raw node id list")
public List<Long> removeIdsFromRawList(@Name("rawIDs") List<Long> rawIDs, @Name("ids") List<Long> ids) {
    if (rawIDs != null && ids != null) {
        rawIDs.removeAll(ids);
        return rawIDs;
    }
    return rawIDs;
}
 
Example #11
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 #12
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 #13
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 #14
Source File: Diff.java    From neo4j-versioner-core with Apache License 2.0 5 votes vote down vote up
@Procedure(value = "graph.versioner.diff", mode = DEFAULT)
@Description("graph.versioner.diff(stateFrom, stateTo) - Get a list of differences that must be applied to stateFrom in order to convert it into stateTo")
public Stream<DiffOutput> diff(
        @Name("stateFrom") Node stateFrom,
        @Name("stateTo") Node stateTo) {
    return diffBetweenStates(stateFrom, stateTo);
}
 
Example #15
Source File: Diff.java    From neo4j-versioner-core with Apache License 2.0 5 votes vote down vote up
@Procedure(value = "graph.versioner.diff.from.previous", mode = DEFAULT)
  @Description("graph.versioner.diff.from.previous(state) - Get a list of differences that must be applied to the previous statusof the given one in order to become the given state")
  public Stream<DiffOutput> diffFromPrevious(
          @Name("state") Node state) {

return Optional.ofNullable(state.getSingleRelationship(RelationshipType.withName(Utility.PREVIOUS_TYPE), Direction.OUTGOING))
		.map(Relationship::getEndNode)
		.map(sFrom -> diffBetweenStates(sFrom, state))
		.orElse(Stream.empty());
  }
 
Example #16
Source File: Diff.java    From neo4j-versioner-core with Apache License 2.0 5 votes vote down vote up
@Procedure(value = "graph.versioner.diff.from.current", mode = DEFAULT)
@Description("graph.versioner.diff.from.current(state) - Get a list of differences that must be applied to the given state in order to become the current entity state")
public Stream<DiffOutput> diffFromCurrent(
		@Name("state") Node state) {

	return Optional.ofNullable(state.getSingleRelationship(RelationshipType.withName(Utility.HAS_STATE_TYPE), Direction.INCOMING))
			.map(Relationship::getStartNode)
			.map(entity -> entity.getSingleRelationship(RelationshipType.withName(Utility.CURRENT_TYPE), Direction.OUTGOING))
			.map(Relationship::getEndNode)
			.filter(current -> !current.equals(state))
			.map(current -> diffBetweenStates(state, current))
			.orElse(Stream.empty());
}
 
Example #17
Source File: Get.java    From neo4j-versioner-core with Apache License 2.0 5 votes vote down vote up
@Procedure(value = "graph.versioner.get.current.path", mode = DEFAULT)
@Description("graph.versioner.get.current.path(entity) - Get the current Path (Entity, State and rels) for the given Entity.")
public Stream<PathOutput> getCurrentPath(
        @Name("entity") Node entity) {

    PathImpl.Builder builder = new PathImpl.Builder(entity);

    builder = Optional.ofNullable(entity.getSingleRelationship(RelationshipType.withName(Utility.CURRENT_TYPE), Direction.OUTGOING))
            .map(builder::push)
            .orElse(new PathImpl.Builder(entity));

    return Stream.of(builder.build()).map(PathOutput::new);
}
 
Example #18
Source File: Get.java    From neo4j-versioner-core with Apache License 2.0 5 votes vote down vote up
@Procedure(value = "graph.versioner.get.current.state", mode = DEFAULT)
@Description("graph.versioner.get.current.state(entity) - Get the current State node for the given Entity.")
public Stream<NodeOutput> getCurrentState(
        @Name("entity") Node entity) {

    return Stream.of(Optional.ofNullable(entity.getSingleRelationship(RelationshipType.withName(Utility.CURRENT_TYPE), Direction.OUTGOING))
            .map(Relationship::getEndNode).map(NodeOutput::new).orElse(null));
}
 
Example #19
Source File: Get.java    From neo4j-versioner-core with Apache License 2.0 5 votes vote down vote up
@Procedure(value = "graph.versioner.get.by.label", mode = DEFAULT)
@Description("graph.versioner.get.by.label(entity, label) - Get State nodes with the given label, by the given Entity node")
public Stream<NodeOutput> getAllStateByLabel(
        @Name("entity") Node entity,
        @Name("label") String label) {

    return StreamSupport.stream(entity.getRelationships(RelationshipType.withName(Utility.HAS_STATE_TYPE), Direction.OUTGOING).spliterator(), false)
            .map(Relationship::getEndNode)
            .filter(node -> node.hasLabel(Label.label(label)))
            .map(NodeOutput::new);
}
 
Example #20
Source File: Get.java    From neo4j-versioner-core with Apache License 2.0 5 votes vote down vote up
@Procedure(value = "graph.versioner.get.by.date", mode = DEFAULT)
@Description("graph.versioner.get.by.date(entity, date) - Get State node by the given Entity node, created at the given date")
public Stream<NodeOutput> getStateByDate(
        @Name("entity") Node entity,
        @Name("date") LocalDateTime date) {

    return StreamSupport.stream(entity.getRelationships(RelationshipType.withName(Utility.HAS_STATE_TYPE), Direction.OUTGOING).spliterator(), false)
            .filter(relationship -> relationship.getProperty(Utility.START_DATE_PROP).equals(date))
            .map(Relationship::getEndNode)
            .map(NodeOutput::new);
}
 
Example #21
Source File: ZdrProcedures.java    From ongdb-lab-apoc with Apache License 2.0 5 votes vote down vote up
/**
 * @param
 * @return
 * @Description: TODO(节点是否包含某个KEY - 多个中的任意一个)
 */
@UserFunction(name = "zdr.apoc.nodeIsContainsKey")
@Description("Node is contain key or not")
public boolean nodeIsContainsKey(@Name("node") Node node, @Name("locMultiFields") List<String> locMultiFields) {
    Map<String, Object> mapProperties = node.getAllProperties();
    for (int i = 0; i < locMultiFields.size(); i++) {
        String field = locMultiFields.get(i);
        if (mapProperties.containsKey(field)) {
            return true;
        }
    }
    return false;
}
 
Example #22
Source File: ZdrProcedures.java    From ongdb-lab-apoc with Apache License 2.0 5 votes vote down vote up
/**
 * @param
 * @return
 * @Description: TODO(去重合并多个节点列表)
 */
@UserFunction(name = "zdr.apoc.mergeNodes")
@Description("Merge node list")
public List<Node> mergeNodes(@Name("nodePackArray") List<List<Node>> nodePackArray) {

    List<Node> nodes = new ArrayList<>();

    for (int i = 0; i < nodePackArray.size(); i++) {
        List<Node> nodeList = nodePackArray.get(i);
        nodes.addAll(nodeList);
    }
    NodeHandle nodeHandle = new NodeHandle();

    return nodeHandle.distinctNodes(nodes);
}
 
Example #23
Source File: ZdrProcedures.java    From ongdb-lab-apoc with Apache License 2.0 5 votes vote down vote up
/**
 * @param
 * @return
 * @Description: TODO(节点是否包含权限)
 */
@UserFunction(name = "zdr.apoc.isContainAuthority")
@Description("Node is contains authority or not")
public boolean isContainAuthority(@Name("node") Node node) {
    Iterable<String> iterableKeys = node.getPropertyKeys();

    String prefix = "sysuser_id_";
    for (Iterator iterator = iterableKeys.iterator(); iterator.hasNext(); ) {
        String key = (String) iterator.next();
        if (key.contains(prefix)) {
            return true;
        }
    }
    return false;
}
 
Example #24
Source File: ZdrProcedures.java    From ongdb-lab-apoc with Apache License 2.0 5 votes vote down vote up
/**
 * 判断字符串中是否包含中文
 *
 * @param node:节点的所有属性中是否包含中文
 * @return 是否为中文
 * @warn 不能校验是否为中文标点符号
 */
@UserFunction(name = "zdr.apoc.isContainChinese")
@Description("Node is contains chinese or not")
public long isContainChinese(@Name("node") Node node) {

    Iterable<String> iterableKeys = node.getPropertyKeys();
    StringBuilder nodeValueBuilder = new StringBuilder();
    for (Iterator iterator = iterableKeys.iterator(); iterator.hasNext(); ) {
        Object next = iterator.next();
        Object nodeValue = node.getProperty((String) next);
        if (nodeValue instanceof String) {
            nodeValueBuilder.append(nodeValue);
        }
    }
    // 所有节点属性value
    char[] nodeValueChar = nodeValueBuilder.toString().toCharArray();

    int chineseCharCount = 0;
    ChineseVerify chineseVerify = new ChineseVerify();
    for (int i = 0; i < nodeValueChar.length; i++) {
        char c = nodeValueChar[i];
        if (chineseVerify.isContainChinese(String.valueOf(c))) {
            chineseCharCount++;
        }
    }
    return chineseCharCount;
}
 
Example #25
Source File: Get.java    From neo4j-versioner-core with Apache License 2.0 5 votes vote down vote up
@Procedure(value = "graph.versioner.get.nth.state", mode = DEFAULT)
@Description("graph.versioner.get.nth.state(entity, nth) - Get the nth State node for the given Entity.")
public Stream<NodeOutput> getNthState(
		@Name("entity") Node entity,
		@Name("nth") long nth) {

   	return getCurrentState(entity)
			.findFirst()
			.flatMap(currentState -> getNthStateFrom(currentState.node, nth))
			.map(Utility::streamOfNodes)
			.orElse(Stream.empty());
}
 
Example #26
Source File: ZdrProcedures.java    From ongdb-lab-apoc with Apache License 2.0 5 votes vote down vote up
/**
 * @param
 * @return
 * @Description: TODO(判断两个时间区间是否有交叉)
 */
@UserFunction(name = "zdr.apoc.timeCrossOrNot")
@Description("Time zone cross or not")
public boolean timeCrossOrNot(@Name("mapPara") Map<String, Object> mapPara) {

    DateHandle dateHandle = new DateHandle();
    String r1Start = (String) mapPara.get("r1Start");
    String r1Stop = (String) mapPara.get("r1Stop");
    String r2Start = (String) mapPara.get("r2Start");
    String r2Stop = (String) mapPara.get("r2Stop");

    if ((dateHandle.objectToDate(r1Start) || dateHandle.objectToDate(r1Stop)) && (dateHandle.objectToDate(r2Start)
            || dateHandle.objectToDate(r2Stop))) {

        long r1StartMill = dateHandle.dateToMillisecond(r1Start);
        long r1StopMill = dateHandle.dateToMillisecond(r1Stop);
        long r2StartMill = dateHandle.dateToMillisecond(r2Start);
        long r2StopMill = dateHandle.dateToMillisecond(r2Stop);

        // 不可能交叉的情况:
        // 1、区间一的结束时间小于区间二的开始时间
        // 2、区间一的开始时间大于区间二的结束时间

        if ((r1StartMill > r2StopMill && r1StartMill != 0 && r2StopMill != 0)
                || (r1StopMill < r2StartMill && r1StopMill != 0 && r2StartMill != 0)
                || (r1StartMill > r2StartMill && r2StopMill == 0)
                || (r1StartMill < r2StartMill && r1StopMill == 0)) {
            return false;
        } else {
            return true;
        }
    }
    return false;
}
 
Example #27
Source File: ZdrProcedures.java    From ongdb-lab-apoc with Apache License 2.0 5 votes vote down vote up
/**
 * @param
 * @return
 * @Description: TODO(Present字符转换获取当前系统时间)
 */
@UserFunction(name = "zdr.apoc.presentStringToDate")
@Description("Present-Convert date to relevant format")
public String presentStringToDate(@Name("present") String present) {
    if ("Present".equals(present)) {
        DateHandle dateHandle = new DateHandle();
        return dateHandle.millisecondToDate(System.currentTimeMillis());
    }
    return present;
}
 
Example #28
Source File: ZdrProcedures.java    From ongdb-lab-apoc with Apache License 2.0 5 votes vote down vote up
/**
 * @param
 * @return
 * @Description: TODO(小数点向后移动)
 */
@UserFunction(name = "zdr.apoc.moveDecimalPoint")
@Description("Move six decimal points")
public Number moveDecimalPoint(@Name("mapPara") Map<String, Object> mapPara) {
    double scoreObject = shiftDouble(mapPara.get("scoreObject"));
    double moveLength = shiftDouble(mapPara.get("moveLength"));
    BigDecimal score = BigDecimal.valueOf(scoreObject);
    score = score.multiply(BigDecimal.valueOf(moveLength));
    BigInteger scoreInt = score.toBigInteger();
    return scoreInt.intValue();
}
 
Example #29
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 #30
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);
}