org.neo4j.graphdb.Relationship Java Examples

The following examples show how to use org.neo4j.graphdb.Relationship. 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: TestPun.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
@Test
public void testPun() {
  Node i = getNode("http://example.org/i");
  Node j = getNode("http://example.org/j");
  Node k = getNode("http://example.org/k");

  RelationshipType p = RelationshipType.withName("http://example.org/p");
  Relationship relationship = getOnlyElement(GraphUtil.getRelationships(i, j, p));
  assertThat("OPE edge should start with the subject.", relationship.getStartNode(), is(i));
  assertThat("OPE edge should end with the target.", relationship.getEndNode(), is(j));
  relationship = getOnlyElement(GraphUtil.getRelationships(i, k, OwlRelationships.RDFS_SUBCLASS_OF));
  assertThat("Subclass edge should start with i.", relationship.getStartNode(), is(i));
  assertThat("Subclass edge should end with k.", relationship.getEndNode(), is(k));
  assertThat("i is both a class an a named individual" , i.getLabels(), 
      is(IsIterableContainingInAnyOrder.containsInAnyOrder(OwlLabels.OWL_CLASS, OwlLabels.OWL_NAMED_INDIVIDUAL)));
}
 
Example #2
Source File: TestSubClassOfExistential.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
/**
 * See https://github.com/SciCrunch/SciGraph/wiki/MappingToOWL#subclassof-axioms
 * 
 * Reduction step should give us a simple edge {sub p super}
 */
@Test
public void testSubclass() {
  Node subclass = getNode("http://example.org/subclass");
  Node superclass = getNode("http://example.org/superclass");

  RelationshipType p = RelationshipType.withName("http://example.org/p");
  Relationship relationship = getOnlyElement(GraphUtil.getRelationships(subclass, superclass, p));
  assertThat("subclassOf relationship should start with the subclass.",
      relationship.getStartNode(), is(subclass));
  assertThat("subclassOf relationship should end with the superclass.",
      relationship.getEndNode(), is(superclass));
  assertThat("relationship has the correct iri",
      GraphUtil.getProperty(relationship, CommonProperties.IRI, String.class),
      is(Optional.of("http://example.org/p")));
  assertThat("relationship is asserted",
      GraphUtil.getProperty(relationship, CommonProperties.CONVENIENCE, Boolean.class),
      is(Optional.of(true)));
  assertThat("owltype is added",
      GraphUtil.getProperty(relationship, CommonProperties.OWL_TYPE, String.class),
      is(Optional.of(OwlRelationships.RDFS_SUBCLASS_OF.name())));
}
 
Example #3
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 #4
Source File: GraphTransactionalImpl.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
@Override
public long createRelationship(long start, long end, RelationshipType type) {
  Optional<Long> relationshipId = getRelationship(start, end, type);

  if (relationshipId.isPresent()) {
    return relationshipId.get();
  } else {
    try (Transaction tx = graphDb.beginTx()) {
      Node startNode = graphDb.getNodeById(start);
      Node endNode = graphDb.getNodeById(end);
      Relationship relationship;
      synchronized (graphLock) {
        relationship = startNode.createRelationshipTo(endNode, type);
        relationshipMap.put(start, end, type, relationship.getId());
      }
      tx.success();
      return relationship.getId();
    }
  }
}
 
Example #5
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 #6
Source File: NeoGraph.java    From neo4jena with Apache License 2.0 6 votes vote down vote up
/**
 * Checks if the given triple exist in the graph.
 */
@Override
public boolean contains(Node subject, Node predicate, Node object) {
	try(Transaction tx = graphdb.beginTx()) {
		// Check subject
		org.neo4j.graphdb.Node sub= nodeFactory.get(subject);
		if(sub!=null) {
			// Check object
			org.neo4j.graphdb.Node obj = nodeFactory.get(object);
			if(obj!=null) {
				// Check relationship
				Relationship relation = relationshipFactory.get(sub, predicate.getURI(), obj);
				if(relation!=null) {
					tx.success();
					return true;
				}
			}
		}
	}
	return false;
}
 
