org.neo4j.graphdb.Transaction Java Examples

The following examples show how to use org.neo4j.graphdb.Transaction. 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: Neo4j.java    From SPADE with GNU General Public License v3.0 6 votes vote down vote up
public List<Map<String, Object>> executeQueryForSmallResult(String query){
		try(Transaction tx = graphDb.beginTx()){
			List<Map<String, Object>> listOfMaps = new ArrayList<Map<String, Object>>();
			Result result = null;
//			globalTxCheckin();
			try{
				result = graphDb.execute(query);
				while(result.hasNext()){
					listOfMaps.add(new HashMap<String, Object>(result.next()));
				}
			}catch(QueryExecutionException ex){
				logger.log(Level.SEVERE, "Neo4j Cypher query execution not successful!", ex);
			}finally{
				tx.success();
			}
			return listOfMaps;
		}
	}
 
Example #2
Source File: AtlasTransformerTest.java    From atlas with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void simpleRoadContraction() {
    List<FastNode> dummyNodesForWay1 = getDummyNodesForWay(20);
    Way way1 = getDummyWay(dummyNodesForWay1);

    fastWriter.start(graphDatabaseService);
    dummyNodesForWay1.stream().forEach(fastNode ->  fastWriter.addNode(fastNode));
    fastWriter.addWay(way1);
    fastWriter.finish();

    // this is a bug, i should count way start node as an inserted node
    assertFastNodeCountInDatabase(20,21);

    Transaction tx = graphDatabaseService.beginTx();
    ContractCriteria contractCriteria = new ContractCriteria();
    atlasTransformer.applyContraction(this.graphDatabaseService, contractCriteria);
    tx.success();
    tx.close();

    assertFastNodeCountInDatabase(20,4);
}
 
Example #3
Source File: QueryEngine.java    From paprika with GNU Affero General Public License v3.0 6 votes vote down vote up
public List<String> findKeysFromPackageName(String appName) throws CypherException, IOException {
    ArrayList<String> keys = new ArrayList<>();
    try (Transaction ignored = graphDatabaseService.beginTx()) {
        Result result = graphDatabaseService.execute("MATCH (n:App) WHERE n.package='"+appName+"' RETURN n.app_key as key");
        while ( result.hasNext() )
        {
            Map<String,Object> row = result.next();
            keys.add((String) row.get("key"));
        }
    }
    return keys;
}
 
Example #4
Source File: ReachabilityIndex.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
public void dropIndex() {
  if (indexExists()) {
    Transaction tx = graphDb.beginTx();

    // ...cleanup the index.
    int counter = 0;
    for (Node n : graphDb.getAllNodes()) {
      n.removeProperty(IN_LIST_PROPERTY);
      n.removeProperty(OUT_LIST_PROPERTY);
      tx = batchTransactions(tx, counter++);
    }

    // reset the flag.
    metaDataNode.setProperty(INDEX_EXISTS_PROPERTY, false);

    tx.success();
    tx.close();
    logger.info("Reachability index dropped.");
  } else {
    logger.warning("There was no reachability index to drop.");
  }
}
 
Example #5
Source File: CustomerProceduresTest.java    From ongdb-lab-apoc with Apache License 2.0 6 votes vote down vote up
@Test
    public void testRecommend() {
        GraphDatabaseService db = neo4j.getGraphDatabaseService();

        try (Transaction tx = db.beginTx()) {
            // CALL training.recommendOnly("Dee Dee Titley_0_linkedin") YIELD stringObjectMap RETURN stringObjectMap
//            Result res = db.execute("CALL training.recommendOnly(\"Dee Dee Titley_0_linkedin\") YIELD stringObjectMap RETURN stringObjectMap");

            Result res = db.execute("CALL zdr.index.search('linkin', 'name:china*', 10) YIELD node RETURN node");

//
//            System.out.println(res.resultAsString());
//            System.out.println(res.next());
//            Node node = (Node) res.next().get("stringObjectMap");
//            CustomerProcedures.Movie movie = (CustomerProcedures.Movie) res.next().get("stringObjectMap");
//            movie.stringObjectMap.forEach((k, v) -> System.out.println("key:value = " + k + ":" + v));
//            System.out.println(node.getId());
//            System.out.println(node.getLabels());
//            System.out.println(node.getRelationships());

        }
    }
 
