org.neo4j.graphdb.Direction Java Examples

The following examples show how to use org.neo4j.graphdb.Direction. 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: DeepWalkProc.java    From ml-models with Apache License 2.0 6 votes vote down vote up
private Graph load(
        String label,
        String relationship,
        AllocationTracker tracker,
        Class<? extends GraphFactory> graphFactory,
        PageRankScore.Stats.Builder statsBuilder, ProcedureConfiguration configuration) {
    GraphLoader graphLoader = new GraphLoader(api, Pools.DEFAULT)
            .init(log, label, relationship, configuration)
            .withAllocationTracker(tracker)
            .withDirection(configuration.getDirection(Direction.BOTH))
            .withoutNodeProperties()
            .withoutNodeWeights()
            .withoutRelationshipWeights();


    try (ProgressTimer timer = ProgressTimer.start()) {
        Graph graph = graphLoader.load(graphFactory);
        statsBuilder.withNodes(graph.nodeCount());
        return graph;
    }
}
 
Example #2
Source File: Neo4jApiTransformationInjectConnectedSegments.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
@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();
			}
		}
	}
}
 
Example #3
Source File: Neo4jUtil.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example #4
Source File: ReadOptimizedGraphity.java    From metalcon with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean removeFriendship(final Node following, final Node followed) {
	// find the replica node of the user followed
	Node followedReplica = null;
	for (Relationship followship : following.getRelationships(
			SocialGraphRelationshipType.FOLLOW, Direction.OUTGOING)) {
		followedReplica = followship.getEndNode();
		if (NeoUtils.getNextSingleNode(followedReplica,
				SocialGraphRelationshipType.REPLICA).equals(followed)) {
			break;
		}
		followedReplica = null;
	}

	// there is no such followship existing
	if (followedReplica == null) {
		return false;
	}

	this.removeFromReplicaLayer(followedReplica);
	return true;
}
 
Example #5
Source File: Neo4JApiQueryRouteSensorInject.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
@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;
}
 
Example #6
Source File: Neo4JApiQuerySemaphoreNeighborInject.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
@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;
}
 
Example #7
Source File: UniqueRelationshipFactory.java    From neo4jena with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #8
Source File: CategoryProcessor.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #9
Source File: Traversals.java    From EvilCoder with MIT License 6 votes vote down vote up
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;
}
 
Example #10
Source File: DeepGL.java    From ml-models with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    for (; ; ) {
        final int nodeId = nodeQueue.getAndIncrement();
        if (nodeId >= nodeCount || !running()) {
            return;
        }

        List<Integer> neighbours = new LinkedList<>();
        graph.forEachRelationship(nodeId, Direction.BOTH, (sourceNodeId, targetNodeId, relationId) -> {
            neighbours.add(targetNodeId);
            return true;
        });

        final INDArray oldVals = ndDiffused.getRows(ArrayUtils.toPrimitive(neighbours.toArray(new Integer[0])));
        ndDiffusedTemp.putRow(nodeId, oldVals.mean(0));
    }
}
 
Example #11
Source File: DeepGL.java    From ml-models with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    for (; ; ) {
        final int nodeId = nodeQueue.getAndIncrement();
        if (nodeId >= nodeCount || !running()) {
            return;
        }

        Set<String> nodeProperties = graph.availableNodeProperties();

        double[] row = new double[3 + nodeProperties.size()];
        row[0] = graph.degree(nodeId, Direction.INCOMING);
        row[1] = graph.degree(nodeId, Direction.OUTGOING);
        row[2] = graph.degree(nodeId, Direction.BOTH);

        Iterator<String> iterator = nodeProperties.iterator();
        int counter = 3;

        while (iterator.hasNext()) {
            row[counter] = graph.nodeProperties(iterator.next()).get(nodeId);
            counter++;
        }

        embedding.putRow(nodeId, Nd4j.create(row));
    }
}
 
