@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();
 }
  /**
   * Removes all nodes with non-valid resource classes from the graph.
   *
   * @param docGraph
   * @param validResourceClasses
   */
  private void preProcessGraph(DocGraph docGraph, Set<String> validResourceClasses) {
    log.info(String.format("Preprocessing DocGraph[%d]", docGraph.getId()));
    Node n;
    int cnt = 0;
    try (Transaction tx = graphDB.beginTx()) {
      for (Long nodeId : docGraph.getNodes()) {
        n = graphDB.getNodeById(nodeId);
        // node's class is resource class and it's not in the valid set
        if (n.hasProperty(Constants.NODE_SUPER_CLASS_KEY)
            && n.getProperty(Constants.NODE_SUPER_CLASS_KEY)
                .equals(Constants.NODE_SUPER_CLASS_RESOURCE_VALUE)
            && !validResourceClasses.contains(getNodeClass(n))) {
          try (Transaction innerTx = graphDB.beginTx()) {

            log.info("Deleting " + n);
            for (Relationship e : n.getRelationships()) {
              e.delete();
            }
            n.delete();
            innerTx.success();
            cnt++;
          }
        }
      }
      tx.success();
    }

    log.info(
        String.format("Preprocessing removed %d nodes from DocGraph[%d]", cnt, docGraph.getId()));
  }
 public void delete(ConstructionZoneNode zone) {
   Node n = zone.getNode();
   for (Relationship rel : n.getRelationships()) {
     rel.delete();
   }
   n.delete();
 }
 /*
  * It will remove a property from an embedded node if it exists.
  * After deleting the property, if the node does not have any more properties and relationships (except for an incoming one),
  * it will delete the embedded node as well.
  */
 private void removePropertyForEmbedded(Node embeddedNode, String[] embeddedColumnSplit, int i) {
   if (i == embeddedColumnSplit.length - 1) {
     // Property
     String property = embeddedColumnSplit[embeddedColumnSplit.length - 1];
     if (embeddedNode.hasProperty(property)) {
       embeddedNode.removeProperty(property);
     }
   } else {
     Iterator<Relationship> iterator =
         embeddedNode
             .getRelationships(Direction.OUTGOING, withName(embeddedColumnSplit[i]))
             .iterator();
     if (iterator.hasNext()) {
       removePropertyForEmbedded(iterator.next().getEndNode(), embeddedColumnSplit, i + 1);
     }
   }
   if (!embeddedNode.getPropertyKeys().iterator().hasNext()) {
     // Node without properties
     Iterator<Relationship> iterator = embeddedNode.getRelationships().iterator();
     if (iterator.hasNext()) {
       Relationship relationship = iterator.next();
       if (!iterator.hasNext()) {
         // Node with only one relationship and no properties,
         // we can remove it:
         // It means we have removed all the properties from the embedded node
         // and it is NOT an intermediate node like
         // (entity) --> (embedded1) --> (embedded2)
         relationship.delete();
         embeddedNode.delete();
       }
     }
   }
 }
  @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);
  }
示例#6
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();
 }
示例#7
0
 @Test
 public void testSimple3() {
   Node node1 = getGraphDb().createNode();
   Node node2 = getGraphDb().createNode();
   for (int i = 0; i < 1; i++) {
     node1.createRelationshipTo(node2, MyRelTypes.TEST);
     node1.createRelationshipTo(node2, MyRelTypes.TEST_TRAVERSAL);
     node1.createRelationshipTo(node2, MyRelTypes.TEST2);
   }
   allGetRelationshipMethods2(node1, Direction.OUTGOING);
   allGetRelationshipMethods2(node2, Direction.INCOMING);
   newTransaction();
   allGetRelationshipMethods2(node1, Direction.OUTGOING);
   allGetRelationshipMethods2(node2, Direction.INCOMING);
   node1.getRelationships(MyRelTypes.TEST, Direction.OUTGOING).iterator().next().delete();
   node1
       .getRelationships(MyRelTypes.TEST_TRAVERSAL, Direction.OUTGOING)
       .iterator()
       .next()
       .delete();
   node1.getRelationships(MyRelTypes.TEST2, Direction.OUTGOING).iterator().next().delete();
   node1.createRelationshipTo(node2, MyRelTypes.TEST);
   node1.createRelationshipTo(node2, MyRelTypes.TEST_TRAVERSAL);
   node1.createRelationshipTo(node2, MyRelTypes.TEST2);
   allGetRelationshipMethods2(node1, Direction.OUTGOING);
   allGetRelationshipMethods2(node2, Direction.INCOMING);
   newTransaction();
   allGetRelationshipMethods2(node1, Direction.OUTGOING);
   allGetRelationshipMethods2(node2, Direction.INCOMING);
   for (Relationship rel : node1.getRelationships()) {
     rel.delete();
   }
   node1.delete();
   node2.delete();
 }