Example #6
Source File: Neo4jIndexingTest.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
@Test
public void testBatchIndexToAutoIndex() throws IOException {
  BatchInserter inserter = BatchInserters.inserter(new File(path));
  BatchInserterIndexProvider indexProvider = new LuceneBatchInserterIndexProvider(inserter);
  BatchInserterIndex index =
      indexProvider.nodeIndex("node_auto_index", MapUtil.stringMap("type", "exact"));
  long node = inserter.createNode(MapUtil.map("foo", "bar"));
  index.add(node, MapUtil.map("foo", "bar"));
  index.flush();
  assertThat("Batch indexed node can be retrieved", index.get("foo", "bar").next(), is(node));
  indexProvider.shutdown();
  inserter.shutdown();
  graphDb = getGraphDb();
  try (Transaction tx = graphDb.beginTx()) {
    assertThat("AutoIndex is not enabled after reopening the graph", graphDb.index()
        .getNodeAutoIndexer().isEnabled(), is(false));
    assertThat("AutoIndexed properties are not maintained after closing the graph", graphDb
        .index().getNodeAutoIndexer().getAutoIndexedProperties(), is(empty()));
    assertThat("Batch index properties are in the index", graphDb.index().getNodeAutoIndexer()
        .getAutoIndex().query("foo", "bar").size(), is(1));
    tx.success();
  }
}
 
Example #7
Source File: Neo4j.java    From SPADE with GNU General Public License v3.0 6 votes vote down vote up
public Graph getEdges(int childVertexId, int parentVertexId)
{
    Graph resultGraph = new Graph();
    try( Transaction tx = graphDb.beginTx() )
    {
        IndexHits<Relationship> queryHits = edgeIndex.query("type:*", graphDb.getNodeById(childVertexId), graphDb.getNodeById(parentVertexId));
        for (Relationship currentRelationship : queryHits)
        {
            resultGraph.putVertex(convertNodeToVertex(currentRelationship.getStartNode()));
            resultGraph.putVertex(convertNodeToVertex(currentRelationship.getEndNode()));
            resultGraph.putEdge(convertRelationshipToEdge(currentRelationship));
        }
        queryHits.close();
        tx.success();
    }
    return resultGraph;
}
 
Example #8
Source File: VocabularyNeo4jImpl.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
@Override
public Optional<Concept> getConceptFromId(Query query) {
  String idQuery = StringUtils.strip(query.getInput(), "\"");
  idQuery = curieUtil.getIri(idQuery).orElse(idQuery);
  try (Transaction tx = graph.beginTx()) {
    Node node =
        graph.index().getNodeAutoIndexer().getAutoIndex().get(CommonProperties.IRI, idQuery)
            .getSingle();
    tx.success();
    Concept concept = null;
    if (null != node) {
      concept = transformer.apply(node);
    }
    return Optional.ofNullable(concept);
  }
}
 
Example #9
Source File: OwlPostprocessorTest.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws InterruptedException, ExecutionException {
  Transaction tx = graphDb.beginTx();
  enableIndexing();
  parent = graphDb.createNode();
  parent.setProperty(CommonProperties.IRI, "http://example.org/a");
  child = graphDb.createNode();
  child.createRelationshipTo(parent, OwlRelationships.RDFS_SUBCLASS_OF);
  grandChild = graphDb.createNode();
  grandChild.createRelationshipTo(child, OwlRelationships.RDFS_SUBCLASS_OF);
  equivalent = graphDb.createNode();
  equivalentSubclass = graphDb.createNode();
  equivalentSubclass.createRelationshipTo(equivalent, OwlRelationships.RDFS_SUBCLASS_OF);
  equivalent.createRelationshipTo(child, OwlRelationships.OWL_EQUIVALENT_CLASS);
  instance = graphDb.createNode();
  instance.createRelationshipTo(grandChild, OwlRelationships.RDF_TYPE);
  tx.success();
  postprocessor = new OwlPostprocessor(graphDb, Collections.<String, String>emptyMap());
  Map<String, String> categoryMap = new HashMap<>();
  categoryMap.put("http://example.org/a", "foo");
  tx.close();
  postprocessor.processCategories(categoryMap);
  tx = graphDb.beginTx();
}
 