Example #12
Source File: DeepGLProc.java    From ml-models with Apache License 2.0 5 votes vote down vote up
@Procedure(value = "embedding.deepgl.stream")
public Stream<DeepGL.Result> deepGLStream(
        @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.1);

    final HeavyGraph graph = (HeavyGraph) new GraphLoader(api, Pools.DEFAULT)
            .init(log, label, relationship, configuration)
            .withoutNodeProperties()
            .withDirection(configuration.getDirection(Direction.BOTH))
            .withOptionalNodeProperties(extractNodeFeatures(config))
            .load(configuration.getGraphImpl());

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

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

    algo.compute();
    graph.release();

    return algo.resultStream();
}
 
Example #13
Source File: Neo4jApiTransformationRepairSemaphoreNeighbor.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void activate(final Collection<Neo4jSemaphoreNeighborMatch> matches) {
	for (final Neo4jSemaphoreNeighborMatch match : matches) {
		final Node semaphore = match.getSemaphore();
		final Node route2 = match.getRoute2();
		if (!route2.hasRelationship(Direction.OUTGOING, Neo4jConstants.relationshipTypeEntry)) {
			route2.createRelationshipTo(semaphore, Neo4jConstants.relationshipTypeEntry);
		}
	}
}
 
Example #14
Source File: TestGCISubClassOf.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@Test
public void testSubclassBlankNodeFiller() {
  Relationship r = getOnlyElement(subclass.getRelationships(Direction.INCOMING, OwlRelationships.FILLER));
  Node blankNode1 = r.getOtherNode(subclass);
  assertThat(blankNode1.hasLabel(OwlLabels.OWL_ANONYMOUS), is(true));
  r = getOnlyElement(blankNode1.getRelationships(Direction.OUTGOING, OwlRelationships.RDFS_SUBCLASS_OF));
  Node blankNode2 = r.getOtherNode(blankNode1);
  assertThat(blankNode2.hasLabel(OwlLabels.OWL_ANONYMOUS), is(true));
  r = getOnlyElement(blankNode1.getRelationships(Direction.OUTGOING, p));
  assertThat(r.getOtherNode(blankNode1), is(superclass));
}
 
Example #15
Source File: GraphApiNeighborhoodTest.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@Test
public void multipleAncestors_areReturned() {
  Graph graph = graphApi.getNeighbors(newHashSet(i), 10,
      newHashSet(new DirectedRelationshipType(OwlRelationships.RDFS_SUBCLASS_OF, Direction.OUTGOING)), absent);
  assertThat(graph.getVertices(), IsIterableWithSize.<Vertex>iterableWithSize(4));
  assertThat(graph.getEdges(), IsIterableWithSize.<Edge>iterableWithSize(4));
}
 
Example #16
Source File: StatusUpdateTemplate.java    From metalcon with GNU General Public License v3.0 5 votes vote down vote up
/**
 * create a new status update template from a neo4j node
 * 
 * @param templateNode
 *            neo4j template node
 */
public StatusUpdateTemplate(final org.neo4j.graphdb.Node templateNode) {
	// read template information
	this.name = (String) templateNode
			.getProperty(Properties.Templates.IDENTIFIER);
	this.version = (String) templateNode
			.getProperty(Properties.Templates.VERSION);
	this.javaCode = (String) templateNode
			.getProperty(Properties.Templates.CODE);
	this.fields = new HashMap<String, TemplateFieldInfo>();
	this.files = new HashMap<String, TemplateFileInfo>();

	// read template field items
	TemplateFieldInfo fieldInfo;
	for (Relationship field : templateNode
			.getRelationships(SocialGraphRelationshipType.Templates.FIELD,
					Direction.OUTGOING)) {
		fieldInfo = new TemplateFieldInfo(field.getEndNode());
		this.fields.put(fieldInfo.getName(), fieldInfo);
	}

	// read template file items
	TemplateFileInfo fileInfo;
	for (Relationship file : templateNode.getRelationships(
			SocialGraphRelationshipType.Templates.FILE, Direction.OUTGOING)) {
		fileInfo = new TemplateFileInfo(file.getEndNode());
		this.files.put(fileInfo.getName(), fileInfo);
	}
}
 