示例#8
0
  public void visit(SpatialIndexVisitor visitor, Node indexNode) {
    if (!visitor.needsToVisit(getIndexNodeEnvelope(indexNode))) {
      return;
    }

    try (Transaction tx = database.beginTx()) {
      if (indexNode.hasRelationship(RTreeRelationshipTypes.RTREE_CHILD, Direction.OUTGOING)) {
        // Node is not a leaf
        for (Relationship rel :
            indexNode.getRelationships(RTreeRelationshipTypes.RTREE_CHILD, Direction.OUTGOING)) {
          Node child = rel.getEndNode();
          // collect children results
          visit(visitor, child);
        }
      } else if (indexNode.hasRelationship(
          RTreeRelationshipTypes.RTREE_REFERENCE, Direction.OUTGOING)) {
        // Node is a leaf
        for (Relationship rel :
            indexNode.getRelationships(
                RTreeRelationshipTypes.RTREE_REFERENCE, Direction.OUTGOING)) {
          visitor.onIndexReference(rel.getEndNode());
        }
      }
      tx.success();
    }
  }
示例#9
0
  private void visitInTx(SpatialIndexVisitor visitor, Long indexNodeId) {
    Node indexNode = database.getNodeById(indexNodeId);
    if (!visitor.needsToVisit(getIndexNodeEnvelope(indexNode))) {
      return;
    }

    if (indexNode.hasRelationship(RTreeRelationshipTypes.RTREE_CHILD, Direction.OUTGOING)) {
      // Node is not a leaf

      // collect children
      List<Long> children = new ArrayList<Long>();
      for (Relationship rel :
          indexNode.getRelationships(RTreeRelationshipTypes.RTREE_CHILD, Direction.OUTGOING)) {
        children.add(rel.getEndNode().getId());
      }

      // visit children
      for (Long child : children) {
        visitInTx(visitor, child);
      }
    } else if (indexNode.hasRelationship(
        RTreeRelationshipTypes.RTREE_REFERENCE, Direction.OUTGOING)) {
      // Node is a leaf
      try (Transaction tx = database.beginTx()) {
        for (Relationship rel :
            indexNode.getRelationships(
                RTreeRelationshipTypes.RTREE_REFERENCE, Direction.OUTGOING)) {
          visitor.onIndexReference(rel.getEndNode());
        }

        tx.success();
      }
    }
  }
 @Test
 public void testGetOrCreateRelationship() throws Exception {
   final Transaction tx = gdb.beginTx();
   final Node david = graphDatabase.createNode(map("name", "David"));
   final Node michael = graphDatabase.createNode(map("name", "Michael"));
   final Relationship rel1 =
       graphDatabase.getOrCreateRelationship(
           "knows",
           "whom",
           "david_michael",
           david,
           michael,
           "KNOWS",
           map("whom", "david_michael"));
   final Relationship rel2 =
       graphDatabase.getOrCreateRelationship(
           "knows",
           "whom",
           "david_michael",
           david,
           michael,
           "KNOWS",
           map("whom", "david_michael"));
   assertEquals("david_michael", rel1.getProperty("whom"));
   assertEquals("KNOWS", rel1.getType().name());
   assertEquals(david, rel1.getStartNode());
   assertEquals(michael, rel1.getEndNode());
   assertEquals(rel1, rel2);
   assertEquals(
       rel1, gdb.index().forRelationships("knows").get("whom", "david_michael").getSingle());
   tx.success();
   tx.finish();
 }
