Java 类org.neo4j.graphdb.Direction 实例源码

项目:golr-loader    文件:GolrLoader.java   
private Set<DirectedRelationshipType> resolveRelationships(String key, String value) {
  Set<DirectedRelationshipType> rels = new HashSet<>();
  String cypherIn = String.format("[%s:%s]", key, value);
  String cypherOut = cypherUtil.resolveRelationships(cypherIn);
  Matcher m = ENTAILMENT_PATTERN.matcher(cypherOut);
  while (m.find()) {
    String types = m.group(2);
    String[] cypherRels = types.split("\\|");
    for (String cypherRel : cypherRels) {
      String unquotedCypherRel = cypherRel.replaceAll("^`|`$","");
      RelationshipType relType = RelationshipType.withName(unquotedCypherRel);
      DirectedRelationshipType dirRelType = new DirectedRelationshipType(relType, Direction.OUTGOING);
      rels.add(dirRelType);
    }
  }
  return rels;
}
项目:EvilCoder    文件:Traversals.java   
public static DDG getDDGForFunction(Node funcNode)
{
    DDG retval = new DDG();
    for (Node statement : Traversals.getStatementsForFunction(funcNode))
    {
        Iterable<Relationship> rels = statement
                .getRelationships(Direction.OUTGOING);
        long srcId = statement.getId();

        for (Relationship rel : rels)
        {
            if (!rel.getType().toString().equals(EdgeTypes.REACHES))
                continue;
            long dstId = rel.getEndNode().getId();
            String symbol = rel.getProperty("var").toString();
            retval.add(srcId, dstId, symbol);
        }

    }
    return retval;
}
项目:instacart    文件:Predictions.java   
static ArrayList<Node> alternatingOrder (Node order) {
    ArrayList<Node> products = new ArrayList<>();
    Relationship prevRel = order.getSingleRelationship(RelationshipTypes.PREV, Direction.OUTGOING);
    if (prevRel != null) {
        Node prevOrder = prevRel.getEndNode();
        prevRel = prevOrder.getSingleRelationship(RelationshipTypes.PREV, Direction.OUTGOING);
        if (prevRel != null) {
            prevOrder = prevRel.getEndNode();
            for (Relationship r1 : prevOrder.getRelationships(Direction.OUTGOING, RelationshipTypes.HAS)) {
                Node product = r1.getEndNode();
                products.add(product);
            }
        }
    }
    return products;
}
项目:neo4j-versioner-core    文件:Diff.java   
@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) {

    Optional<Node> currentState = 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);

    Stream<DiffOutput> result = Stream.empty();

    if(currentState.isPresent() && !currentState.equals(Optional.of(state))){
        result = diffBetweenStates(Optional.of(state), currentState);
    }

    return result;
}
项目:rule_matcher    文件:Matcher.java   
@Procedure(name = "com.maxdemarzi.match.user", mode = Mode.READ)
@Description("CALL com.maxdemarzi.match.user(username) - find matching rules")
public Stream<NodeResult> matchUser(@Name("username") String username) throws IOException {
    // We start by finding the user
    Node user = db.findNode(Labels.User, "username", username);
    if (user != null) {
        // Gather all of their attributes in to a Set
        Set<Node> userAttributes = new HashSet<>();
        Collection<String> attributes = new HashSet<>();

        for (Relationship r : user.getRelationships(Direction.OUTGOING, RelationshipTypes.HAS)) {
            userAttributes.add(r.getEndNode());
            attributes.add((String)r.getEndNode().getProperty("id"));
        }
        // Find the rules
        Set<Node> rules = findRules(attributes, userAttributes);
        return rules.stream().map(NodeResult::new);
    }

    return null;
}
项目:codemodel-rifle    文件:CfgWalker.java   
@Override
public <R, E extends Throwable> R accept(Visitor<R, E> visitor) throws E {
    //filternodes:
    for (Node node : nodes) {
        visitor.visitNode(node);
        for (Relationship relationship : node.getRelationships(Direction.OUTGOING)) {
            if (nodes.contains(relationship.getOtherNode(node))) {

                if (!relationshipLabels.contains(relationship.getType().name())) {
                    continue;
                }

                visitor.visitRelationship(relationship);
            }
        }
    }
    return visitor.done();
}
项目:codemodel-rifle    文件:SimpleWalker.java   
@Override
public <R, E extends Throwable> R accept(Visitor<R, E> visitor) throws E {
    for (Node node : dbServices.getAllNodes()) {
        if (node.hasLabel(Label.label("CompilationUnit"))) {
            continue;
        }
        if (node.hasLabel(Label.label("SourceSpan"))) {
            continue;
        }
        if (node.hasLabel(Label.label("SourceLocation"))) {
            continue;
        }

        visitor.visitNode(node);
        for (Relationship edge : node.getRelationships(Direction.OUTGOING)) {
            if (edge.isType(RelationshipType.withName("location"))) {
                continue;
            }
            visitor.visitRelationship(edge);
        }
    }
    return visitor.done();
}
项目:WhiteLab2.0-Neo4J-Plugin    文件:QueryBenchmark.java   
private Traverser getPatternMatch(Node startNode, final List<String> patterns, final List<NodeLabel> nodeLabels, final List<LinkLabel> linkLabels) {
    TraversalDescription td = database.traversalDescription()
        .depthFirst()
        .evaluator( new Evaluator() {
            public Evaluation evaluate( final org.neo4j.graphdb.Path path ) {
                if ( path.length() == 0 ) {
                    return Evaluation.EXCLUDE_AND_CONTINUE;
                }
                boolean isToken = path.endNode().hasLabel(NodeLabel.WordToken);
                boolean included = isToken && (path.length() == 1 || nodeHasAnnotation(path.endNode(), linkLabels.get(path.length() - 1), patterns.get(path.length() - 1)));
                boolean continued = path.length() < patterns.size();
                return Evaluation.of( included, continued );
            }
        } )
        .relationships(LinkLabel.NEXT, Direction.OUTGOING)
        .relationships(LinkLabel.HAS_TYPE, Direction.INCOMING)
        .relationships(LinkLabel.HAS_LEMMA, Direction.INCOMING)
        .relationships(LinkLabel.HAS_POS_TAG, Direction.INCOMING)
        .relationships(LinkLabel.HAS_HEAD, Direction.INCOMING);
    return td.traverse(startNode);
}
项目:doc2graph    文件:DocumentRelationBuilderByKeyTest.java   
@Test
public void shouldDeleteOneRelations()
{
    context.setDocumentKey("key");

    Node parent = db.createNode();
    parent.setProperty("type", "album");

    Node child = db.createNode();
    child.setProperty("type", "artist");

    Node track = db.createNode();
    track.setProperty("type", "track");

    this.docrel.buildRelation(parent, child, context);
    context.setDocumentKey("another_key");
    this.docrel.buildRelation(child, track, context);

    Set<Node> orphans = this.docrel.deleteRelations(context);

    Assert.assertEquals(1, orphans.size());
    Assert.assertEquals(1, StreamSupport.stream(parent.getRelationships().spliterator(), false).count());
    Assert.assertEquals(0, StreamSupport.stream(child.getRelationships(Direction.OUTGOING).spliterator(), false).count());
}
项目:doc2graph    文件:DocumentRelationBuilderByKeyTest.java   
@Test
public void shouldCreate3Relation()
{
    context.setDocumentKey("key");

    Node parent = db.createNode();
    parent.setProperty("type", "album");

    Node child = db.createNode();
    child.setProperty("type", "artist");

    this.docrel.buildRelation(parent, child, context);

    context.setDocumentKey("another_key");

    Node track = db.createNode();
    track.setProperty("type", "track");
    this.docrel.buildRelation(parent, child, context);
    this.docrel.buildRelation(child, track, context);

    Assert.assertEquals(2, StreamSupport.stream(parent.getRelationships().spliterator(), false).count());
    Assert.assertEquals(1, StreamSupport.stream(child.getRelationships(Direction.OUTGOING).spliterator(), false).count());

}
项目:doc2graph    文件:DocumentRelationBuilderTypeArrayKeyTest.java   
@Test
public void shouldDeleteRelationsOfKey()
{
    context.setDocumentKey("key");

    Node parent = db.createNode();
    parent.setProperty("type", "album");

    Node child = db.createNode();
    child.setProperty("type", "artist");

    Node track = db.createNode();
    track.setProperty("type", "track");

    this.docrel.buildRelation(parent, child, context);
    context.setDocumentKey("another_key");
    this.docrel.buildRelation(child, track, context);

    Set<Node> orphans = this.docrel.deleteRelations(context);

    Assert.assertEquals(1, orphans.size());
    Assert.assertEquals(1, StreamSupport.stream(parent.getRelationships().spliterator(), false).count());
    Assert.assertEquals(0, StreamSupport.stream(child.getRelationships(Direction.OUTGOING).spliterator(), false).count());
}
项目:umls-graph-api    文件:GraphFunctions.java   
public static List<String> getHypernyms(String cui){
  List<String> hypers = new ArrayList<>();

  try ( Transaction tx = graphDb.beginTx() ){
    TraversalDescription td = graphDb.traversalDescription()
        .breadthFirst()
        .relationships(RelReader.RelTypes.ISA, Direction.OUTGOING)
        .evaluator(Evaluators.excludeStartPosition());

    Node cuiNode = graphDb.findNode(RelReader.DictLabels.Concept, RelReader.CUI_PROPERTY, cui);
    if(cuiNode == null) return hypers;

    Traverser traverser = td.traverse(cuiNode);
    for(Path path : traverser){
      hypers.add(path.endNode().getProperty(RelReader.CUI_PROPERTY).toString());
    }
    tx.success();
  }
  return hypers;
}
项目:umls-graph-api    文件:GraphFunctions.java   
public static List<String> getHyponyms(String cui){
  List<String> hypos = new ArrayList<>();

  try ( Transaction tx = graphDb.beginTx() ){
    TraversalDescription td = graphDb.traversalDescription()
        .breadthFirst()
        .relationships(RelReader.RelTypes.ISA, Direction.INCOMING)
        .evaluator(Evaluators.excludeStartPosition());

    Node cuiNode = graphDb.findNode(RelReader.DictLabels.Concept, RelReader.CUI_PROPERTY, cui);
    if(cuiNode == null) return hypos;

    Traverser traverser = td.traverse(cuiNode);
    for(Path path : traverser){
      hypos.add(path.endNode().getProperty(RelReader.CUI_PROPERTY).toString());
    }
    tx.success();
  }
  return hypos;    
}
项目:umls-graph-api    文件:GraphFunctions.java   
public static boolean isa(String cui1, String cui2){
  boolean match=false;
  try ( Transaction tx = graphDb.beginTx() ){
    Node cui1Node = graphDb.findNode(RelReader.DictLabels.Concept, RelReader.CUI_PROPERTY, cui1);
    Node cui2Node = graphDb.findNode(RelReader.DictLabels.Concept, RelReader.CUI_PROPERTY, cui2);
    if(cui1Node == null || cui2Node == null) return match;

    TraversalDescription td = graphDb.traversalDescription()
        .breadthFirst()
        .relationships(RelReader.RelTypes.ISA, Direction.OUTGOING)
        .evaluator(Evaluators.excludeStartPosition())
        .evaluator(Evaluators.includeWhereEndNodeIs(cui2Node));

    Traverser traverser = td.traverse(cui1Node);
    if(traverser.iterator().hasNext()){
      match = true;
    }
    tx.success();
  }
  return match;
}
项目:umls-graph-api    文件:GraphFunctions.java   
public static int minDistance(String cui1, String cui2){
  int distance = -1;
  try ( Transaction tx = graphDb.beginTx() ){
    Node cui1Node = graphDb.findNode(RelReader.DictLabels.Concept, RelReader.CUI_PROPERTY, cui1);
    Node cui2Node = graphDb.findNode(RelReader.DictLabels.Concept, RelReader.CUI_PROPERTY, cui2);
    if(cui1Node == null || cui2Node == null) return distance;

    TraversalDescription td = graphDb.traversalDescription()
        .breadthFirst()
        .relationships(RelReader.RelTypes.ISA, Direction.OUTGOING)
        .evaluator(Evaluators.excludeStartPosition())
        .evaluator(Evaluators.includeWhereEndNodeIs(cui2Node));

    Traverser traverser = td.traverse(cui1Node);
    for(Path path : traverser){
      int len = path.length();
      if(distance == -1 || len < distance){
        distance = len;
      }
    }
    tx.success();
  }
  return distance;
}
项目:umls-graph-api    文件:TestRelReader.java   
@Test
public void testRelReader() throws IOException{

  RelReader reader = new RelReader(neo4jLocation);
  reader.batchBuildGraph(new File("my_test_umls/"), "CtakesAllTuis.txt", "SNOMEDCT_US");
  GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase(new File(neo4jLocation));

  try ( Transaction tx = db.beginTx() ){
    TraversalDescription td = db.traversalDescription()
        .breadthFirst()
        .relationships(RelReader.RelTypes.ISA, Direction.INCOMING)
        .evaluator(Evaluators.excludeStartPosition());

    Node cuiNode = db.findNode(RelReader.DictLabels.Concept, RelReader.CUI_PROPERTY, "C0007102");
    Assert.assertNotNull(cuiNode);
    Traverser traverser = td.traverse(cuiNode);
    for(Path path : traverser){
      System.out.println("At depth " + path.length() + " => " + path.endNode().getProperty("cui"));
    }
  }
  db.shutdown();
}
项目:NeoDD    文件:Propoli.java   
public void traverse() {
    if (null != graph && null != root) {
        try (Transaction tx = graph.beginTx()) {
            PathFinder<Path> finder = GraphAlgoFactory.allPaths(
                    PathExpanders.forTypesAndDirections(RelTypes.CHILD_HI, Direction.OUTGOING, RelTypes.CHILD_LO, Direction.OUTGOING), 5);
            // 5 is the number of original relationships + 1
            Iterable<Path> paths = finder.findAllPaths(root, one);
            double total = 0.0;
            for (Path path : paths) {
                double current = 1.0;
                for (Relationship relationship : path.relationships()) {
                    current *= (double) relationship.getProperty(PROB, 1.0);
                }
                total += current;
            }
            System.out.format("The probability is %.2f.\n", total);
            tx.success();
        }
    }
}
项目:NeoDD    文件:Propoli.java   
public void stamp() {
    if (null != graph && null != root) {
        try (Transaction tx = graph.beginTx()) {
            PathFinder<Path> finder = GraphAlgoFactory.allPaths(
                    PathExpanders.forTypesAndDirections(RelTypes.CHILD_HI, Direction.OUTGOING, RelTypes.CHILD_LO, Direction.OUTGOING), 5);
            // 5 is the number of original relationships + 1
            Iterable<Path> paths = finder.findAllPaths(root, one);
            for (Path path : paths) {
                boolean first = true;
                for (Relationship relationship : path.relationships()) {
                    if (first) {
                        System.out.format("(%s)", relationship.getStartNode().getProperty(ID));
                        first = false;
                    }

                    System.out.format(" --[%s,%.2f]-> ", relationship.getType().name(), relationship.getProperty(PROB, 1.0));
                    System.out.format("(%s)", relationship.getEndNode().getProperty(ID));
                }
                System.out.println();
            }
            tx.success();
        }
    }
}
项目:NeoDD    文件:Application.java   
private void analyseDb() {
    Transaction tx = graphDb.beginTx();
    try {
        PathFinder<Path> finder = GraphAlgoFactory.allPaths(//
                PathExpanders.forTypeAndDirection(RelTypes.KNOWS, Direction.BOTH), -1);
        Iterable<Path> paths = finder.findAllPaths(firstNode, secondNode);
        for (Path path : paths) {
            for (Node node : path.nodes()) {
                for (String prop : node.getPropertyKeys())
                    System.out.print(prop);
                System.out.print(node.toString());
            }

            for (Relationship relationship : path.relationships())
                System.out.print(relationship.toString());
        }
        tx.success();
    } finally {
        tx.finish();
    }
}
项目:NeoDD    文件:BDD.java   
public double traverse() {
    if (null != root && value < 0.0) {
        try (Transaction ignore = graph.beginTx()) {
            value = 0.0;
            PathFinder<Path> finder = GraphAlgoFactory.allPaths(
                    PathExpanders.forTypesAndDirections(RelType.LO_CHILD, Direction.OUTGOING, RelType.HI_CHILD, Direction.OUTGOING), max);
            Iterable<Path> paths = finder.findAllPaths(root, one);
            for (Path path : paths) {
                double current = 1.0;
                for (Relationship relationship : path.relationships()) {
                    current *= (double) relationship.getProperty(PROB, 1.0);
                }
                value += current;
            }
        }
    }
    return value;
}
项目:SPADE    文件:GetChildren.java   
@Override
public Graph execute(Map<String, List<String>> parameters, Integer limit)
{
    String vertexQuery = prepareGetVertexQuery(parameters, limit);
    Result result = (Result) currentStorage.executeQuery(vertexQuery);
    Iterator<Node> nodeSet = result.columnAs(VERTEX_ALIAS);
    Node node;
    if(nodeSet.hasNext())
    {
        // starting point can only be one vertex
        node = nodeSet.next();
    }
    else
        return null;
    Iterable<Relationship> relationships = node.getRelationships(Direction.INCOMING);
    Graph children = new Graph();
    for(Relationship relationship: relationships)
    {
        children.putVertex(convertNodeToVertex(relationship.getEndNode()));
    }


    return children;
}
项目:SPADE    文件:GetParents.java   
@Override
public Graph execute(Map<String, List<String>> parameters, Integer limit)
{
    String vertexQuery = prepareGetVertexQuery(parameters, limit);
    Result result = (Result) currentStorage.executeQuery(vertexQuery);
    Iterator<Node> nodeSet = result.columnAs(VERTEX_ALIAS);
    Node node;
    if(nodeSet.hasNext())
    {
        // starting point can only be one vertex
        node = nodeSet.next();
    }
    else
        return null;
    Iterable<Relationship> relationships = node.getRelationships(Direction.OUTGOING);
    Graph parents = new Graph();
    for(Relationship relationship: relationships)
    {
        parents.putVertex(convertNodeToVertex(relationship.getEndNode()));
    }


    return parents;
}
项目:SPADE    文件:Neo4j.java   
/**
 * This function finds the children of a given vertex.
 * A child is defined as a vertex which is the source of a
 * direct edge between itself and the given vertex.
 *
 * @param parentHash hash of the given vertex
 * @return returns graph object containing children of the given vertex OR NULL.
 */