Example #17
Source File: Neo4jGraphDatabase.java    From graphdb-benchmarks with Apache License 2.0 5 votes vote down vote up
@Override
public double getEdgesInsideCommunity(int nodeCommunity, int communityNodes)
{
    double edges = 0;
    try (final Transaction tx = beginUnforcedTransaction())
    {
        try
        {
            ResourceIterable<Node> nodes = neo4jGraph.findNodesByLabelAndProperty(NODE_LABEL, NODE_COMMUNITY,
                nodeCommunity);
            ResourceIterable<Node> comNodes = neo4jGraph.findNodesByLabelAndProperty(NODE_LABEL, COMMUNITY,
                communityNodes);
            for (Node node : nodes)
            {
                Iterable<Relationship> relationships = node.getRelationships(RelTypes.SIMILAR, Direction.OUTGOING);
                for (Relationship r : relationships)
                {
                    Node neighbor = r.getOtherNode(node);
                    if (Iterables.contains(comNodes, neighbor))
                    {
                        edges++;
                    }
                }
            }
            tx.success();
        }
        catch (Exception e)
        {
            tx.failure();
            throw new BenchmarkingException("unable to get edges inside community", e);
        }
    }

    return edges;
}
 
Example #18
Source File: PageRankArrayStorageParallelSPI.java    From graph_processing with MIT License 5 votes vote down vote up
private int[] computeDegrees(ReadOperations ops, int labelId, int relationshipId) throws EntityNotFoundException {
    int[] degree = new int[nodeCount];
    Arrays.fill(degree,-1);
    PrimitiveLongIterator it = ops.nodesGetForLabel(labelId);
    int totalCount = nodeCount;
    runOperations(pool, it, totalCount, ops, new OpsRunner() {
        public void run(int id) throws EntityNotFoundException {
            degree[id] = ops.nodeGetDegree(id, Direction.OUTGOING, relationshipId);
        }
    });
    return degree;
}
 
Example #19
Source File: DegreeArrayStorageParallelSPI.java    From graph_processing with MIT License 5 votes vote down vote up
public DegreeArrayStorageParallelSPI(GraphDatabaseService db, ExecutorService pool, Direction direction) {
    this.pool = pool;
    this.db = (GraphDatabaseAPI)db;
    this.nodeCount = new NodeCounter().getNodeCount(db);
    this.direction = direction;
    if (!direction.equals(Direction.BOTH)) {
        directionName = direction.name().toLowerCase() + "_";
    }
}
 
Example #20
Source File: Utils.java    From graph_processing with MIT License 5 votes vote down vote up
public static SingleSourceShortestPath<Double> getSingleSourceShortestPath(RelationshipType relationshipType)
{
    return new SingleSourceShortestPathDijkstra<Double>( 0.0, null,
            new CostEvaluator<Double>()
            {
                public Double getCost( Relationship relationship,
                                       Direction direction )
                {
                    return 1.0;
                }
            }, new org.neo4j.graphalgo.impl.util.DoubleAdder(),
            new org.neo4j.graphalgo.impl.util.DoubleComparator(),
            Direction.BOTH, relationshipType );
}
 
Example #21
Source File: DegreeCentralityTest.java    From graph_processing with MIT License 5 votes vote down vote up
@Test
public void shouldCalculateInDegreeCentralityArrayStorageSPI() throws IOException {
    DegreeArrayStorageParallelSPI inDegree = new DegreeArrayStorageParallelSPI(db, pool, Direction.INCOMING);
    inDegree.compute("Movie", "ACTED_IN", 1);
    long id = (long) getMovieEntry("The Matrix", db).get("id");
    assertTrue("InDegree Centrality calculted incorrectly", 5 == inDegree.getResult(id));
}
 