示例#11
0
  public void removeAll() throws ApplicationException {

    log.info("Removing all nodes and references.");

    Transaction tx = graphDb.beginTx();
    try {
      GlobalGraphOperations ops = GlobalGraphOperations.at(graphDb);

      for (Relationship relationship : ops.getAllRelationships()) {
        relationship.delete();
      }
      for (Node node : ops.getAllNodes()) {
        node.delete();
      }

      tx.success();
      log.info("Deleted all relationships and nodes");

    } catch (Exception e) {
      log.error(e.toString());
      tx.failure();
      throw new ApplicationException(e);
    } finally {
      tx.finish();
    }
  }
示例#12
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);
 }
示例#13
0
 @Override
 public List<String> completionCandidates(String partOfLine, Session session) {
   String lastWord = TextUtil.lastWordOrQuoteOf(partOfLine, false);
   if (lastWord.startsWith("-")) {
     return super.completionCandidates(partOfLine, session);
   }
   try {
     TreeSet<String> result = new TreeSet<String>();
     NodeOrRelationship current = getCurrent(session);
     if (current.isNode()) {
       // TODO Check if -r is supplied
       Node node = current.asNode();
       for (Node otherNode : RelationshipToNodeIterable.wrap(node.getRelationships(), node)) {
         long otherNodeId = otherNode.getId();
         String title = findTitle(getServer(), session, otherNode);
         if (title != null) {
           if (!result.contains(title)) {
             maybeAddCompletionCandidate(result, title + "," + otherNodeId, lastWord);
           }
         }
         maybeAddCompletionCandidate(result, "" + otherNodeId, lastWord);
       }
     } else {
       maybeAddCompletionCandidate(result, START_ALIAS, lastWord);
       maybeAddCompletionCandidate(result, END_ALIAS, lastWord);
       Relationship rel = current.asRelationship();
       maybeAddCompletionCandidate(result, "" + rel.getStartNode().getId(), lastWord);
       maybeAddCompletionCandidate(result, "" + rel.getEndNode().getId(), lastWord);
     }
     return new ArrayList<String>(result);
   } catch (ShellException e) {
     e.printStackTrace();
     return super.completionCandidates(partOfLine, session);
   }
 }
 @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);
 }
示例#15
0
 @Override
 public WeightedPath findSinglePath(Node start, Node end) {
   lastMetadata = new Metadata();
   AStarIterator iterator = new AStarIterator(start, end);
   while (iterator.hasNext()) {
     Node node = iterator.next();
     GraphDatabaseService graphDb = node.getGraphDatabase();
     if (node.equals(end)) {
       // Hit, return path
       double weight = iterator.visitData.get(node.getId()).wayLength;
       LinkedList<Relationship> rels = new LinkedList<Relationship>();
       Relationship rel =
           graphDb.getRelationshipById(iterator.visitData.get(node.getId()).cameFromRelationship);
       while (rel != null) {
         rels.addFirst(rel);
         node = rel.getOtherNode(node);
         long nextRelId = iterator.visitData.get(node.getId()).cameFromRelationship;
         rel = nextRelId == -1 ? null : graphDb.getRelationshipById(nextRelId);
       }
       Path path = toPath(start, rels);
       lastMetadata.paths++;
       return new WeightedPathImpl(weight, path);
     }
   }
   return null;
 }