@Deprecated
@Override
public Graph getChildren(String parentHash)
{
    Graph children = null;
    try (Transaction tx = graphDb.beginTx())
    {
        children = new Graph();
        Node parentNode = graphDb.findNode(NodeTypes.VERTEX, PRIMARY_KEY, parentHash);
        for(Relationship relationship: parentNode.getRelationships(Direction.OUTGOING))
        {
            children.putVertex(convertNodeToVertex(relationship.getEndNode()));
        }
        tx.success();
    }

    return children;
}
项目:SPADE    文件:Neo4j.java   
/**
 * This function finds the parents of a given vertex.
 * A parent is defined as a vertex which is the destination of a
 * direct edge between itself and the given vertex.
 *
 * @param childVertexHash hash of the given vertex
 * @return returns graph object containing parents of the given vertex OR NULL.
 */
@Deprecated
@Override
public Graph getParents(String childVertexHash)
{
    Graph parents = null;
    try (Transaction tx = graphDb.beginTx())
    {
        parents = new Graph();
        Node childNode = graphDb.findNode(NodeTypes.VERTEX, PRIMARY_KEY, childVertexHash);
        for(Relationship relationship: childNode.getRelationships(Direction.INCOMING))
        {
            parents.putVertex(convertNodeToVertex(relationship.getStartNode()));
        }
        tx.success();
    }

    return parents;
}
项目:dnainator    文件:Neo4jSequenceNode.java   
/**
 * Construct a new {@link Neo4jSequenceNode} which wraps the given
 * Neo4j {@link Node}.
 * @param service The Neo4j service, for accessing the database.
 * @param node The Neo4j node.
 */
