Ejemplo n.º 1
0
  private void addMutantToDB(
      Individual original, Individual mutant, int generationNumber, Location location) {
    final GraphDatabaseService graphDB = GraphDB.graphDB();
    IndexManager index = graphDB.index();
    Index<Node> individualNodes = index.forNodes("individuals");
    Index<Node> locationNodes = index.forNodes("locations");

    Transaction tx = graphDB.beginTx();

    Relationship mutantRelationship;
    Relationship node;
    Node individualNode;
    try {
      individualNode = graphDB.createNode();
      individualNode.setProperty("fitness", mutant.getGlobalFitness());
      individualNode.setProperty("id", mutant.uid.toString());
      Node locationNode = locationNodes.get("locationID", location.getPosition()).next();
      node = individualNode.createRelationshipTo(locationNode, RelTypes.LOCATEDIN);
      node.setProperty("generation", generationNumber);

      Node originalNode = individualNodes.get("id", original.uid.toString()).next();
      mutantRelationship = individualNode.createRelationshipTo(originalNode, RelTypes.MUTANTOF);
      mutantRelationship.setProperty("generation", generationNumber);

      individualNodes.add(individualNode, "id", mutant.uid.toString());

      tx.success();
    } finally {
      tx.finish();
    }
  }
Ejemplo n.º 2
0
  @Test
  public void testRelationshipAddProperty() {
    Node node1 = getGraphDb().createNode();
    Node node2 = getGraphDb().createNode();
    Relationship rel1 = node1.createRelationshipTo(node2, MyRelTypes.TEST);
    Relationship rel2 = node2.createRelationshipTo(node1, MyRelTypes.TEST);
    try {
      rel1.setProperty(null, null);
      fail("Null argument should result in exception.");
    } catch (IllegalArgumentException e) {
    }
    Integer int1 = new Integer(1);
    Integer int2 = new Integer(2);
    String string1 = new String("1");
    String string2 = new String("2");

    // add property
    rel1.setProperty(key1, int1);
    rel2.setProperty(key1, string1);
    rel1.setProperty(key2, string2);
    rel2.setProperty(key2, int2);
    assertTrue(rel1.hasProperty(key1));
    assertTrue(rel2.hasProperty(key1));
    assertTrue(rel1.hasProperty(key2));
    assertTrue(rel2.hasProperty(key2));
    assertTrue(!rel1.hasProperty(key3));
    assertTrue(!rel2.hasProperty(key3));
    assertEquals(int1, rel1.getProperty(key1));
    assertEquals(string1, rel2.getProperty(key1));
    assertEquals(string2, rel1.getProperty(key2));
    assertEquals(int2, rel2.getProperty(key2));

    getTransaction().failure();
  }
Ejemplo n.º 3
0
  @Test
  public void testRelationshipChangeProperty() {
    Integer int1 = new Integer(1);
    Integer int2 = new Integer(2);
    String string1 = new String("1");
    String string2 = new String("2");

    Node node1 = getGraphDb().createNode();
    Node node2 = getGraphDb().createNode();
    Relationship rel1 = node1.createRelationshipTo(node2, MyRelTypes.TEST);
    Relationship rel2 = node2.createRelationshipTo(node1, MyRelTypes.TEST);
    rel1.setProperty(key1, int1);
    rel2.setProperty(key1, string1);
    rel1.setProperty(key2, string2);
    rel2.setProperty(key2, int2);

    try {
      rel1.setProperty(null, null);
      fail("Null argument should result in exception.");
    } catch (IllegalArgumentException e) {
    } catch (NotFoundException e) {
      fail("wrong exception");
    }

    // test type change of exsisting property
    // cannot test this for now because of exceptions in PL
    rel2.setProperty(key1, int1);

    rel1.delete();
    rel2.delete();
    node2.delete();
    node1.delete();
  }