Example #10
Source File: Neo4jGraphDatabase.java    From graphdb-benchmarks with Apache License 2.0 6 votes vote down vote up
@Override
public int getCommunitySize(int community)
{
    Set<Integer> nodeCommunities = new HashSet<Integer>();

    try (final Transaction tx = beginUnforcedTransaction())
    {
        try
        {
            ResourceIterable<Node> nodes = neo4jGraph.findNodesByLabelAndProperty(NODE_LABEL, COMMUNITY, community);
            for (Node n : nodes)
            {
                Integer nodeCommunity = (Integer) (n.getProperty(COMMUNITY));
                nodeCommunities.add(nodeCommunity);
            }
            tx.success();
        }
        catch (Exception e)
        {
            tx.failure();
            throw new BenchmarkingException("unable to get community size", e);
        }
    }

    return nodeCommunities.size();
}
 
Example #11
Source File: NodeManagerTest.java    From graphify with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetNodeProperty() 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
    Transaction tx1 = db.beginTx();
    Node a = nodeManager.getOrCreateNode(dataNodeManager, "a", db);
    tx1.success();
    Assert.assertNotNull(a);

    String expected = "success";
    nodeManager.setNodeProperty(a.getId(), "test", expected, db);
    Transaction tx = db.beginTx();
    String actual = (String)NodeManager.getNodeFromGlobalCache(a.getId()).get("test");
    tx.success();

    Assert.assertEquals(expected, actual);
}
 
Example #12
Source File: Neo4JApiQueryRouteSensorInject.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Collection<Neo4jRouteSensorInjectMatch> evaluate() {
	final Collection<Neo4jRouteSensorInjectMatch> 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) {

			final Iterable<Node> sensors = Neo4jUtil.getAdjacentNodes(route, Neo4jConstants.relationshipTypeRequires,
					Direction.OUTGOING, Neo4jConstants.labelSensor);

			for (final Node sensor : sensors) {
				final Map<String, Object> match = new HashMap<>();
				match.put(QueryConstants.VAR_ROUTE, route);
				match.put(QueryConstants.VAR_SENSOR, sensor);
				matches.add(new Neo4jRouteSensorInjectMatch(match));
			}
		}
	}

	return matches;
}
 
Example #13
Source File: Neo4jGraphDatabase.java    From graphdb-benchmarks with Apache License 2.0 6 votes vote down vote up
@Override
public void initCommunityProperty()
{
    int communityCounter = 0;

    // maybe commit changes every 1000 transactions?
    try (final Transaction tx = beginUnforcedTransaction())
    {
        try
        {
            for (Node n : GlobalGraphOperations.at(neo4jGraph).getAllNodes())
            {
                n.setProperty(NODE_COMMUNITY, communityCounter);
                n.setProperty(COMMUNITY, communityCounter);
                communityCounter++;
            }
            tx.success();
        }
        catch (Exception e)
        {
            tx.failure();
            throw new BenchmarkingException("unable to initialize community property", e);
        }
    }
}
 
Example #14
Source File: ReachabilityIndex.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
/**
 * @return The hop coverage for each node sorted in descending order.
 */