Example #22
Source File: DegreeCentralityTest.java    From graph_processing with MIT License 5 votes vote down vote up
@Test
public void shouldCalculateOutDegreeCentralityArrayStorageSPI() throws IOException {
    DegreeArrayStorageParallelSPI outDegree = new DegreeArrayStorageParallelSPI(db, pool, Direction.OUTGOING);
    outDegree.compute("Person", "ACTED_IN", 1);
    long id = (long) getPersonEntry("Tom Hanks", db).get("id");
    assertTrue("outDegree Centrality calculted incorrectly", 12 == outDegree.getResult(id));
}
 
Example #23
Source File: DegreeCentralityTest.java    From graph_processing with MIT License 5 votes vote down vote up
@Test
public void shouldCalculateDegreeCentralityArrayStorageSPI() throws IOException {
    DegreeArrayStorageParallelSPI degree = new DegreeArrayStorageParallelSPI(db, pool, Direction.BOTH);
    degree.compute("Person", "ACTED_IN", 1);
    long id = (long) TestUtils.getPersonEntry("Tom Hanks", db).get("id");
    assertTrue("outDegree Centrality calculted incorrectly", 12 == degree.getResult(id));
}
 
Example #24
Source File: TestInferredEdges.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@Test
public void testInferredEdges() {
  Node cx = getNode("http://example.org/cx");
  Node dx = getNode("http://example.org/dx");

  Iterable<Relationship> superclasses = dx.getRelationships(OwlRelationships.RDFS_SUBCLASS_OF, Direction.OUTGOING);
  Relationship r = getOnlyElement(superclasses);
  assertThat("A subclassOf relationship is introduced.    ", r.getOtherNode(dx), is(cx));
}
 
Example #25
Source File: Neo4jGraphDatabase.java    From graphdb-benchmarks with Apache License 2.0 5 votes vote down vote up
@Override
public Set<Integer> getCommunitiesConnectedToNodeCommunities(int nodeCommunities)
{
    Set<Integer> communities = new HashSet<Integer>();
    try (final Transaction tx = beginUnforcedTransaction())
    {
        try
        {
            ResourceIterable<Node> nodes = neo4jGraph.findNodesByLabelAndProperty(Neo4jGraphDatabase.NODE_LABEL,
                NODE_COMMUNITY, nodeCommunities);
            for (Node n : nodes)
            {
                for (Relationship r : n.getRelationships(RelTypes.SIMILAR, Direction.OUTGOING))
                {
                    Node neighbour = r.getOtherNode(n);
                    Integer community = (Integer) (neighbour.getProperty(COMMUNITY));
                    communities.add(community);
                }
            }
            tx.success();
        }
        catch (Exception e)
        {
            tx.failure();
            throw new BenchmarkingException("unable to get communities connected to node communities", e);
        }
    }

    return communities;
}
 
Example #26
Source File: ReadOptimizedGraphity.java    From metalcon with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean deleteStatusUpdate(final Node user, final Node statusUpdate) {
	// get the status update owner
	final Node statusUpdateAuthor = NeoUtils.getPrevSingleNode(
			statusUpdate, SocialGraphRelationshipType.UPDATE);

	// the status update is not owned by the user passed
	if (!user.equals(statusUpdateAuthor)) {
		return false;
	}

	// update ego network
	this.updateReplicaLayerStatusUpdateDeletion(user, statusUpdate);

	// remove reference from previous status update
	final Node previousUpdate = NeoUtils.getPrevSingleNode(statusUpdate,
			SocialGraphRelationshipType.UPDATE);
	previousUpdate.getSingleRelationship(
			SocialGraphRelationshipType.UPDATE, Direction.OUTGOING)
			.delete();

	// update references to the next status update (if existing)
	final Node nextUpdate = NeoUtils.getNextSingleNode(statusUpdate,
			SocialGraphRelationshipType.UPDATE);
	if (nextUpdate != null) {
		statusUpdate.getSingleRelationship(
				SocialGraphRelationshipType.UPDATE, Direction.OUTGOING)
				.delete();
		previousUpdate.createRelationshipTo(nextUpdate,
				SocialGraphRelationshipType.UPDATE);
	}

	// delete the status update node
	statusUpdate.delete();
	return true;
}
 