Ejemplo n.º 4
0
  @Test
  public void testRelationshipAutoIndexFromAPISanity() {
    final String propNameToIndex = "test";
    AutoIndexer<Relationship> autoIndexer = graphDb.index().getRelationshipAutoIndexer();
    autoIndexer.startAutoIndexingProperty(propNameToIndex);
    autoIndexer.setEnabled(true);
    newTransaction();

    Node node1 = graphDb.createNode();
    Node node2 = graphDb.createNode();
    Node node3 = graphDb.createNode();

    Relationship rel12 =
        node1.createRelationshipTo(node2, DynamicRelationshipType.withName("DYNAMIC"));
    Relationship rel23 =
        node2.createRelationshipTo(node3, DynamicRelationshipType.withName("DYNAMIC"));

    rel12.setProperty(propNameToIndex, "rel12");
    rel23.setProperty(propNameToIndex, "rel23");

    newTransaction();

    assertEquals(rel12, autoIndexer.getAutoIndex().get(propNameToIndex, "rel12").getSingle());
    assertEquals(rel23, autoIndexer.getAutoIndex().get(propNameToIndex, "rel23").getSingle());
  }
 @Test
 public void testRelationshipCahinIterator() {
   Node node1 = getGraphDb().createNode();
   Node node2 = getGraphDb().createNode();
   Relationship rels[] = new Relationship[100];
   for (int i = 0; i < rels.length; i++) {
     if (i < 50) {
       rels[i] = node1.createRelationshipTo(node2, MyRelTypes.TEST);
     } else {
       rels[i] = node2.createRelationshipTo(node1, MyRelTypes.TEST);
     }
   }
   newTransaction();
   getNodeManager().clearCache();
   Iterable<Relationship> relIterable = node1.getRelationships();
   for (Relationship rel : rels) {
     rel.delete();
   }
   newTransaction();
   for (Relationship rel : relIterable) {
     System.out.println(rel);
   }
   node1.delete();
   node2.delete();
 }
Ejemplo n.º 6
0
  @Test
  public void
      makeSureLazyLoadingRelationshipsWorksEvenIfOtherIteratorAlsoLoadsInTheSameIteration() {
    int numEdges = 100;

    /* create 256 nodes */
    GraphDatabaseService graphDB = getGraphDb();
    Node[] nodes = new Node[256];
    for (int num_nodes = 0; num_nodes < nodes.length; num_nodes += 1) {
      nodes[num_nodes] = graphDB.createNode();
    }
    newTransaction();

    /* create random outgoing relationships from node 5 */
    Node hub = nodes[4];
    int nextID = 7;

    RelationshipType outtie = withName("outtie");
    RelationshipType innie = withName("innie");
    for (int k = 0; k < numEdges; k++) {
      Node neighbor = nodes[nextID];
      nextID += 7;
      nextID &= 255;
      if (nextID == 0) {
        nextID = 1;
      }
      hub.createRelationshipTo(neighbor, outtie);
    }
    newTransaction();

    /* create random incoming relationships to node 5 */
    for (int k = 0; k < numEdges; k += 1) {
      Node neighbor = nodes[nextID];
      nextID += 7;
      nextID &= 255;
      if (nextID == 0) {
        nextID = 1;
      }
      neighbor.createRelationshipTo(hub, innie);
    }
    commit();
    clearCache();

    newTransaction();
    hub = graphDB.getNodeById(hub.getId());

    int count = 0;
    for (@SuppressWarnings("unused") Relationship r1 : hub.getRelationships()) {
      count += count(hub.getRelationships());
    }
    assertEquals(40000, count);

    count = 0;
    for (@SuppressWarnings("unused") Relationship r1 : hub.getRelationships()) {
      count += count(hub.getRelationships());
    }
    assertEquals(40000, count);
    commit();
  }
