Java Code Examples for org.neo4j.graphdb.GraphDatabaseService#beginTx()

The following examples show how to use org.neo4j.graphdb.GraphDatabaseService#beginTx() . 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: CypherUtil.java    From graphify with Apache License 2.0 6 votes vote down vote up
public static String executeCypher(GraphDatabaseService db, String cypher, Map<String, Object> params) {
    org.neo4j.cypher.javacompat.ExecutionEngine engine;
    engine = new org.neo4j.cypher.javacompat.ExecutionEngine(db);
    List<Map<String, Object>> results = new ArrayList<>();

    org.neo4j.cypher.javacompat.ExecutionResult result;

    try ( Transaction tx = db.beginTx() ) {
        result = engine.execute(cypher, params);
        for (Map<String,Object> row : result) {
            results.add(new LinkedHashMap<>(row));
        }
        tx.success();
    }

    return new Gson().toJson(results);
}
 
Example 2
Source File: Neo4JApiQuerySwitchSetInject.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Collection<Neo4jSwitchSetInjectMatch> evaluate() {
	final Collection<Neo4jSwitchSetInjectMatch> matches = new ArrayList<>();

	final GraphDatabaseService graphDb = driver.getGraphDb();
	try (Transaction tx = graphDb.beginTx()) {
		// (sw:Switch)
		final Iterable<Node> sws = () -> graphDb.findNodes(Neo4jConstants.labelSwitch);
		for (final Node sw : sws) {
			final Map<String, Object> match = new HashMap<>();
			match.put(QueryConstants.VAR_SW, sw);
			matches.add(new Neo4jSwitchSetInjectMatch(match));
		}
	}

	return matches;
}
 
Example 3
Source File: Neo4JApiQueryPosLengthInject.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Collection<Neo4jPosLengthInjectMatch> evaluate() {
	final Collection<Neo4jPosLengthInjectMatch> matches = new ArrayList<>();

	final GraphDatabaseService graphDb = driver.getGraphDb();
	try (Transaction tx = graphDb.beginTx()) {
		// (segment:Segment)
		final Iterable<Node> segments = () -> graphDb.findNodes(Neo4jConstants.labelSegment);
		for (final Node segment : segments) {
			final Map<String, Object> match = new HashMap<>();
			match.put(VAR_SEGMENT, segment);
			matches.add(new Neo4jPosLengthInjectMatch(match));
		}
	}

	return matches;
}
 
Example 4
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 5
Source File: Neo4JApiQueryPosLength.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Collection<Neo4jPosLengthMatch> evaluate() {
	final Collection<Neo4jPosLengthMatch> matches = new ArrayList<>();

	final GraphDatabaseService graphDb = driver.getGraphDb();
	try (Transaction tx = graphDb.beginTx()) {
		// (segment:Segment)
		final Iterable<Node> segments = () -> graphDb.findNodes(Neo4jConstants.labelSegment);
		for (final Node segment : segments) {
			final Number lengthNumber = (Number) segment.getProperty(LENGTH);
			final int length = Neo4jHelper.numberToInt(lengthNumber);

			// segment.length <= 0
			if (length <= 0) {
				final Map<String, Object> match = new HashMap<>();
				match.put(VAR_SEGMENT, segment);
				match.put(VAR_LENGTH, length);
				matches.add(new Neo4jPosLengthMatch(match));
			}
		}
	}

	return matches;
}
 
Example 6
Source File: PatternRecognitionResource.java    From graphify with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a Neo4j node entity that contains the root pattern for performing hierarchical pattern recognition from.
 * @param db The Neo4j graph database service.
 * @return Returns a Neo4j node entity that contains the root pattern for performing hierarchical pattern recognition from.
 */
private static Node getRootPatternNode(GraphDatabaseService db) {
    Node patternNode;
    patternNode = new NodeManager().getOrCreateNode(GRAPH_MANAGER, GraphManager.ROOT_TEMPLATE, db);
    try(Transaction tx = db.beginTx()) {
        if (!patternNode.hasProperty("matches")) {
            patternNode.setProperty("matches", 0);
            patternNode.setProperty("threshold", GraphManager.MIN_THRESHOLD);
            patternNode.setProperty("root", 1);
            patternNode.setProperty("phrase", "{0} {1}");
        }
        tx.success();
    }
    return patternNode;
}
 
Example 7
Source File: DataRelationshipManager.java    From graphify with Apache License 2.0 5 votes vote down vote up
public void getOrCreateNode(Long start, Long end, GraphDatabaseService db) {
    List<Long> relList = relationshipCache.getIfPresent(start);

    Node startNode = db.getNodeById(start);

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

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

    if (!relList.contains(end)) {
        Transaction tx = db.beginTx();
        try {
            Node endNode = db.getNodeById(end);
            startNode.createRelationshipTo(endNode, withName(relationshipType));
            tx.success();
        } catch (final Exception e) {
            tx.failure();
        } finally {
            tx.close();
            relList.add(end);
            relationshipCache.put(start, relList);
        }
    }
}
 