public Neo4jSequenceNode(GraphDatabaseService service, Node node) {
    loaded = false;

    this.service = service;
    this.node = node;
    this.annotations = new ArrayList<>();
    this.outgoing = new ArrayList<>();
    this.sources = new HashSet<>();
    this.scores = new HashMap<>();

    try (Transaction tx = service.beginTx()) {
        this.id         = (String) node.getProperty(SequenceProperties.ID.name());
        basedist        = (int) node.getProperty(SequenceProperties.BASE_DIST.name());
        interestingness = (int) node.getProperty(SequenceProperties.INTERESTINGNESS.name(), 0);

        node.getRelationships(RelTypes.NEXT, Direction.OUTGOING).forEach(e ->
            outgoing.add((String) e.getEndNode().getProperty(SequenceProperties.ID.name())));
        node.getRelationships(RelTypes.SOURCE, Direction.OUTGOING).forEach(e ->
            sources.add((String) e.getEndNode().getProperty(SourceProperties.SOURCE.name())));

        tx.success();
    }
}
项目:dnainator    文件:Neo4jSequenceNode.java   
private void load() {
    if (loaded) {
        return;
    }

    try (Transaction tx = service.beginTx()) {
        start    = (int)    node.getProperty(SequenceProperties.STARTREF.name());
        end      = (int)    node.getProperty(SequenceProperties.ENDREF.name());
        sequence = (String) node.getProperty(SequenceProperties.SEQUENCE.name());
        rank     = (int)    node.getProperty(SequenceProperties.RANK.name());
        node.getRelationships(RelTypes.ANNOTATED, Direction.OUTGOING).forEach(e ->
                annotations.add(new Neo4jAnnotation(service, e.getEndNode())));
        for (ScoreIdentifier id : Scores.values()) {
            scores.put(id, (Integer) node.getProperty(id.name(), 0));
        }
        tx.success();
    }

    loaded = true;
}
项目:dnainator    文件:Neo4jAnnotation.java   
/**
 * Constructs a new Neo4jAnnotation.
 * @param service the service for accessing the database
 * @param delegate the node to delegate to.
 */