Ejemplo n.º 7
0
  @Test
  public void testRelationshipRemoveProperty() {
    Integer int1 = new Integer(1);
    Integer int2 = new Integer(2);
    String string1 = new String("1");
    String string2 = new String("2");

    Node node1 = getGraphDb().createNode();
    Node node2 = getGraphDb().createNode();
    Relationship rel1 = node1.createRelationshipTo(node2, MyRelTypes.TEST);
    Relationship rel2 = node2.createRelationshipTo(node1, MyRelTypes.TEST);
    // verify that we can rely on PL to reomve non existing properties
    try {
      if (rel1.removeProperty(key1) != null) {
        fail("Remove of non existing property should return null");
      }
    } catch (NotFoundException e) {
    }
    try {
      rel1.removeProperty(null);
      fail("Remove null property should throw exception.");
    } catch (IllegalArgumentException e) {
    }

    rel1.setProperty(key1, int1);
    rel2.setProperty(key1, string1);
    rel1.setProperty(key2, string2);
    rel2.setProperty(key2, int2);
    try {
      rel1.removeProperty(null);
      fail("Null argument should result in exception.");
    } catch (IllegalArgumentException e) {
    }

    // test remove property
    assertEquals(int1, rel1.removeProperty(key1));
    assertEquals(string1, rel2.removeProperty(key1));
    // test remove of non exsisting property
    try {
      if (rel2.removeProperty(key1) != null) {
        fail("Remove of non existing property should return null");
      }
    } catch (NotFoundException e) {
      // have to set rollback only here
      getTransaction().failure();
    }
    rel1.delete();
    rel2.delete();
    node1.delete();
    node2.delete();
  }
Ejemplo n.º 8
0
 @Test
 public void testSimple() {
   Node node1 = getGraphDb().createNode();
   Node node2 = getGraphDb().createNode();
   Relationship rel1 = node1.createRelationshipTo(node2, MyRelTypes.TEST);
   node1.createRelationshipTo(node2, MyRelTypes.TEST);
   rel1.delete();
   newTransaction();
   assertTrue(node1.getRelationships().iterator().hasNext());
   assertTrue(node2.getRelationships().iterator().hasNext());
   assertTrue(node1.getRelationships(MyRelTypes.TEST).iterator().hasNext());
   assertTrue(node2.getRelationships(MyRelTypes.TEST).iterator().hasNext());
   assertTrue(node1.getRelationships(MyRelTypes.TEST, Direction.OUTGOING).iterator().hasNext());
   assertTrue(node2.getRelationships(MyRelTypes.TEST, Direction.INCOMING).iterator().hasNext());
 }
Ejemplo n.º 9
0
  @Test
  public void testRemoveRelationshipRemovesDocument() {
    AutoIndexer<Relationship> autoIndexer = graphDb.index().getRelationshipAutoIndexer();
    autoIndexer.startAutoIndexingProperty("foo");
    autoIndexer.setEnabled(true);

    newTransaction();

    Node node1 = graphDb.createNode();
    Node node2 = graphDb.createNode();
    Relationship rel = node1.createRelationshipTo(node2, DynamicRelationshipType.withName("foo"));
    rel.setProperty("foo", "bar");

    newTransaction();

    assertThat(
        graphDb.index().forRelationships("relationship_auto_index").query("_id_:*").size(),
        equalTo(1));

    newTransaction();

    rel.delete();

    newTransaction();

    assertThat(
        graphDb.index().forRelationships("relationship_auto_index").query("_id_:*").size(),
        equalTo(0));
  }
Ejemplo n.º 10
0
  @Test
  public void testDefaultsAreSeparateForNodesAndRelationships() throws Exception {
    stopDb();
    config = new HashMap<>();
    config.put(GraphDatabaseSettings.node_keys_indexable.name(), "propName");
    config.put(GraphDatabaseSettings.node_auto_indexing.name(), "true");
    // Now only node properties named propName should be indexed.
    startDb();

    newTransaction();

    Node node1 = graphDb.createNode();
    Node node2 = graphDb.createNode();
    node1.setProperty("propName", "node1");
    node2.setProperty("propName", "node2");
    node2.setProperty("propName_", "node2");

    Relationship rel =
        node1.createRelationshipTo(node2, DynamicRelationshipType.withName("DYNAMIC"));
    rel.setProperty("propName", "rel1");

    newTransaction();

    ReadableIndex<Node> autoIndex = graphDb.index().getNodeAutoIndexer().getAutoIndex();
    assertEquals(node1, autoIndex.get("propName", "node1").getSingle());
    assertEquals(node2, autoIndex.get("propName", "node2").getSingle());
    assertFalse(
        graphDb
            .index()
            .getRelationshipAutoIndexer()
            .getAutoIndex()
            .get("propName", "rel1")
            .hasNext());
  }