Example 8
Source File: PageRank.java    From Neo4jSNA with Apache License 2.0 5 votes vote down vote up
public PageRank(GraphDatabaseService g) {
	rankMap = new Long2DoubleOpenHashMap();
	try(Transaction tx = g.beginTx()) {
		for(@SuppressWarnings("unused") Node n : GlobalGraphOperations.at(g).getAllNodes())
			nodeCount += 1;
		tx.success();
	}
	this.firstMember = ( 1.0 - this.dampingFactor ) / this.nodeCount;
}
 
Example 9
Source File: Neo4jModuleTest.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@Test(expected = WriteOperationsNotAllowedException.class)
public void graphDbReadOnlyWithApi() {
  GraphDatabaseService graphDb = injectorReadOnly.getInstance(GraphDatabaseService.class);
  Transaction tx = graphDb.beginTx();
  try {
    graphDb.createNode(Label.label("test"));
  } finally {
    tx.close();
  }
}
 
Example 10
Source File: Neo4JApiQuerySwitchMonitored.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Collection<Neo4jSwitchMonitoredMatch> evaluate() {
	final Collection<Neo4jSwitchMonitoredMatch> matches = new ArrayList<>();

	final GraphDatabaseService graphDb = driver.getGraphDb();
	try (Transaction tx = graphDb.beginTx()) {
		final Iterable<Node> sws = () -> graphDb.findNodes(Neo4jConstants.labelSwitch);
		// (sw:Switch)
		for (final Node sw : sws) {
			// (sw)-[:sensor]->(Sensor) NAC
			final Iterable<Relationship> relationshipSensors = sw.getRelationships(Direction.OUTGOING, Neo4jConstants.relationshipTypeMonitoredBy);

			boolean hasSensor = false;
			for (final Relationship relationshipSensor : relationshipSensors) {
				final Node sensor = relationshipSensor.getEndNode();
				if (sensor.hasLabel(Neo4jConstants.labelSensor)) {
					hasSensor = true;
					break;
				}
			}

			if (!hasSensor) {
				final Map<String, Object> match = new HashMap<>();
				match.put(VAR_SW, sw);
				matches.add(new Neo4jSwitchMonitoredMatch(match));
			}
		}
	}

	return matches;
}
 
Example 11
Source File: NodeManagerTest.java    From graphify with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetOrCreateNode() throws Exception {
    GraphDatabaseService db = setUpDb();
    NodeManager nodeManager = new NodeManager();
    NodeManager.globalNodeCache.invalidateAll();
    DataNodeManager.dataCache.invalidateAll();
    DataNodeManager dataNodeManager = new DataNodeManager();

    // Write some nodes to the database
    Node a = nodeManager.getOrCreateNode(dataNodeManager, "a", db);
    Node b = nodeManager.getOrCreateNode(dataNodeManager, "b", db);
    Node c = nodeManager.getOrCreateNode(dataNodeManager, "c", db);
    Node d = nodeManager.getOrCreateNode(dataNodeManager, "d", db);
    Node e = nodeManager.getOrCreateNode(dataNodeManager, "e", db);
    Node f = nodeManager.getOrCreateNode(dataNodeManager, "f", db);
    Node g = nodeManager.getOrCreateNode(dataNodeManager, "g", db);

    Assert.assertNotNull(a);
    Assert.assertNotNull(b);
    Assert.assertNotNull(c);
    Assert.assertNotNull(d);
    Assert.assertNotNull(e);
    Assert.assertNotNull(f);
    Assert.assertNotNull(g);

    String expected = "a";

    Transaction tx = db.beginTx();
    String actual = (String)a.getProperty("value");
    tx.success();
    Assert.assertEquals(expected, actual);
}
 
Example 12
Source File: OntologyGraphRuleTest.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@Test
public void ontology_isLoaded() {
  GraphDatabaseService graphDb = graphRule.getGraphDb();
  try (Transaction tx = graphDb.beginTx()) {
    assertThat(size(graphDb.getAllNodes()), is(greaterThan(0)));
    tx.success();
  }
}
 
Example 13
Source File: BasePerformanceTest.java    From graph_processing with MIT License 5 votes vote down vote up
private void populateDb(GraphDatabaseService db) {
    try ( Transaction tx = db.beginTx()) {
        db.execute(TestObjects.MOVIES_QUERY);
        db.execute(TestObjects.KNOWS_QUERY);
        tx.success();
    }
}
 