SortedSet<Entry<Long, Integer>> getHopCoverages(Predicate<Node> nodePredicate) {
  SortedSet<Entry<Long, Integer>> nodeSet = new TreeSet<Entry<Long, Integer>>(
      new Comparator<Entry<Long, Integer>>() {
        @Override
        public int compare(Entry<Long, Integer> a, Entry<Long, Integer> b) {
          int difference = b.getValue() - a.getValue();
          return (0 != difference) ? difference : (int) (a.getKey() - b.getKey());
        }
      });

  try (Transaction tx = graphDb.beginTx()) {
    for (Node n : graphDb.getAllNodes()) {
      if (n.getId() > 0) {
        int relationshipCount = nodePredicate.apply(n) ? size(n.getRelationships()) : -1;
        nodeSet.add(new AbstractMap.SimpleEntry<Long, Integer>(n.getId(), relationshipCount));
      }
    }
  }

  return nodeSet;
}
 
Example #15
Source File: Neo4jSingleInsertion.java    From graphdb-benchmarks with Apache License 2.0 6 votes vote down vote up
@Override
public void relateNodes(Node src, Node dest)
{
    try (final Transaction tx = ((GraphDatabaseAPI) neo4jGraph).tx().unforced().begin())
    {
        try
        {
            src.createRelationshipTo(dest, Neo4jGraphDatabase.RelTypes.SIMILAR);
            tx.success();
        }
        catch (Exception e)
        {
            tx.failure();
            throw new BenchmarkingException("unable to relate nodes", e);
        }
    }
}
 
Example #16
Source File: VocabularyNeo4jImpl.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
List<Concept> limitHits(IndexHits<Node> hits, Query query) {
  try (Transaction tx = graph.beginTx()) {
    Iterable<Concept> concepts = Iterables.transform(hits, transformer);
    if (!query.isIncludeDeprecated()) {
      concepts = filter(concepts, new Predicate<Concept>() {
        @Override
        public boolean apply(Concept concept) {
          return !concept.isDeprecated();
        }
      });
    }
    Iterable<Concept> limitedHits = limit(concepts, query.getLimit());
    List<Concept> ret = newArrayList(limitedHits);
    tx.success();
    return ret;
  }
}
 
Example #17
Source File: SchemaIndexesTest.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
@Test
public void schemaOnMultipleProperties() {
  Neo4jConfiguration configuration = new Neo4jConfiguration();
  configuration.setLocation(graphPath.getRoot().getAbsolutePath());
  Set<String> property = new HashSet<String>();
  property.add("property");
  property.add("property2");
  Map<String, Set<String>> schemaIndexes = new HashMap<String, Set<String>>();
  schemaIndexes.put("label", property);
  configuration.setSchemaIndexes(schemaIndexes);

  Neo4jModule.setupSchemaIndexes(graphDb, configuration);

  try (Transaction tx = graphDb.beginTx()) {
    assertThat(size(graphDb.schema().getIndexes()), is(2));
    tx.success();
    tx.close();
  }
}
 
Example #18
Source File: Neo4jGraphDatabase.java    From graphdb-benchmarks with Apache License 2.0 6 votes vote down vote up
@Override
public int getNodeCount()
{
    int nodeCount = 0;
    try (final Transaction tx = beginUnforcedTransaction())
    {
        try
        {
            nodeCount = IteratorUtil.count(GlobalGraphOperations.at(neo4jGraph).getAllNodes());
            tx.success();
        }
        catch (Exception e)
        {
            tx.failure();
            throw new BenchmarkingException("unable to get node count", e);
        }
    }

    return nodeCount;
}
 