Ejemplo n.º 11
0
  private void createSomeTransactions(GraphDatabaseService db) {
    Transaction tx = db.beginTx();
    Node node1 = db.createNode();
    Node node2 = db.createNode();
    node1.createRelationshipTo(node2, DynamicRelationshipType.withName("relType1"));
    tx.success();
    tx.finish();

    tx = db.beginTx();
    node1.delete();
    tx.success();
    try {
      // Will throw exception, causing the tx to be rolledback.
      tx.finish();
    } catch (Exception nothingToSeeHereMoveAlong) {
      // InvalidRecordException coming, node1 has rels
    }
    /*
     *  The damage has already been done. The following just makes sure
     *  the corrupting tx is flushed to disk, since we will exit
     *  uncleanly.
     */
    tx = db.beginTx();
    node1.setProperty("foo", "bar");
    tx.success();
    tx.finish();
  }
  @Override
  public void generate(String dbPath) {
    GraphDatabaseService graphDb = new EmbeddedGraphDatabase(dbPath);
    Index<Node> nodeIndex =
        graphDb
            .index()
            .forNodes("nodes", MapUtil.stringMap("provider", "lucene", "type", "fulltext"));
    Index<Relationship> relationshipIndex =
        graphDb
            .index()
            .forRelationships(
                "relationships", MapUtil.stringMap("provider", "lucene", "type", "fulltext"));
    Transaction tx = graphDb.beginTx();
    try {
      Node n = graphDb.createNode();
      Node n2 = graphDb.createNode();
      Relationship rel = n.createRelationshipTo(n2, REL_TYPE);

      nodeIndex.add(n, "name", "alpha bravo");
      nodeIndex.add(n2, "name", "charlie delta");
      relationshipIndex.add(rel, "name", "echo foxtrot");

      tx.success();
    } finally {
      tx.finish();
    }
    graphDb.shutdown();
  }
Ejemplo n.º 13
0
  @Test
  public void shouldBeAbleToGetPropertiesOnRelationship() throws Exception {

    long relationshipId;
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("foo", "bar");
    properties.put("neo", "Thomas A. Anderson");
    properties.put("number", 15L);
    Transaction tx = database.getGraph().beginTx();
    try {
      Node startNode = database.getGraph().createNode();
      Node endNode = database.getGraph().createNode();
      Relationship relationship =
          startNode.createRelationshipTo(endNode, DynamicRelationshipType.withName("knows"));
      for (Map.Entry<String, Object> entry : properties.entrySet()) {
        relationship.setProperty(entry.getKey(), entry.getValue());
      }
      relationshipId = relationship.getId();
      tx.success();
    } finally {
      tx.finish();
    }

    Map<String, Object> readProperties =
        serialize(actions.getAllRelationshipProperties(relationshipId));
    assertEquals(properties, readProperties);
  }
Ejemplo n.º 14
0
  @Test
  public void testRelationshipChangeProperty2() {
    Integer int1 = new Integer(1);
    Integer int2 = new Integer(2);
    String string1 = new String("1");
    String string2 = new String("2");
    Boolean bool1 = new Boolean(true);
    Boolean bool2 = new Boolean(false);

    Node node1 = getGraphDb().createNode();
    Node node2 = getGraphDb().createNode();
    Relationship rel1 = node1.createRelationshipTo(node2, MyRelTypes.TEST);
    rel1.setProperty(key1, int1);
    rel1.setProperty(key1, int2);
    assertEquals(int2, rel1.getProperty(key1));
    rel1.removeProperty(key1);
    rel1.setProperty(key1, string1);
    rel1.setProperty(key1, string2);
    assertEquals(string2, rel1.getProperty(key1));
    rel1.removeProperty(key1);
    rel1.setProperty(key1, bool1);
    rel1.setProperty(key1, bool2);
    assertEquals(bool2, rel1.getProperty(key1));
    rel1.removeProperty(key1);

    rel1.delete();
    node2.delete();
    node1.delete();
  }