示例#16
0
 /**
  * Constructs a path to a given node, for a given set of predecessors. The result is a list of
  * alternating Node/Relationship.
  *
  * @param node The start node
  * @param predecessors The predecessors set
  * @param includeNode Boolean which determines if the start node should be included in the paths
  * @param backwards Boolean, if true the order of the nodes in the paths will be reversed
  * @return A path as a list of alternating Node/Relationship.
  */
 public static List<PropertyContainer> constructSinglePathToNode(
     Node node,
     Map<Node, List<Relationship>> predecessors,
     boolean includeNode,
     boolean backwards) {
   LinkedList<PropertyContainer> path = new LinkedList<PropertyContainer>();
   if (includeNode) {
     if (backwards) {
       path.addLast(node);
     } else {
       path.addFirst(node);
     }
   }
   Node currentNode = node;
   List<Relationship> currentPreds = predecessors.get(currentNode);
   // Traverse predecessors until we have added a node without predecessors
   while (currentPreds != null && currentPreds.size() != 0) {
     // Get next node
     Relationship currentRelationship = currentPreds.get(0);
     currentNode = currentRelationship.getOtherNode(currentNode);
     // Add current
     if (backwards) {
       path.addLast(currentRelationship);
       path.addLast(currentNode);
     } else {
       path.addFirst(currentRelationship);
       path.addFirst(currentNode);
     }
     // Continue with the next node
     currentPreds = predecessors.get(currentNode);
   }
   return path;
 }
 private Object toJsonCompatible(Object value) {
   if (value instanceof Node) {
     final Node node = (Node) value;
     final Map<String, Object> result = SubGraph.toMap(node);
     result.put("_id", node.getId());
     return result;
   }
   if (value instanceof Relationship) {
     final Relationship relationship = (Relationship) value;
     final Map<String, Object> result = SubGraph.toMap(relationship);
     result.put("_id", relationship.getId());
     result.put("_start", relationship.getStartNode().getId());
     result.put("_end", relationship.getEndNode().getId());
     result.put("_type", relationship.getType().name());
     return result;
   }
   if (value instanceof Iterable) {
     final List<Object> result = new ArrayList<Object>();
     for (Object inner : (Iterable) value) {
       result.add(toJsonCompatible(inner));
     }
     return result;
   }
   return value;
 }
示例#18
0
 /** Same as constructAllPathsToNodeAsNodes, but different return type */
 protected static List<LinkedList<Node>> constructAllPathsToNodeAsNodeLinkedLists(
     Node node,
     Map<Node, List<Relationship>> predecessors,
     boolean includeNode,
     boolean backwards) {
   List<LinkedList<Node>> paths = new LinkedList<LinkedList<Node>>();
   List<Relationship> current = predecessors.get(node);
   // First build all paths to this node's predecessors
   if (current != null) {
     for (Relationship r : current) {
       Node n = r.getOtherNode(node);
       paths.addAll(constructAllPathsToNodeAsNodeLinkedLists(n, predecessors, true, backwards));
     }
   }
   // If no paths exists to this node, just create an empty one (which will
   // have this node added to it)
   if (paths.isEmpty()) {
     paths.add(new LinkedList<Node>());
   }
   // Then add this node to all those paths
   if (includeNode) {
     for (LinkedList<Node> path : paths) {
       if (backwards) {
         path.addFirst(node);
       } else {
         path.addLast(node);
       }
     }
   }
   return paths;
 }
示例#19
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();
  }
示例#20
0
 /** Same as constructAllPathsToNodeAsRelationships, but different return type */
 protected static List<LinkedList<Relationship>> constructAllPathsToNodeAsRelationshipLinkedLists(
     Node node, Map<Node, List<Relationship>> predecessors, boolean backwards) {
   List<LinkedList<Relationship>> paths = new LinkedList<LinkedList<Relationship>>();
   List<Relationship> current = predecessors.get(node);
   // First build all paths to this node's predecessors
   if (current != null) {
     for (Relationship r : current) {
       Node n = r.getOtherNode(node);
       List<LinkedList<Relationship>> newPaths =
           constructAllPathsToNodeAsRelationshipLinkedLists(n, predecessors, backwards);
       paths.addAll(newPaths);
       // Add the relationship
       for (LinkedList<Relationship> path : newPaths) {
         if (backwards) {
           path.addFirst(r);
         } else {
           path.addLast(r);
         }
       }
     }
   }
   // If no paths exists to this node, just create an empty one
   if (paths.isEmpty()) {
     paths.add(new LinkedList<Relationship>());
   }
   return paths;
 }
  private void putAssociationOperation(
      Association association,
      AssociationKey associationKey,
      AssociationOperation action,
      AssociatedEntityKeyMetadata associatedEntityKeyMetadata) {
    Relationship relationship =
        associationQueries
            .get(associationKey.getMetadata())
            .findRelationship(dataBase, associationKey, action.getKey());

    if (relationship != null) {
      for (String relationshipProperty : associationKey.getMetadata().getRowKeyIndexColumnNames()) {
        relationship.setProperty(relationshipProperty, action.getValue().get(relationshipProperty));
      }

      for (String column :
          associationKey
              .getMetadata()
              .getColumnsWithoutKeyColumns(action.getValue().getColumnNames())) {
        if (!isRowKeyColumn(associationKey.getMetadata(), column)) {
          relationship.getEndNode().setProperty(column, action.getValue().get(column));
        }
      }

      GraphLogger.log("Updated relationship: %1$s", relationship);
    } else {
      relationship =
          createRelationship(associationKey, action.getValue(), associatedEntityKeyMetadata);
      GraphLogger.log("Created relationship: %1$s", relationship);
    }
  }