public Neo4jAnnotation(GraphDatabaseService service, Node delegate) {
    try (Transaction tx = service.beginTx()) {
        this.geneName = (String) delegate.getProperty(AnnotationProperties.ID.name());
        this.range = new Range((int) delegate.getProperty(AnnotationProperties.STARTREF.name()),
                (Integer) delegate.getProperty(AnnotationProperties.ENDREF.name()));
        this.isMutation = delegate.hasLabel(NodeLabels.DRMUTATION);
        this.isSense = (Boolean) delegate.getProperty(AnnotationProperties.SENSE.name());
        this.annotatedNodes = new ArrayList<>();
        delegate.getRelationships(Direction.INCOMING, RelTypes.ANNOTATED).forEach(e ->
            annotatedNodes.add(
                (String) e.getStartNode().getProperty(SequenceProperties.ID.name())
            )
        );
        tx.success();
    }
}
项目:dnainator    文件:AnalyzeCommand.java   
/**
 * Rank the destination nodes of the outgoing edges of the given node.
 * @param n the source node of the destination nodes to be ranked.
 */
private void rankDest(Node n) {
    int baseSource = (int) n.getProperty(BASE_DIST.name())
            + (int) n.getProperty(Scores.SEQ_LENGTH.name());
    int rankSource = (int) n.getProperty(RANK.name()) + 1;

    for (Relationship r : n.getRelationships(RelTypes.NEXT, Direction.OUTGOING)) {
        Node dest = r.getEndNode();

        if ((int) dest.getProperty(BASE_DIST.name()) < baseSource) {
            dest.setProperty(BASE_DIST.name(), baseSource);
        }
        if ((int) dest.getProperty(RANK.name()) < rankSource) {
            dest.setProperty(RANK.name(), rankSource);
        }
    }
}
项目:graphalytics-platforms-neo4j    文件:CommunityDetectionLPComputation.java   
private long computeNewLabel(Node node) {
    // Count the frequency of labels at neighbours of the current node
    labelCounts.clear();
    labelCounts.defaultReturnValue(0L);
    for (Relationship relationship : node.getRelationships(EDGE, Direction.BOTH)) {
        long otherLabel = labels.get(relationship.getOtherNode(node));
        labelCounts.put(otherLabel, labelCounts.get(otherLabel) + 1);
    }

    // Find the most frequent label with the lowest id
    long bestLabel = labels.get(node);
    long bestFrequency = 0;
    for (Long2LongMap.Entry labelFrequencyPair : labelCounts.long2LongEntrySet()) {
        long nextLabel = labelFrequencyPair.getLongKey();
        long nextFrequency = labelFrequencyPair.getLongValue();
        if (nextFrequency > bestFrequency) {
            bestLabel = nextLabel;
            bestFrequency = nextFrequency;
        } else if (nextFrequency == bestFrequency && nextLabel < bestLabel) {
            bestLabel = nextLabel;
        }
    }
    return bestLabel;
}
项目:golr-loader    文件:ClosureTest.java   
@Test
public void closures_areReturned() {
  DirectedRelationshipType type = new DirectedRelationshipType(OwlRelationships.RDFS_SUBCLASS_OF, Direction.OUTGOING);
  Set<DirectedRelationshipType> types = newHashSet(type);
  Closure closure = closureUtil.getClosure(c, types);
  assertThat(closure.getCurie(), is("X:c"));
  assertThat(closure.getLabel(), is("C"));
  assertThat(closure.getCuries(), contains("X:c", "X:b", "X:a"));
  assertThat(closure.getLabels(), contains("C", "X:b", "A"));
  closure = closureUtil.getClosure(b, types);
  assertThat(closure.getCurie(), is("X:b"));
  assertThat(closure.getLabel(), is("X:b"));
  assertThat(closure.getCuries(), contains("X:b", "X:a"));
  assertThat(closure.getLabels(), contains("X:b", "A"));
  closure = closureUtil.getClosure(a, types);
  assertThat(closure.getCurie(), is("X:a"));
  assertThat(closure.getLabel(), is("A"));
  assertThat(closure.getCuries(), contains("X:a"));
  assertThat(closure.getLabels(), contains("A"));
}
项目:welshare    文件:ViralLinkDaoNeo4j.java   
@Override
public ViralShortUrl getLink(String key) {
    Node node = index.getSingleNode(KEY, key);
    if (node == null) {
        return null;
    }
    ViralShortUrl url = new ViralShortUrl();
    if (node.hasProperty(INITIAL_KEY)) {
        Node initialNode = index.getSingleNode(KEY, node.getProperty(INITIAL_KEY));
        url.setLongUrl((String) initialNode.getProperty(LONG_URL));
    } else {
        url.setLongUrl((String) node.getProperty(LONG_URL));
    }
    url.setKey(key);
    url.setShowTopBar(true);
    url.setTrackViral(true);
    Iterator<Relationship> relationshipIterator = node.getRelationships(LinkRelationship.SPAWNS, Direction.INCOMING).iterator();
    if (relationshipIterator.hasNext()) {
        url.setTimeAdded(new DateTime(relationshipIterator.next().getProperty(CREATED)));
    }

    fillUrlData(node, url);
    return url;
}
项目:trainbenchmark    文件:Neo4JApiQuerySemaphoreNeighborInject.java   
@Override
public Collection<Neo4jSemaphoreNeighborInjectMatch> evaluate() {
    final Collection<Neo4jSemaphoreNeighborInjectMatch> matches = new ArrayList<>();

    final GraphDatabaseService graphDb = driver.getGraphDb();
    try (Transaction tx = graphDb.beginTx()) {
        // (route:Route)
        final Iterable<Node> routes = () -> graphDb.findNodes(Neo4jConstants.labelRoute);
        for (final Node route : routes) {
            Iterable<Relationship> entries = route.getRelationships(Direction.OUTGOING, Neo4jConstants.relationshipTypeEntry);

            for (Relationship entry : entries) {
                final Node semaphore = entry.getEndNode();

                final Map<String, Object> match = new HashMap<>();
                match.put(QueryConstants.VAR_ROUTE, route);
                match.put(QueryConstants.VAR_SEMAPHORE, semaphore);
                matches.add(new Neo4jSemaphoreNeighborInjectMatch(match));
            }
        }
    }

    return matches;
}
项目:trainbenchmark    文件:Neo4JApiQueryRouteSensorInject.java   
@Override
public Collection<Neo4jRouteSensorInjectMatch> evaluate() {
    final Collection<Neo4jRouteSensorInjectMatch> matches = new ArrayList<>();

    final GraphDatabaseService graphDb = driver.getGraphDb();
    try (Transaction tx = graphDb.beginTx()) {
        // (route:Route)
        final Iterable<Node> routes = () -> graphDb.findNodes(Neo4jConstants.labelRoute);
        for (final Node route : routes) {

            final Iterable<Node> sensors = Neo4jUtil.getAdjacentNodes(route, Neo4jConstants.relationshipTypeRequires,
                    Direction.OUTGOING, Neo4jConstants.labelSensor);

            for (final Node sensor : sensors) {
                final Map<String, Object> match = new HashMap<>();
                match.put(QueryConstants.VAR_ROUTE, route);
                match.put(QueryConstants.VAR_SENSOR, sensor);
                matches.add(new Neo4jRouteSensorInjectMatch(match));
            }
        }
    }

    return matches;
}
项目:trainbenchmark    文件:Neo4jUtil.java   
public static Iterable<Node> getAdjacentNodes(final Node sourceNode, final RelationshipType relationshipType, final Direction direction, final Label targetNodeLabel) {
    final Collection<Node> nodes = new ArrayList<>();

    final Iterable<Relationship> relationships = sourceNode.getRelationships(relationshipType, direction);
    for (final Relationship relationship : relationships) {
        final Node candidate;
        switch (direction) {
        case INCOMING:
            candidate = relationship.getStartNode();
            break;
        case OUTGOING:
            candidate = relationship.getEndNode();          
            break;
        default:
            throw new UnsupportedOperationException("Direction: " + direction + " not supported.");
        }
        if (!candidate.hasLabel(targetNodeLabel)) {
            continue;
        }
        nodes.add(candidate);
    }
    return nodes;
}
项目:trainbenchmark    文件:Neo4jApiTransformationInjectConnectedSegments.java   
@Override
public void activate(final Collection<Neo4jConnectedSegmentsInjectMatch> matches) {
    for (final Neo4jConnectedSegmentsInjectMatch match : matches) {
        // create (segment2) node
        final Node segment2 = driver.getGraphDb().createNode(Neo4jConstants.labelSegment);
        segment2.setProperty(ModelConstants.ID, driver.generateNewVertexId());
        segment2.setProperty(ModelConstants.LENGTH, TrainBenchmarkConstants.DEFAULT_SEGMENT_LENGTH);

        // (segment2)-[:monitoredBy]->(sensor)
        segment2.createRelationshipTo(match.getSensor(), Neo4jConstants.relationshipTypeMonitoredBy);

        // (segment1)-[:connectsTo]->(segment2)
        match.getSegment1().createRelationshipTo(segment2, Neo4jConstants.relationshipTypeConnectsTo);
        // (segment2)-[:connectsTo]->(segment3)
        segment2.createRelationshipTo(match.getSegment3(), Neo4jConstants.relationshipTypeConnectsTo);

        // remove (segment1)-[:connectsTo]->(segment3)
        final Iterable<Relationship> connectsToEdges = match.getSegment1().getRelationships(Direction.OUTGOING,
                Neo4jConstants.relationshipTypeConnectsTo);
        for (final Relationship connectsToEdge : connectsToEdges) {
            if (connectsToEdge.getEndNode().equals(match.getSegment3())) {
                connectsToEdge.delete();
            }
        }
    }
}
项目:neo4jena    文件:UniqueRelationshipFactory.java   
/**
 * Finds relationship of given type between subject and object nodes.
 * 
 * @return Relationship if exists or null.
 */