Ejemplo n.º 15
0
 @Test
 public void deleteRelsWithCommitInMiddle() throws Exception {
   Node node = getGraphDb().createNode();
   Node otherNode = getGraphDb().createNode();
   RelationshipType[] types =
       new RelationshipType[] {withName("r1"), withName("r2"), withName("r3"), withName("r4")};
   int count = 30; // 30*4 > 100 (rel grabSize)
   for (int i = 0; i < types.length * count; i++) {
     node.createRelationshipTo(otherNode, types[i % types.length]);
   }
   newTransaction();
   clearCache();
   int delCount = 0;
   int loopCount = 0;
   while (delCount < count) {
     loopCount++;
     for (Relationship rel : node.getRelationships(types[1])) {
       rel.delete();
       if (++delCount == count / 2) {
         newTransaction();
       }
     }
   }
   assertEquals(1, loopCount);
   assertEquals(count, delCount);
 }
Ejemplo n.º 16
0
  public RelationshipRepresentation createRelationship(
      long startNodeId, long endNodeId, String type, Map<String, Object> properties)
      throws StartNodeNotFoundException, EndNodeNotFoundException, PropertyValueException {

    Node start, end;
    try {
      start = node(startNodeId);
    } catch (NodeNotFoundException e) {
      throw new StartNodeNotFoundException();
    }
    try {
      end = node(endNodeId);
    } catch (NodeNotFoundException e) {
      throw new EndNodeNotFoundException();
    }
    final RelationshipRepresentation result;
    Transaction tx = graphDb.beginTx();
    try {
      result =
          new RelationshipRepresentation(
              set(
                  start.createRelationshipTo(end, DynamicRelationshipType.withName(type)),
                  properties));
      tx.success();
    } finally {
      tx.finish();
    }
    return result;
  }
 @Before
 public void createTestingGraph() {
   Node node1 = getGraphDb().createNode();
   Node node2 = getGraphDb().createNode();
   Relationship rel = node1.createRelationshipTo(node2, MyRelTypes.TEST);
   node1Id = (int) node1.getId();
   node2Id = (int) node2.getId();
   node1.setProperty(key1, int1);
   node1.setProperty(key2, string1);
   node2.setProperty(key1, int2);
   node2.setProperty(key2, string2);
   rel.setProperty(key1, int1);
   rel.setProperty(key2, string1);
   node1.setProperty(arrayKey, array);
   node2.setProperty(arrayKey, array);
   rel.setProperty(arrayKey, array);
   Transaction tx = getTransaction();
   tx.success();
   tx.finish();
   NodeManager nodeManager =
       ((EmbeddedGraphDatabase) getGraphDb()).getConfig().getGraphDbModule().getNodeManager();
   nodeManager.clearCache();
   tx = getGraphDb().beginTx();
   setTransaction(tx);
 }
Ejemplo n.º 18
0
 @Test
 public void testRelationshipCreateAndDelete() {
   Node node1 = getGraphDb().createNode();
   Node node2 = getGraphDb().createNode();
   Relationship relationship = node1.createRelationshipTo(node2, MyRelTypes.TEST);
   Relationship relArray1[] = getRelationshipArray(node1.getRelationships());
   Relationship relArray2[] = getRelationshipArray(node2.getRelationships());
   assertEquals(1, relArray1.length);
   assertEquals(relationship, relArray1[0]);
   assertEquals(1, relArray2.length);
   assertEquals(relationship, relArray2[0]);
   relArray1 = getRelationshipArray(node1.getRelationships(MyRelTypes.TEST));
   assertEquals(1, relArray1.length);
   assertEquals(relationship, relArray1[0]);
   relArray2 = getRelationshipArray(node2.getRelationships(MyRelTypes.TEST));
   assertEquals(1, relArray2.length);
   assertEquals(relationship, relArray2[0]);
   relArray1 = getRelationshipArray(node1.getRelationships(MyRelTypes.TEST, Direction.OUTGOING));
   assertEquals(1, relArray1.length);
   relArray2 = getRelationshipArray(node2.getRelationships(MyRelTypes.TEST, Direction.INCOMING));
   assertEquals(1, relArray2.length);
   relArray1 = getRelationshipArray(node1.getRelationships(MyRelTypes.TEST, Direction.INCOMING));
   assertEquals(0, relArray1.length);
   relArray2 = getRelationshipArray(node2.getRelationships(MyRelTypes.TEST, Direction.OUTGOING));
   assertEquals(0, relArray2.length);
   relationship.delete();
   node2.delete();
   node1.delete();
 }