Example 14
Source File: DataImporterTest.java    From neo4j-rdbms-import with GNU General Public License v3.0 5 votes vote down vote up
private static String assertImport() {
    GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase(STORE_DIR);

    try (Transaction tx = db.beginTx()) {
        int nodes = IteratorUtil.count(db.getAllNodes());
        Assert.assertEquals(USERS, nodes);
        int rels = IteratorUtil.count(GlobalGraphOperations.at(db).getAllRelationships());
        Assert.assertEquals(FRIENDSHIPS, rels);
        return "Imported nodes " + nodes + " rels " + rels;
    } finally {
        db.shutdown();
    }
}
 
Example 15
Source File: Neo4jHelper.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
public static void cleanDb( GraphDatabaseService graphDatabaseService, boolean includeReferenceNode ) {
  Transaction tx = graphDatabaseService.beginTx();
  try {
    clearIndex(graphDatabaseService);
    removeNodes(graphDatabaseService, includeReferenceNode);
    tx.success();
  } catch (Throwable t) {
    tx.failure();
    throw new RuntimeException("Error cleaning database ",t);
  } finally {
    tx.close();
  }
}
 
Example 16
Source File: NeoGraph.java    From neo4jena with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes this graph.
 */
public NeoGraph(final GraphDatabaseService graphdb) {
	this.graphdb = graphdb;
	try(Transaction tx = graphdb.beginTx()) {
		nodeFactory = new UniqueNodeFactory(graphdb, this);
		relationshipFactory = new UniqueRelationshipFactory(graphdb, this);
	}
}
 
Example 17
Source File: TestUtil.java    From ongdb-lab-apoc with Apache License 2.0 5 votes vote down vote up
public static void testResult(GraphDatabaseService db, String call, Map<String, Object> params, Consumer<Result> resultConsumer) {
    try (Transaction tx = db.beginTx()) {
        Map<String, Object> p = (params == null) ? Collections.<String, Object>emptyMap() : params;
        resultConsumer.accept(db.execute(call, p));
        tx.success();
    }
}
 
Example 18
Source File: LabelPropagationPerformance.java    From graph_processing with MIT License 5 votes vote down vote up
private void populateDb(GraphDatabaseService db) {
    try ( Transaction tx = db.beginTx()) {
        db.execute(TestObjects.MOVIES_QUERY);
        db.execute(TestObjects.KNOWS_QUERY);
        tx.success();
    }
}
 
Example 19
Source File: WriterTest.java    From neo4j-mazerunner with Apache License 2.0 4 votes vote down vote up
private void createSampleGraph(GraphDatabaseService db) {

        List<Node> nodes = new ArrayList<>();

        int max = 200;
        Transaction tx = db.beginTx();
        Node partitionNode = db.createNode();
        partitionNode.addLabel(DynamicLabel.label("Category"));
        tx.success();
        tx.close();
        int count = 0;
        int partitionBlockCount = 50;

        tx = db.beginTx();
        // Create nodes
        for (int i = 0; i < max; i++) {

            nodes.add(db.createNode());
            nodes.get(i).addLabel(DynamicLabel.label("Node"));
            partitionNode.createRelationshipTo(nodes.get(i), withName("HAS_CATEGORY"));
            count++;
            if(count >= partitionBlockCount && i != max - 1) {

                count = 0;
                partitionNode = db.createNode();
                partitionNode.addLabel(DynamicLabel.label("Category"));

                tx.success();
                tx.close();
                tx = db.beginTx();

                System.out.println(i);
            }
        }

        tx.success();
        tx.close();

        tx = db.beginTx();
        // Create PageRank test graph
        for (int i = 0; i < (max / 2) - 1; i++) {
            nodes.get(i).createRelationshipTo(nodes.get(i + (max / 2)), withName("CONNECTED_TO"));
            nodes.get(i + (max / 2)).createRelationshipTo(nodes.get(i + 1), withName("CONNECTED_TO"));
            if(count >= partitionBlockCount / 2 && i != max - 1) {
                tx.success();
                tx.close();
                tx = db.beginTx();

                System.out.println("B: " + i);
            }
            if(i == (max / 2) - 2) {
                nodes.get((i + 1) + (max / 2)).createRelationshipTo(nodes.get(0), withName("CONNECTED_TO"));
                nodes.get(i + 1).createRelationshipTo(nodes.get((max / 2)), withName("CONNECTED_TO"));
            }
        }

        tx.success();
        tx.close();
    }
 
Example 20
Source File: GraphManagerTest.java    From graphify with Apache License 2.0 4 votes vote down vote up
private static String executeCypher(GraphDatabaseService db, String cypher, Map<String, Object> params) {

        Result result;

        List<Map<String, Object>> results = new ArrayList<>();

        try ( Transaction tx = db.beginTx() ) {
            result = db.execute(cypher, params);
            tx.success();



            while (result.hasNext()) {
                results.add(result.next());
            }

            tx.success();
            tx.close();
        }

        return new Gson().toJson(results);
    }