示例#22
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());
  }
示例#23
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();
    }
  }
示例#24
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());
  }
  @Test
  public void removeNodesWithARelation() {
    int originalNodeCount = countNodesOf(graphDb);
    int removedNodeCount = 0;

    Transaction tx = graphDb.beginTx();
    try {
      Set<Node> toRemove = new HashSet<Node>();
      for (Node node : graphDb.getAllNodes()) {
        for (Relationship relationship : node.getRelationships(RelationType.ON)) {
          toRemove.add(relationship.getStartNode());
          toRemove.add(relationship.getEndNode());
          relationship.delete();
        }
      }
      for (Node node : toRemove) {
        node.delete();
        removedNodeCount++;
      }
      tx.success();
    } finally {
      tx.finish();
    }

    int finalNodeCount = countNodesOf(graphDb);
    assertEquals(
        Integer.valueOf(originalNodeCount), Integer.valueOf(finalNodeCount + removedNodeCount));
  }
示例#26
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));
  }
示例#27
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!");
  }
示例#28
0
    @SuppressWarnings("unchecked")
    private void expand() {
      Iterable<Relationship> expand = expander.expand(this, BranchState.NO_STATE);
      for (Relationship rel : expand) {
        lastMetadata.rels++;
        Node node = rel.getOtherNode(lastNode);
        Visit visit = visitData.get(node.getId());
        if (visit != null && visit.visited) {
          continue;
        }

        Visit lastVisit = visitData.get(lastNode.getId());
        double tentativeGScore =
            lastVisit.wayLength + lengthEvaluator.getCost(rel, Direction.OUTGOING);
        double estimate = estimateEvaluator.getCost(node, end);

        if (visit == null || !visit.next || tentativeGScore < visit.wayLength) {
          if (visit == null) {
            visit = new Visit(rel.getId(), tentativeGScore, estimate);
            visitData.put(node.getId(), visit);
          } else {
            visit.update(rel.getId(), tentativeGScore, estimate);
          }
          addNext(node, estimate + tentativeGScore, visit);
        }
      }
    }
示例#29
0
 private boolean traverse(CallPosition callPos) {
   // make everything like it was before we returned previous match
   PatternPosition currentPos = callPos.getPatternPosition();
   PatternRelationship pRel = callPos.getPatternRelationship();
   pRel.mark();
   visitedRels.remove(callPos.getLastVisitedRelationship());
   Node currentNode = currentPos.getCurrentNode();
   Iterator<Relationship> relItr = callPos.getRelationshipIterator();
   while (relItr.hasNext()) {
     Relationship rel = relItr.next();
     if (visitedRels.contains(rel)) {
       continue;
     }
     if (!checkProperties(pRel, rel)) {
       continue;
     }
     Node otherNode = rel.getOtherNode(currentNode);
     PatternNode otherPosition = pRel.getOtherNode(currentPos.getPatternNode());
     pRel.mark();
     visitedRels.add(rel);
     if (traverse(new PatternPosition(otherNode, otherPosition, pRel, rel, optional), true)) {
       callPos.setLastVisitedRelationship(rel);
       return true;
     }
     visitedRels.remove(rel);
     pRel.unMark();
   }
   pRel.unMark();
   if (callPos.shouldPopUncompleted()) {
     uncompletedPositions.pop();
   }
   callStack.pop();
   foundElements.pop();
   return false;
 }
 @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();
 }