Ejemplo n.º 19
0
  public void rn() throws IOException {
    List<RoadLink> links = loadToDatabase("/Users/duduba/gj.mif", "/Users/duduba/gj.mid", false);

    GraphDatabaseService graphDb = neo.getDb();
    Index<Node> nodeIndex = neo.getNodeIndex();

    for (RoadLink link : links) {
      Transaction tx = graphDb.beginTx();
      try {

        Node fromNode = nodeIndex.get("id", link.fromNode).getSingle();
        if (fromNode == null) {
          fromNode = graphDb.createNode();
          fromNode.setProperty("id", link.fromNode);
          nodeIndex.add(fromNode, "id", link.fromNode);
        }
        Node toNode = nodeIndex.get("id", link.toNode).getSingle();
        if (toNode == null) {
          toNode = graphDb.createNode();
          toNode.setProperty("id", link.toNode);
          nodeIndex.add(toNode, "id", link.toNode);
        }

        Relationship r = fromNode.createRelationshipTo(toNode, Neo.RelTypes.TO);
        r.setProperty("no", link.no);
        r.setProperty("name", link.name);

        tx.success();
      } finally {
        tx.finish();
      }
    }
    logger.debug("haha, it's ok!");
  }
Ejemplo n.º 20
0
  @Test
  public void shouldLoadAllRelationships() throws Exception {
    // GIVEN
    GraphDatabaseAPI db = getGraphDbAPI();
    Node node;
    try (Transaction tx = db.beginTx()) {
      node = db.createNode();
      for (int i = 0; i < 112; i++) {
        node.createRelationshipTo(db.createNode(), MyRelTypes.TEST);
        db.createNode().createRelationshipTo(node, MyRelTypes.TEST);
      }
      tx.success();
    }
    // WHEN
    db.getDependencyResolver().resolveDependency(NodeManager.class).clearCache();
    int one, two;
    try (Transaction tx = db.beginTx()) {
      one = count(node.getRelationships(MyRelTypes.TEST, Direction.OUTGOING));
      two = count(node.getRelationships(MyRelTypes.TEST, Direction.OUTGOING));
      tx.success();
    }

    // THEN
    assertEquals(two, one);
  }
 @Test
 public void testRelMultiRemoveProperty() {
   Node node1 = getGraphDb().createNode();
   Node node2 = getGraphDb().createNode();
   Relationship rel = node1.createRelationshipTo(node2, MyRelTypes.TEST);
   rel.setProperty("key0", "0");
   rel.setProperty("key1", "1");
   rel.setProperty("key2", "2");
   rel.setProperty("key3", "3");
   rel.setProperty("key4", "4");
   newTransaction();
   rel.removeProperty("key3");
   rel.removeProperty("key2");
   rel.removeProperty("key3");
   newTransaction();
   getNodeManager().clearCache();
   assertEquals("0", rel.getProperty("key0"));
   assertEquals("1", rel.getProperty("key1"));
   assertEquals("4", rel.getProperty("key4"));
   assertTrue(!rel.hasProperty("key2"));
   assertTrue(!rel.hasProperty("key3"));
   rel.delete();
   node1.delete();
   node2.delete();
 }
Ejemplo n.º 22
0
  private void connect(
      final Integer fromFacebookId,
      final Integer toFacebookId,
      final ConnectionType connectionType) {
    final Transaction transaction = graphDb.beginTx();
    try {
      final Node fromNode = this.getIndexedNode(fromFacebookId);
      final Node toNode = this.getIndexedNode(toFacebookId);

      if (fromNode == null || toNode == null) {
        if (logger.isWarnEnabled()) {
          logger.warn("Can't connect nodes {} <> {} because one or both does not exists.");
        }
        throw new ResourceNotFoundException("One or both sides of the connection does not exists.");
      }

      fromNode.createRelationshipTo(toNode, connectionType);

      if (logger.isInfoEnabled()) {
        logger.info(
            "{} is now Connected to {} with the {} relation.",
            fromNode.getProperty(Neo4JPersonRepository.PROPERTY_NAME),
            toNode.getProperty(Neo4JPersonRepository.PROPERTY_NAME),
            connectionType);
      }

      transaction.success();
    } catch (final Exception e) {
      transaction.failure();
      logger.error("Error connecting " + fromFacebookId + " to " + toFacebookId + ".", e);
      throw e;
    } finally {
      transaction.finish();
    }
  }