Example #7
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 #8
Source File: GraphBatchImplMultipleLoadTest.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipleInserts() throws IOException {
  Graph batchGraph = getBatchGraph();
  long a = batchGraph.createNode("a");
  long b = batchGraph.createNode("b");
  batchGraph.createRelationship(a, b, TYPE);
  batchGraph.shutdown();
  batchGraph = getBatchGraph();
  a = batchGraph.createNode("a");
  long c = batchGraph.createNode("c");
  batchGraph.createRelationship(a, c, TYPE);
  batchGraph.shutdown();
  GraphDatabaseService graphDb = getGraphDB();
  try (Transaction tx = graphDb.beginTx()) {
    Iterable<Node> nodes = graphDb.getAllNodes();
    assertThat(size(nodes), is(3));
    Iterable<Relationship> relationships = graphDb.getAllRelationships();
    assertThat(size(relationships), is(2));
    tx.success();
  }
}
 
Example #9
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 #10
Source File: NeoUtils.java    From metalcon with GNU General Public License v3.0 5 votes vote down vote up
/**
 * find an outgoing relation from the user passed of the specified type
 * 
 * @param user
 *            source user node
 * @param relType
 *            relationship type of the relation being searched
 * @return node targeted by the relation<br>
 *         null - if there is no relation of the type specified
 */
public static Node getNextSingleNode(final Node user,
		RelationshipType relationshipType) {
	// find an outgoing relation of the type specified
	Relationship rel = null;
	try {
		rel = user.getSingleRelationship(relationshipType,
				Direction.OUTGOING);
	} catch (final NonWritableChannelException e) {
		// TODO: why is this here? Bug for read-only databases in previous
		// version?
	}

	return (rel == null) ? (null) : (rel.getEndNode());
}
 
Example #11
Source File: TestSubObjectPropertyChainOf.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@Test
public void testSubclass() {
  Node p1 = getNode("http://example.org/p1");
  Node p2 = getNode("http://example.org/p2");
  Node p3 = getNode("http://example.org/p3");

  Relationship first = getOnlyElement(GraphUtil.getRelationships(p3, p1,
      OwlRelationships.OWL_PROPERTY_CHAIN_AXIOM));
  assertThat(GraphUtil.getProperty(first, "order", Integer.class), is(Optional.of(0)));
  Relationship second = getOnlyElement(GraphUtil.getRelationships(p3, p2,
      OwlRelationships.OWL_PROPERTY_CHAIN_AXIOM));
  assertThat(GraphUtil.getProperty(second, "order", Integer.class), is(Optional.of(1)));
}
 
Example #12
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 #13
Source File: TestObjectPropertyAssertion.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@Test
public void testObjectPropertyAssertion() {
  Node i = getNode("http://example.org/i");
  Node j = getNode("http://example.org/j");

  RelationshipType p = RelationshipType.withName("http://example.org/p");
  Relationship relationship = getOnlyElement(GraphUtil.getRelationships(i, j, p));
  assertThat("OPE edge should start with the subject.", relationship.getStartNode(), is(i));
  assertThat("OPE edge should start with the target.", relationship.getEndNode(), is(j));
}
 
Example #14
Source File: TinkerGraphUtilTest.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
Relationship mockRealtionship(Node start, Node end) {
  Relationship r = mock(Relationship.class);
  when(r.getPropertyKeys()).thenReturn(Collections.<String>emptySet());
  when(r.getType()).thenReturn(RelationshipType.withName("FOO"));
  when(r.getStartNode()).thenReturn(start);
  when(r.getEndNode()).thenReturn(end);
  return r;
}
 
Example #15
Source File: TestSubAnnotationPropertyOf.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@Test
public void testSubclass() {
  Node subp = getNode("http://example.org/subproperty");
  Node superp = getNode("http://example.org/superproperty");
  assertThat("subclass should be a directed relationship",
      GraphUtil.getRelationships(subp, superp, OwlRelationships.RDFS_SUB_PROPERTY_OF),
      is(IsIterableWithSize.<Relationship> iterableWithSize(1)));
}
 
Example #16
Source File: EdgeLabelerTest.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@Test
public void edgeWithNodeIsTaggedWithType() {
  Relationship rel =
      n1.getRelationships(RelationshipType.withName(relationshipType2)).iterator().next();
  assertThat(rel.hasProperty(EdgeLabeler.edgeProperty), is(true));
  assertThat(GraphUtil.getProperty(rel, EdgeLabeler.edgeProperty, String.class).get(),
      is(relationshipType2));
}
 
Example #17
Source File: EdgeLabelerTest.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@Test
public void edgeWithLabeledNodeIsTagged() {
  Relationship rel =
      n1.getRelationships(RelationshipType.withName(relationshipType1)).iterator().next();
  assertThat(rel.hasProperty(EdgeLabeler.edgeProperty), is(true));
  assertThat(GraphUtil.getProperty(rel, EdgeLabeler.edgeProperty, String.class).get(),
      is(relationshipType1Label));
}
 