Example #27
Source File: DataRelationshipManager.java    From graphify with Apache License 2.0 5 votes vote down vote up
public void getOrCreateNode(Long start, Long end, GraphDatabaseService db) {
    List<Long> relList = relationshipCache.getIfPresent(start);

    Node startNode = db.getNodeById(start);

    if (relList == null) {
        List<Long> nodeList = new ArrayList<>();
        for(Node endNodes : db.traversalDescription()
                .depthFirst()
                .relationships(withName(relationshipType), Direction.OUTGOING)
                .evaluator(Evaluators.fromDepth(1))
                .evaluator(Evaluators.toDepth(1))
                .traverse(startNode)
                .nodes())
        {
            nodeList.add(endNodes.getId());
        }

        relList = nodeList;
        relationshipCache.put(start, relList);
    }

    if (!relList.contains(end)) {
        Transaction tx = db.beginTx();
        try {
            Node endNode = db.getNodeById(end);
            startNode.createRelationshipTo(endNode, withName(relationshipType));
            tx.success();
        } catch (final Exception e) {
            tx.failure();
        } finally {
            tx.close();
            relList.add(end);
            relationshipCache.put(start, relList);
        }
    }
}
 
Example #28
Source File: ReadOptimizedGraphity.java    From metalcon with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void createStatusUpdate(final long timestamp, final Node user,
		final StatusUpdate content) {
	// get last recent status update
	final Node lastUpdate = NeoUtils.getNextSingleNode(user,
			SocialGraphRelationshipType.UPDATE);

	// create new status update node
	final Node crrUpdate = NeoUtils.createStatusUpdateNode(content.getId());

	// prepare status update for JSON parsing
	content.setTimestamp(timestamp);
	content.setCreator(new User(user));

	// fill status update node
	crrUpdate.setProperty(Properties.StatusUpdate.TIMESTAMP, timestamp);
	crrUpdate.setProperty(Properties.StatusUpdate.CONTENT_TYPE,
			content.getType());
	crrUpdate.setProperty(Properties.StatusUpdate.CONTENT, content
			.toJSONObject().toJSONString());

	// update references to previous status update (if existing)
	if (lastUpdate != null) {
		user.getSingleRelationship(SocialGraphRelationshipType.UPDATE,
				Direction.OUTGOING).delete();
		crrUpdate.createRelationshipTo(lastUpdate,
				SocialGraphRelationshipType.UPDATE);
	}

	// add reference from user to current update node
	user.createRelationshipTo(crrUpdate, SocialGraphRelationshipType.UPDATE);
	user.setProperty(Properties.User.LAST_UPDATE, timestamp);

	// update ego network for this user
	this.updateEgoNetwork(user);
}
 
Example #29
Source File: StoreGraphDependencyMojo.java    From maven-dependency-mapper with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void getDependencies() {
    Node projectNode = makeNode(project.getArtifact());
    for(Relationship r:projectNode.getRelationships(Direction.OUTGOING)){
        r.delete();
    }
    if (project.getParentArtifact() != null) {
        registerDependency("parent", projectNode, project.getParentArtifact());
    }
    registerDependencies(project.getDependencies());
}
 
Example #30
Source File: ReachabilityEvaluator.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
ReachabilityEvaluator(InMemoryReachabilityIndex inMemoryIdx,
    Direction direction,
    Predicate<Node> nodePredicate) {
  this.inMemoryIndex = inMemoryIdx;
  this.direction = direction;
  this.nodePredicate = nodePredicate;
}