Ejemplo n.º 23
0
  private void createLink(final Lnk domainLink) throws ApplicationException {
    Transaction tx = graphDb.beginTx();
    Node nodeA = null;
    Node nodeB = null;
    try {
      long keyValueA = Long.parseLong(domainLink.getaNode().trim());
      long keyValueB = Long.parseLong(domainLink.getbNode().trim());

      nodeA = nodeIndex.get(DomainConstants.PROP_NODE_ID, keyValueA).getSingle();
      nodeB = nodeIndex.get(DomainConstants.PROP_NODE_ID, keyValueB).getSingle();

      if (null == nodeA || null == nodeB) {
        throw new ApplicationException(
            String.format(
                "Link referenced %s A-Node with key %d, and the link referenced %s B-Node with key %d",
                nodeA, keyValueA, nodeB, keyValueB));
      }

      log.info(
          String.format(
              "Link inserted from  %s A-Node with key %d, to the link referenced %s B-Node with key %d",
              nodeA, keyValueA, nodeB, keyValueB));

      nodeA.createRelationshipTo(nodeB, DomainConstants.RelTypes.DOMAIN_LINK);

      tx.success();

    } catch (Exception e) {
      log.error(e.toString());
      tx.failure();
      throw new ApplicationException(e);
    } finally {
      tx.finish();
    }
  }
Ejemplo n.º 24
0
  private void putOneToOneAssociation(
      Tuple tuple,
      Node node,
      TupleOperation operation,
      TupleContext tupleContext,
      Set<String> processedAssociationRoles) {
    String associationRole = tupleContext.getTupleTypeContext().getRole(operation.getColumn());

    if (!processedAssociationRoles.contains(associationRole)) {
      processedAssociationRoles.add(associationRole);

      EntityKey targetKey =
          getEntityKey(
              tuple,
              tupleContext
                  .getTupleTypeContext()
                  .getAssociatedEntityKeyMetadata(operation.getColumn()));

      // delete the previous relationship if there is one; for a to-one association, the
      // relationship won't have any
      // properties, so the type is uniquely identifying it
      Iterator<Relationship> relationships =
          node.getRelationships(withName(associationRole)).iterator();
      if (relationships.hasNext()) {
        relationships.next().delete();
      }

      // create a new relationship
      Node targetNode =
          entityQueries
              .get(targetKey.getMetadata())
              .findEntity(dataBase, targetKey.getColumnValues());
      node.createRelationshipTo(targetNode, withName(associationRole));
    }
  }
Ejemplo n.º 25
0
  @Test
  public void shouldBeAbleToImplementAnonymousGraphQuery() throws Exception {
    // given
    GraphDatabaseService db = Db.impermanentDb();
    Transaction tx = db.beginTx();
    Node firstNode = db.createNode();
    Node secondNode = db.createNode();
    firstNode.createRelationshipTo(secondNode, withName("CONNECTED_TO"));
    tx.success();
    tx.finish();

    GraphQuery query =
        new GraphQuery() {
          @Override
          public Iterable<Node> execute(Node startNode) {
            return startNode.traverse(
                Traverser.Order.DEPTH_FIRST,
                StopEvaluator.DEPTH_ONE,
                ReturnableEvaluator.ALL_BUT_START_NODE,
                withName("CONNECTED_TO"),
                Direction.OUTGOING);
          }
        };

    // when
    Iterable<Node> result = query.execute(firstNode);

    // then
    Iterator<Node> iterator = result.iterator();
    assertEquals(secondNode, iterator.next());
    assertFalse(iterator.hasNext());
  }