Example #19
Source File: DeepGLIntegrationTest.java    From ml-models with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setupGraph() throws KernelException {

    final String cypher =
            "CREATE (a:Node {name:'a'})\n" +
                    "CREATE (b:Node {name:'b'})\n" +
                    "CREATE (c:Node {name:'c'})\n" +
                    "CREATE (d:Node {name:'d'})\n" +
                    "CREATE (e:Node {name:'e'})\n" +
                    "CREATE (f:Node {name:'f'})\n" +
                    "CREATE (g:Node {name:'g'})\n" +
                    "CREATE" +
                    " (a)-[:TYPE]->(b),\n" +
                    " (a)-[:TYPE]->(f),\n" +
                    " (b)-[:TYPE]->(c),\n" +
                    " (c)-[:TYPE]->(d),\n" +
                    " (d)-[:TYPE]->(g),\n" +
                    " (d)-[:TYPE]->(e)";


    db = TestDatabaseCreator.createTestDatabase();

    try (Transaction tx = db.beginTx()) {
        db.execute(cypher);
        tx.success();
    }

    db.getDependencyResolver()
            .resolveDependency(Procedures.class)
            .registerProcedure(DeepGLProc.class);

}
 
Example #20
Source File: DataImporterEmployeeTest.java    From neo4j-rdbms-import with GNU General Public License v3.0 5 votes vote down vote up
private static String importInfo() {
    GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase(STORE_DIR);

    try (Transaction tx = db.beginTx()) {
        int nodes = IteratorUtil.count(db.getAllNodes());
        int rels = IteratorUtil.count(GlobalGraphOperations.at(db).getAllRelationships());
        return "Imported nodes " + nodes + " rels " + rels;
    } finally {
        db.shutdown();
    }
}
 
Example #21
Source File: AtlasTraversalTest.java    From atlas with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void getWayNodesIncludingWayStart() {
    List<FastNode> dummyNodesForWay1 = getDummyNodesForWay(20);
    Way way1 = getDummyWay(dummyNodesForWay1);

    fastWriter.start(graphDatabaseService);
    dummyNodesForWay1.stream().forEach(node -> fastWriter.addNode(node));
    Node wayNode = fastWriter.addWay(way1);

    Transaction tx = graphDatabaseService.beginTx();
    assertPathContainsNodesAndJustNodes(wayNode, dummyNodesForWay1);
    tx.close();
    tx.success();
}
 
Example #22
Source File: InMemoryNeoTest.java    From Neo4jSNA with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    db = new TestGraphDatabaseFactory().newImpermanentDatabase();
    try (Transaction tx = db.beginTx()) {
        this.initGraph();
        tx.success();
    }
}
 
Example #23
Source File: Neo4jGraphDatabase.java    From graphdb-benchmarks with Apache License 2.0 5 votes vote down vote up
@Override
public Set<Integer> getCommunitiesConnectedToNodeCommunities(int nodeCommunities)
{
    Set<Integer> communities = new HashSet<Integer>();
    try (final Transaction tx = beginUnforcedTransaction())
    {
        try
        {
            ResourceIterable<Node> nodes = neo4jGraph.findNodesByLabelAndProperty(Neo4jGraphDatabase.NODE_LABEL,
                NODE_COMMUNITY, nodeCommunities);
            for (Node n : nodes)
            {
                for (Relationship r : n.getRelationships(RelTypes.SIMILAR, Direction.OUTGOING))
                {
                    Node neighbour = r.getOtherNode(n);
                    Integer community = (Integer) (neighbour.getProperty(COMMUNITY));
                    communities.add(community);
                }
            }
            tx.success();
        }
        catch (Exception e)
        {
            tx.failure();
            throw new BenchmarkingException("unable to get communities connected to node communities", e);
        }
    }

    return communities;
}
 
Example #24
Source File: QuartileCalculator.java    From paprika with GNU Affero General Public License v3.0 5 votes vote down vote up
public void calculateNumberofInstructionsQuartile() throws IOException {
    Map<String, Double> res;
    Result result;
    try (Transaction ignored = graphDatabaseService.beginTx()) {
        String query = "MATCH (n:Method) WHERE NOT HAS(n.is_getter) AND NOT HAS(n.is_setter) AND n.number_of_instructions > 0 RETURN percentileCont(n.number_of_instructions,0.25) as Q1, percentileCont(n.number_of_instructions,0.5) as MED, percentileCont(n.number_of_instructions,0.75) as Q3";
        result = graphDatabaseService.execute(query);
        res = calculeTresholds(result);
    }
    queryEngine.statsToCSV(res, "_STAT_NB_INSTRUCTIONS.csv");
}
 