Example #18
Source File: GraphDump.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
public static void dumpGraph(GraphDatabaseService graphDb) {
  for (Node node: graphDb.getAllNodes()) {
    dumpNode(node);
  }
  for (Relationship relationship: graphDb.getAllRelationships()) {
    dumpRelationship(relationship);
  }
}
 
Example #19
Source File: Clique.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
private void moveEdgesToLeader(Node leader, List<Node> clique, Transaction tx) {
  for (Node n : clique) {
    logger.fine("Processing underNode - " + n.getProperty(NodeProperties.IRI));
    // int edgesMoved = 0;
    Iterable<Relationship> rels = n.getRelationships();
    for (Relationship rel : rels) {
      if ((isOneOfType(rel, relationships)) && (rel.getStartNode().getId() == leader.getId()
          || rel.getEndNode().getId() == leader.getId())) {
        logger.fine("equivalence relation which is already attached to the leader, do nothing");
      } else {
        if ((rel.getEndNode().getId() == n.getId())) {
          logger.fine("MOVE TARGET " + rel.getId() + " FROM " + n.getProperty(NodeProperties.IRI)
              + " TO " + leader.getProperty(NodeProperties.IRI));

          moveRelationship(n, leader, rel, ORIGINAL_REFERENCE_KEY_TARGET);
        } else if ((rel.getStartNode().getId() == n.getId())) {
          logger.fine("MOVE SOURCE " + rel.getId() + " FROM " + n.getProperty(NodeProperties.IRI)
              + " TO " + leader.getProperty(NodeProperties.IRI));

          moveRelationship(n, leader, rel, ORIGINAL_REFERENCE_KEY_SOURCE);
        }
      }
      // edgesMoved += 1;
      //
      // if (edgesMoved >= 100) { // Commit for nodes with many edges
      // logger.fine("rel batch commit for leader " + leader.getProperty(NodeProperties.IRI) +
      // " and peasant " + n.getProperty(NodeProperties.IRI));
      // tx.success();
      // tx.close();
      // tx = graphDb.beginTx();
      // edgesMoved = 0;
      // }
    }
    deleteEdges(n, tx);
  }
}
 
Example #20
Source File: Clique.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
private void moveRelationship(Node from, Node to, Relationship rel, String property) {
  Relationship newRel = null;
  logger.fine("create new rel between " + rel.getOtherNode(from).getId() + " and " + to.getId());
  if (property == ORIGINAL_REFERENCE_KEY_TARGET) {
    newRel = rel.getOtherNode(from).createRelationshipTo(to, rel.getType());
  } else {
    newRel = to.createRelationshipTo(rel.getOtherNode(from), rel.getType());
  }
  copyProperties(rel, newRel);
  rel.setProperty(REL_TO_REMOVE, true); // mark for deletion
  newRel.setProperty(property, from.getProperty(NodeProperties.IRI));
}
 
Example #21
Source File: GraphTransactionalImpl.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@Override
public <T> Optional<T> getRelationshipProperty(long relationshipId, String property,
    Class<T> type) {
  try (Transaction tx = graphDb.beginTx()) {
    Relationship relationship = graphDb.getRelationshipById(relationshipId);
    Optional<T> value = Optional.<T>empty();
    if (relationship.hasProperty(property)) {
      value = Optional.<T> of(type.cast(relationship.getProperty(property)));
    }
    tx.success();
    return value;
  }
}
 
Example #22
Source File: GraphTransactionalImpl.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@Override
public void addRelationshipProperty(long relationshipId, String property, Object value) {
  if (GraphUtil.ignoreProperty(value)) {
    return;
  }
  try (Transaction tx = graphDb.beginTx()) {
    Relationship relationship = graphDb.getRelationshipById(relationshipId);
    if (relationship.hasProperty(property)) {
      relationship.setProperty(property, GraphUtil.getNewPropertyValue(relationship.getProperty(property), value));
    } else {
      relationship.setProperty(property, value);
    }
    tx.success();
  }
}
 
Example #23
Source File: UniqueRelationshipFactory.java    From neo4jena with Apache License 2.0 5 votes vote down vote up
/**
 * Gets an existing relationship of specified type between subject and object node
 * or creates one.
 */
public Relationship getOrCreate(Node subject, RelationshipType type, Node object) {
	Relationship r = get(subject, type, object);
	if(r==null)
		r = create(subject, type, object);
	return r;
}
 