Ejemplo n.º 26
0
  private long createDb() {
    GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);

    long firstNodeId = -1;

    Transaction tx = graphDb.beginTx();
    try {
      Node firstNode = graphDb.createNode();
      firstNodeId = firstNode.getId();
      firstNode.setProperty("message", "Hello, ");
      firstNode.setProperty(
          "someJson", "{\n  \"is\" : \"vcard\",\n  \"name\" : \"Jim Barritt\"\n}");

      Node secondNode = graphDb.createNode();
      secondNode.setProperty("message", "World!");

      Relationship relationship = firstNode.createRelationshipTo(secondNode, KNOWS);
      relationship.setProperty("message", "brave Neo4j ");

      tx.success();

      return firstNodeId;
    } finally {
      tx.finish();
      graphDb.shutdown();
    }
  }
 private Node addNode(EmbeddedGraphDatabase graphDb) {
   Node referenceNode = graphDb.getReferenceNode();
   Node node = graphDb.createNode();
   node.setProperty("theId", node.getId());
   referenceNode.createRelationshipTo(node, MyRels.TEST);
   return node;
 }
Ejemplo n.º 28
0
  public static void main(String[] args) {
    GraphDatabaseFactory neodb = new GraphDatabaseFactory();
    // Direccion de la Base de datos Neo4j
    GraphDatabaseService graphDb =
        neodb.newEmbeddedDatabase("C:\\Users\\Administrador\\Documents\\Neo4j\\default.graphdb");

    try (Transaction tx = graphDb.beginTx()) {
      // Creacion de nodos con sus propiedades
      Node bobNode = graphDb.createNode(NodeType.Person); // Tipo del nodo Person
      bobNode.setProperty("Pid", 5001);
      bobNode.setProperty("Name", "Bob");
      bobNode.setProperty("Age", 23);

      Node aliceNode = graphDb.createNode(NodeType.Person);
      aliceNode.setProperty("Pid", 5002);
      aliceNode.setProperty("Name", "Eve");

      Node eveNode = graphDb.createNode(NodeType.Person);
      eveNode.setProperty("Name", "Eve");

      Node itNode = graphDb.createNode(NodeType.Course); // TIpo del nodo Course
      itNode.setProperty("Id", 1);
      itNode.setProperty("Name", "IT Beginners");
      itNode.setProperty("Location", "Room 153");

      Node electronicNode = graphDb.createNode(NodeType.Course);
      electronicNode.setProperty("Name", "Electronics Advanced");

      // Creacion de relaciones entre los nodos
      bobNode.createRelationshipTo(aliceNode, RelationType.Knows); // Tipo de relacion Knows

      Relationship bobRelIt =
          bobNode.createRelationshipTo(
              itNode, RelationType.BelongsTo); // Tipo de relacion BelongsTo
      bobRelIt.setProperty("Function", "Student");

      Relationship bobRelElectronics =
          bobNode.createRelationshipTo(electronicNode, RelationType.BelongsTo);
      bobRelElectronics.setProperty("Function", "Supply Teacher");

      Relationship aliceRelIt = aliceNode.createRelationshipTo(itNode, RelationType.BelongsTo);
      aliceRelIt.setProperty("Function", "Teacher");

      tx.success(); // Proceso termino de forma exitosa
    }
    graphDb.shutdown(); // Cerrar base
  }
Ejemplo n.º 29
0
 private void initIndexRoot() {
   Node layerNode = getRootNode();
   if (!layerNode.hasRelationship(RTreeRelationshipTypes.RTREE_ROOT, Direction.OUTGOING)) {
     // index initialization
     Node root = database.createNode();
     layerNode.createRelationshipTo(root, RTreeRelationshipTypes.RTREE_ROOT);
   }
 }
 @Override
 public void rhs(final Collection<Neo4jSwitchSensorMatch> matches) {
   for (final Neo4jSwitchSensorMatch ssnm : matches) {
     final Node sw = ssnm.getSw();
     final Node sensor = neoDriver.getGraphDb().createNode(labelSensor);
     sw.createRelationshipTo(sensor, relationshipTypeSensor);
   }
 }