Example #25
Source File: ClosenessCentralityTest.java    From graph_processing with MIT License 5 votes vote down vote up
@Test
public void shouldCalculateClosenessCentralityTwo() throws IOException {
    Closeness centrality = new Closeness(db);
    centrality.compute("Person", "KNOWS", 0);

    long id = (long) TestUtils.getPersonEntry("Tom Hanks", db).get("id");
    try ( Transaction tx = db.beginTx()) {
        assertEquals(0.005235602094240838, centrality.getResult(id), 0.1D);
    }
}
 
Example #26
Source File: HeavyBroadcastReceiverQuery.java    From paprika with GNU Affero General Public License v3.0 5 votes vote down vote up
public void execute(boolean details) throws CypherException, IOException {
    Result result;
    try (Transaction ignored = graphDatabaseService.beginTx()) {
        String query = "MATCH (c:Class{is_broadcast_receiver:true})-[:CLASS_OWNS_METHOD]->(m:Method{name:'onReceive'}) WHERE m.number_of_instructions > "+veryHigh_noi+" AND m.cyclomatic_complexity>"+veryHigh_cc+" return m.app_key as app_key";
        if(details){
            query += ",m.full_name as full_name";
        }else{
            query += ",count(m) as HBR";
        }
        result = graphDatabaseService.execute(query);
        queryEngine.resultToCSV(result,"_HBR_NO_FUZZY.csv");
    }
}
 
Example #27
Source File: RoadContracter.java    From atlas with GNU General Public License v3.0 5 votes vote down vote up
public boolean contractRoad() {
    Transaction tx = db.beginTx();
    Iterator<Node> wayStartIterator = db.findNodes(Label.label("WAY_START"));
    while(wayStartIterator.hasNext()) {
        Node wayStartNode = wayStartIterator.next();

    }
    tx.success();
    tx.close();
    return true;
}
 
Example #28
Source File: QuartileCalculator.java    From paprika with GNU Affero General Public License v3.0 5 votes vote down vote up
public void calculateCyclomaticComplexityQuartile() throws IOException {
    Map<String, Double> res;
    Result result;
    try (Transaction ignored = graphDatabaseService.beginTx()) {
        String query = "MATCH (n:Method) WHERE NOT HAS(n.is_getter) AND NOT HAS(n.is_setter) AND n.cyclomatic_complexity > 0 RETURN percentileCont(n.cyclomatic_complexity,0.25) as Q1, percentileCont(n.cyclomatic_complexity,0.5) as MED, percentileCont(n.cyclomatic_complexity,0.75) as Q3";
        result = graphDatabaseService.execute(query);
        res = calculeTresholds(result);
    }
    queryEngine.statsToCSV(res, "_STAT_CYCLOMATIC_COMPLEXITY.csv");
}
 
Example #29
Source File: Neo4jHealthCheck.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@Override
protected Result check() throws Exception {
  int count = 0;
  try (Transaction tx = graphDb.beginTx()) {
    count = size(graphDb.getAllNodes());
    tx.success();
  }

  if (count > 0) {
    return Result.healthy();
  } else {
    return Result.unhealthy("There are no nodes in the graph.");
  }
}
 
Example #30
Source File: AtlasTest.java    From atlas with GNU General Public License v3.0 5 votes vote down vote up
public void assertFastNodeCountInDatabase(int noOfFastNodesExpected, int noOfNodesInDatabaseExpected) {
    Transaction tx = graphDatabaseService.beginTx();
    assertTrue(graphDatabaseService.getAllNodes().stream().count() == noOfNodesInDatabaseExpected);
    assertTrue(fastWriter.numberOfNodesAdded == noOfFastNodesExpected);
    tx.success();
    tx.close();
}