public Relationship get(Node subject, RelationshipType type, Node object) {
    try {
        // FIXME Use relationship index instead of iterating over all relationships
        Iterable<Relationship> relations = subject.getRelationships(Direction.OUTGOING, type);
        for(Relationship relation: relations) {
            org.neo4j.graphdb.Node target = relation.getEndNode();
            // Match object with target node in the existing triple
            Iterable<Label> labels = object.getLabels();
            for(Label label:labels) {
                if(label.name().equals(NeoGraph.LABEL_LITERAL)) {
                    // Match literal value of object and target in existing triple
                    if(object.getProperty(NeoGraph.PROPERTY_VALUE).equals(target.getProperty(NeoGraph.PROPERTY_VALUE)))
                        return relation;
                    else return null;
                }
            }
            // Now match URI of object and target in existing triple
            // FIXME Blank Nodes?
            if(object.getProperty(NeoGraph.PROPERTY_URI).equals(target.getProperty(NeoGraph.PROPERTY_URI)))
                return relation;
        }
    } catch(RuntimeException exception) { }
    return null;
}
项目:maven-embedded-neo4j-archetype    文件:Neo4jEmbeddedExample.java   
public String helloWorldTraversal() {
    StringBuilder values = new StringBuilder();
    try (Transaction tx = graphDatabaseService.beginTx()) {
        Node startNode = graphDatabaseService.findNode(Label.label("Word"), "value", "Hello");
        for (Node node : graphDatabaseService.traversalDescription()
                .depthFirst()
                .expand(forTypeAndDirection(withName("IS_FOLLOWED_BY"), Direction.OUTGOING))
                .evaluator(toDepth(2))
                .traverse(startNode)
                .nodes()) {

            values.append(String.valueOf(node.getProperty("value")));
            values.append(" ");
        }
        tx.success();
    }
    return values.substring(0, values.length() - 1);
}
项目:SciGraph    文件:CategoryProcessor.java   
@Override
public Map<String, Set<Long>> call() throws Exception {
  logger.info("Processsing " + category);
  Map<String, Set<Long>> map = new HashMap<String, Set<Long>>();
  Set<Long> nodeSet = new HashSet<Long>();
  Transaction tx = graphDb.beginTx();
  try {
    for (Path position : graphDb.traversalDescription().uniqueness(Uniqueness.NODE_GLOBAL).depthFirst()
        .relationships(OwlRelationships.RDFS_SUBCLASS_OF, Direction.INCOMING).relationships(OwlRelationships.RDF_TYPE, Direction.INCOMING)
        .relationships(OwlRelationships.OWL_EQUIVALENT_CLASS, Direction.BOTH).relationships(OwlRelationships.OWL_SAME_AS, Direction.BOTH)
        .traverse(root)) {
      Node end = position.endNode();
      nodeSet.add(end.getId());
    }
    logger.info("Discovered " + nodeSet.size() + " nodes for " + category);
    map.put(category, nodeSet);
  } catch (Exception e) {
    logger.warning("IRI not found for category: " + category);
  } finally {
    tx.success();
    tx.close();
  }
  return map;
}
项目:SciGraph    文件:OwlPostprocessor.java   
long processCategory(Node root, RelationshipType type, Direction direction, String category) {
  long count = 0;
  int batchSize = 100_000;
  Label label = Label.label(category);
  Transaction tx = graphDb.beginTx();
  for (Path position : graphDb.traversalDescription().uniqueness(Uniqueness.NODE_GLOBAL)
      .depthFirst().relationships(type, direction)
      .relationships(OwlRelationships.RDF_TYPE, Direction.INCOMING)
      .relationships(OwlRelationships.OWL_EQUIVALENT_CLASS, Direction.BOTH).traverse(root)) {
    Node end = position.endNode();
    GraphUtil.addProperty(end, Concept.CATEGORY, category);
    end.addLabel(label);
    if (0 == ++count % batchSize) {
      logger.fine("Commiting " + count);
      tx.success();
      tx.close();
      tx = graphDb.beginTx();
    }
  }
  tx.success();
  tx.close();
  return count;
}
项目:SplitCharater    文件:DbManager.java   
public String knowsLikesTraverser( Node node )
{
    String output = "";
    // START SNIPPET: knowslikestraverser
    for ( Path position : db.traversalDescription()
            .depthFirst()
            .relationships( Rels.KNOWS )
            .relationships( Rels.LIKES, Direction.INCOMING )
            .evaluator( Evaluators.toDepth( 5 ) )
            .traverse( node ) )
    {
        output += position + "\n";
    }
    // END SNIPPET: knowslikestraverser
    return output;
}