@Test public void shouldFailTransactionThatIndexesLargePropertyAfterNodeCreation() { // GIVEN GraphDatabaseService db = dbRule.getGraphDatabaseAPI(); IndexDefinition index = Neo4jMatchers.createIndex( db, LABEL, propertyKey ); //We expect this transaction to fail due to the huge property expectedException.expect( TransactionFailureException.class ); try ( Transaction tx = db.beginTx() ) { db.execute( "CREATE (n:" + LABEL + ")" ); try { db.execute( "match (n:" + LABEL + ")set n.name= \"" + longString + "\"" ); fail( "Argument was illegal" ); } catch ( IllegalArgumentException e ) { //this is expected. } tx.success(); } //Check that the database is empty. try ( Transaction tx = db.beginTx() ) { ResourceIterator<Node> nodes = db.getAllNodes().iterator(); assertFalse( nodes.hasNext() ); } db.shutdown(); }
@Test void streamShouldCloseSingleOnCompleted() { // Given AtomicBoolean closed = new AtomicBoolean( false ); ResourceIterator<Integer> resourceIterator = newResourceIterator( iterator( new Integer[]{1, 2, 3} ), () -> closed.set( true ) ); ResourceIterable<Integer> iterable = () -> resourceIterator; // When List<Integer> result = iterable.stream().collect( Collectors.toList() ); // Then assertEquals( asList(1,2,3), result ); assertTrue( closed.get() ); }
private void cleanDatabaseContent( GraphDatabaseService db ) { try ( Transaction tx = db.beginTx() ) { db.getAllRelationships().forEach( Relationship::delete ); db.getAllNodes().forEach( Node::delete ); tx.success(); } }
try ( Transaction tx = db.beginTx() ) try ( ResourceIterator<Node> allNodes = db.getAllNodes().iterator() ) while ( allNodes.hasNext() ) nodes.add( allNodes.next() ); tx.success(); try ( Transaction tx = db.beginTx() ) if ( random.nextBoolean() ) node.setProperty( randomKey(), random.nextValueAsObject() ); .createRelationshipTo( random.among( nodes ), randomRelationshipType() ); if ( random.nextBoolean() ) relationship.setProperty( randomKey(), random.nextValueAsObject() ); random.among( nodes, node -> node.addLabel( randomLabel() ) ); relationship -> relationship.setProperty( randomKey(), random.nextValueAsObject() ) ); onRandomRelationship( nodes, relationship -> relationship.removeProperty( randomKey() ) ); tx.success();
Transaction tx = db.beginTx(); ResourceIterator<Node> results = db.findNodesByLabelAndProperty(dynamicLabel, propertyKey, keyValue).iterator(); if (results.hasNext()) { nodeStart = results.next(); classCache.put(keyValue, nodeStart.getId()); tx.success(); nodeStart = db.getNodeById(nodeId); createNodeFactory(db); nodeStart = classFactory.getOrCreate(propertyKey, keyValue); nodeStart.addLabel(dynamicLabel); tx.success(); } catch (final Exception e) { tx.failure(); } finally { tx.close(); classCache.put(keyValue, nodeStart != null ? nodeStart.getId() : 0);
private Node getNode(String keyValue, GraphDatabaseService db) { Node nodeStart = null; try(Transaction tx = db.beginTx()) { ResourceIterator<Node> results = db.findNodesByLabelAndProperty(DynamicLabel.label(label), propertyKey, keyValue).iterator(); if (results.hasNext()) { nodeStart = results.next(); patternCache.put(keyValue, nodeStart.getId()); inversePatternCache.put(nodeStart.getId(), keyValue); } tx.success(); tx.close(); } return nodeStart; }
@Test public void testDeleteReferenceNodeOrLastNodeIsOk() { Transaction tx = getTransaction(); for ( int i = 0; i < 10; i++ ) { getGraphDb().createNode(); } // long numNodesPre = getNodeManager().getNumberOfIdsInUse( Node.class // ); // empty the DB instance for ( Node node : getGraphDb().getAllNodes() ) { for ( Relationship rel : node.getRelationships() ) { rel.delete(); } node.delete(); } tx.success(); tx.close(); tx = getGraphDb().beginTx(); assertFalse( getGraphDb().getAllNodes().iterator().hasNext() ); // TODO: this should be valid, fails right now! // assertEquals( 0, numNodesPost ); tx.success(); tx.close(); }
try ( Transaction tx = db.beginTx() ) try ( ResourceIterator<Node> allNodes = db.getAllNodes().iterator() ) while ( allNodes.hasNext() ) nodes.add( allNodes.next() ); tx.success(); try ( Transaction tx = db.beginTx() ) nodes.remove( random.nextInt( nodes.size() ) ).delete(); node.setProperty( key, random.nextValueAsObject() ); random.among( nodes, node -> node.removeLabel( label ) ); tx.success();
/** * It is not allowed to add items manually to automatic indexes. */ @Test @Graph( nodes = {@NODE( name = "I" ), @NODE( name = "you" )}, relationships = {@REL( start = "I", end = "you", type = "know", properties = {@PROP( key = "since", value = "today" )} )}, autoIndexRelationships = true ) public void items_can_not_be_added_manually_to_a_Relationship_AutoIndex() { data.get(); String indexName; try ( Transaction tx = graphdb().beginTx() ) { indexName = graphdb().index().getRelationshipAutoIndexer().getAutoIndex().getName(); tx.success(); } try ( Transaction tx = graphdb().beginTx() ) { ResourceIterable<Relationship> relationships = (ResourceIterable<Relationship>) data.get().get( "I" ).getRelationships(); try ( ResourceIterator<Relationship> resourceIterator = relationships.iterator() ) { gen.get().expectedStatus( 405 ) .payload( createJsonStringFor( getRelationshipUri( resourceIterator.next() ), "name", "I" ) ) .post( postRelationshipIndexUri( indexName ) ).entity(); } } }
@PluginTarget( Node.class ) public Node clonedSubgraph( @Source Node startNode, @Parameter( name = "depth", optional = false ) Integer depth ) GraphDatabaseService graphDb = startNode.getGraphDatabase(); try ( Transaction tx = graphDb.beginTx() ) .iterator(); Iterator<Relationship> oldRelationships = oldNode.getRelationships( Direction.OUTGOING ) .iterator(); while ( oldRelationships.hasNext() ) Node newEndNode = clonedNodes.get( oldRelationship.getEndNode() ); if ( newEndNode != null ) Relationship newRelationship = newStartNode.createRelationshipTo( newEndNode, oldRelationship.getType() ); tx.success();
@PluginTarget( Node.class ) public Path pathToReference( @Source Node me ) { PathFinder<Path> finder = GraphAlgoFactory.shortestPath( PathExpanders.allTypesAndDirections(), 6 ); try ( Transaction tx = me.getGraphDatabase().beginTx() ) { Node other; if ( me.hasRelationship( RelationshipType.withName( "friend" ) ) ) { ResourceIterable<Relationship> relationships = (ResourceIterable<Relationship>) me.getRelationships( RelationshipType.withName( "friend" ) ); try ( ResourceIterator<Relationship> resourceIterator = relationships.iterator() ) { other = resourceIterator.next().getOtherNode( me ); } } else { other = me.getGraphDatabase().createNode(); } Path path = finder.findSinglePath( other, me ); tx.success(); return path; } }
InputIterator relationships = relationships( relationshipRandomSeed, relationshipCount, config.batchSize(), inputIdGenerator, groups ).iterator(); ResourceIterator<Node> dbNodes = db.getAllNodes().iterator() ) while ( dbNodes.hasNext() ) Node node = dbNodes.next(); String id = (String) node.getProperty( "id" ); assertNull( nodeByInputId.put( id, node ) ); verifiedNodes++; assertDegrees( node ); allNodesScanLabelCount += Iterables.count( node.getLabels() ); long labelScanStoreEntryCount = db.getAllLabels().stream() .flatMap( l -> db.findNodes( l ).stream() ) .count(); for ( Relationship relationship : db.getAllRelationships() ) relationshipByName.put( (String) relationship.getProperty( "id" ), relationship ); assertNotNull( "Expected there to be a relationship with name '" + name + "'", relationship ); assertEquals( nodeByInputId.get( uniqueId( input.startIdGroup, input.objectStartId ) ), relationship.getStartNode() ); assertEquals( nodeByInputId.get( uniqueId( input.endIdGroup, input.objectEndId ) ), relationship.getEndNode() ); assertRelationshipEquals( input, relationship );
@Test public void shouldAllowMultilineFieldsWhenEnabled() throws Exception { // GIVEN File data = data( ":ID,name", "1,\"This is a line with\nnewlines in\"" ); // WHEN importTool( "--into", dbRule.getDatabaseDirAbsolutePath(), "--nodes", data.getAbsolutePath(), "--multiline-fields", "true" ); // THEN GraphDatabaseService db = dbRule.getGraphDatabaseAPI(); try ( Transaction tx = db.beginTx() ) { ResourceIterator<Node> allNodes = db.getAllNodes().iterator(); Node node = Iterators.single( allNodes ); allNodes.close(); assertEquals( "This is a line with\nnewlines in", node.getProperty( "name" ) ); tx.success(); } }
@Test public void shouldTrimStringsIfConfiguredTo() throws Exception { // GIVEN String name = " This is a line with leading and trailing whitespaces "; File data = data( ":ID,name", "1,\"" + name + "\"", "2," + name ); // WHEN importTool( "--into", dbRule.getDatabaseDirAbsolutePath(), "--nodes", data.getAbsolutePath(), "--trim-strings", "true" ); // THEN GraphDatabaseService db = dbRule.getGraphDatabaseAPI(); try ( Transaction tx = db.beginTx(); ResourceIterator<Node> allNodes = db.getAllNodes().iterator() ) { Set<String> names = new HashSet<>(); while ( allNodes.hasNext() ) { names.add( allNodes.next().getProperty( "name" ).toString() ); } assertTrue( names.remove( name ) ); assertTrue( names.remove( name.trim() ) ); assertTrue( names.isEmpty() ); tx.success(); } }
@Override public int getCommunityFromNode(int nodeId) { Integer community = 0; try (final Transaction tx = beginUnforcedTransaction()) { try { Node node = neo4jGraph.findNodesByLabelAndProperty(NODE_LABEL, NODE_ID, String.valueOf(nodeId)).iterator() .next(); community = (Integer) (node.getProperty(COMMUNITY)); tx.success(); } catch (Exception e) { tx.failure(); throw new BenchmarkingException("unable to get community from node", e); } } return community; }
public static void deleteEverythingInDB(GraphDatabaseService graphDb) { try (Transaction tx = graphDb.beginTx()) { Iterable<Node> nodes = graphDb.getAllNodes(); for (Node n : nodes) { for (Relationship r : n.getRelationships()) r.delete(); n.delete(); tx.success(); try (Transaction tx = graphDb.beginTx()) { Iterator<Node> nodeIt = graphDb.getAllNodes().iterator(); for (IndexDefinition id : graphDb.schema().getIndexes()) id.drop(); tx.success();
logger.info("Starting clique merge"); Transaction tx = graphDb.beginTx(); ResourceIterable<Node> allNodes = graphDb.getAllNodes(); int size = Iterators.size(allNodes.iterator()); tx.success(); tx.close(); tx = graphDb.beginTx(); TraversalDescription traversalDescription = graphDb.traversalDescription().breadthFirst().uniqueness(Uniqueness.NODE_GLOBAL); tx.success(); tx.close(); tx = graphDb.beginTx(); logger.fine("Processing Node - " + baseNode.getProperty(NodeProperties.IRI)); if (!processedNodes.contains(baseNode.getId())) { logger.fine("-- " + node.getProperty(NodeProperties.IRI)); clique.add(node); processedNodes.add(node.getId());
ResourceIterable<Relationship> relationships = Iterables.asResourceIterable( currentNode.getRelationships() ); try ( ResourceIterator<Relationship> resourceIterator = relationships.iterator() ) while ( resourceIterator.hasNext() ) Relationship rel = resourceIterator.next(); if ( newId.isNode() ) if ( rel.getOtherNode( currentNode ).getId() == newId.getId() ) if ( rel.getId() == newId.getId() ) if ( relationship.getStartNode().getId() == newId.getId() || relationship.getEndNode().getId() == newId.getId() )
private static List<Integer> getFeatureIndexList(GraphDatabaseService db) { Transaction tx = db.beginTx(); // Get classes using Java API final List<Node> patterns = new ArrayList<>(); GlobalGraphOperations.at(db) .getAllNodesWithLabel(DynamicLabel.label("Pattern")) .forEach(a -> patterns.add(a)); Collections.sort(patterns, (a, b) -> ((Integer)b.getProperty("threshold")).compareTo(((Integer)a.getProperty("threshold")))); List<Integer> patternIds = patterns.stream() .filter(a -> getFeatureMatchDistribution(db, a.getId()) > CONFIDENCE_INTERVAL) .map(a -> ((Long)a.getId()).intValue()).collect(Collectors.toList()); tx.success(); tx.close(); return patternIds; }
@Override public Set<Integer> getNeighborsIds(int nodeId) { Set<Integer> neighbors = new HashSet<Integer>(); try (final Transaction tx = beginUnforcedTransaction()) { try { Node n = neo4jGraph.findNodesByLabelAndProperty(NODE_LABEL, NODE_ID, String.valueOf(nodeId)).iterator() .next(); for (Relationship relationship : n.getRelationships(RelTypes.SIMILAR, Direction.OUTGOING)) { Node neighbour = relationship.getOtherNode(n); String neighbourId = (String) neighbour.getProperty(NODE_ID); neighbors.add(Integer.valueOf(neighbourId)); } tx.success(); } catch (Exception e) { tx.failure(); throw new BenchmarkingException("unable to get neighbors ids", e); } } return neighbors; }