Example #24
Source File: TestSubObjectPropertyOf.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@Test
public void testSubclass() {
  Node subp = getNode("http://example.org/subproperty");
  Node superp = getNode("http://example.org/superproperty");
  assertThat("subclass should be a directed relationship",
      GraphUtil.getRelationships(subp, superp, OwlRelationships.RDFS_SUB_PROPERTY_OF),
      is(IsIterableWithSize.<Relationship> iterableWithSize(1)));
}
 
Example #25
Source File: Neo4jIndexHandler.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Optional<Edge> findEdgeById(UUID edgeId) {
  RelationshipIndex edgeIdIndex = getEdgeIdIndex();
  IndexHits<Relationship> hits = edgeIdIndex.query(TIM_ID, edgeId.toString());

  return hits.hasNext() ? traversal().E(hits.next().getId()).tryNext() : Optional.empty();
}
 
Example #26
Source File: Neo4JDb.java    From knowledge-extraction with Apache License 2.0 5 votes vote down vote up
public void insertTriplet(TripletRelation triplet, boolean mergeSubject) {
	final Label label_sub = DynamicLabel.label(LAB_SUBJECT);
	final Label label_obj = DynamicLabel.label(LAB_OBJECT);

	Node arg1 = null;
	if (mergeSubject) {
		arg1 = getNode(null, PROP_NAME, triplet.getArg1()
				.toLowerCase());
	}

	try (Transaction tx = graphDb.beginTx()) {
		if (arg1 == null) {
			arg1 = graphDb.createNode(label_sub);
			arg1.setProperty(PROP_OCCURRENCES, 1);
			arg1.setProperty(PROP_NAME, triplet.getArg1().toLowerCase());
		} else {
			int occurences = (Integer) arg1.getProperty(PROP_OCCURRENCES) + 1;
			arg1.setProperty(PROP_OCCURRENCES, occurences);
		}
		Node arg2 = graphDb.createNode(label_obj);
		arg2.setProperty(PROP_OCCURRENCES, 1);
		arg2.setProperty(PROP_NAME, triplet.getArg2().toLowerCase());

		Relationship relationship = arg1.createRelationshipTo(arg2,
				RelTypes.RELATES);
		relationship.setProperty(PROP_NAME, triplet.getRelation()
				.toLowerCase());
		//confidence
		relationship.setProperty(PROP_CONFIDENCE, triplet.getConfidence());
		tx.success();
	}
}
 
Example #27
Source File: PageRank.java    From Neo4jSNA with Apache License 2.0 5 votes vote down vote up
@Override
public void apply(Node node) {
	double secondMember = 0.0;
	for( Relationship rin : node.getRelationships() ) {
		Node neigh = rin.getOtherNode(node);
		
		double neighRank = (double) neigh.getProperty(attName);
		secondMember += neighRank / neigh.getDegree();
	}
	
	secondMember *= this.dampingFactor;
	node.setProperty(attName, firstMember + secondMember);
}
 
Example #28
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 #29
Source File: ConnectedComponents.java    From Neo4jSNA with Apache License 2.0 5 votes vote down vote up
protected long getLowestComponent(Node n) {
	long minComponent = (long) n.getProperty(attName);

	for(Relationship r : n.getRelationships(direction)) {
		long otherComponent = (long) r.getOtherNode(n).getProperty(attName);
		minComponent = minComponent < otherComponent ? minComponent : otherComponent;
	}
	return minComponent;
}
 
Example #30
Source File: AbstractEmbeddedDBAccess.java    From jcypher with Apache License 2.0 5 votes vote down vote up
private RelationNodes init(Relationship relation) {
	RelationNodes ret = new RelationNodes();
	JsonObjectBuilder rel = Json.createObjectBuilder();
	rel.add("id", String.valueOf(relation.getId()));
	RelationshipType typ = relation.getType();
	if (typ != null)
		rel.add("type", typ.name());
	Node sn = relation.getStartNode();
	if (sn != null) {
		rel.add("startNode", String.valueOf(sn.getId()));
		ret.startNode = sn;
	}
	Node en = relation.getEndNode();
	if (en != null) {
		rel.add("endNode", String.valueOf(en.getId()));
		ret.endNode = en;
	}
	JsonObjectBuilder props = Json.createObjectBuilder();
	Iterator<String> pit = relation.getPropertyKeys().iterator();
	while (pit.hasNext()) {
		String pKey = pit.next();
		Object pval = relation.getProperty(pKey);
		writeLiteral(pKey, pval, props);
	}
	rel.add("properties", props);
	this.relationObject = rel;
	return ret;
}