Java Code Examples for org.neo4j.graphdb.GraphDatabaseService

The following examples show how to use org.neo4j.graphdb.GraphDatabaseService. These examples are extracted from open source projects. 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
@Test
public void checkCallsInitAndFinish() {
  TinkerPopGraphManager graph = makeGraph("1");
  DatabaseCheck databaseCheck1 = mock(DatabaseCheck.class);
  DatabaseCheck databaseCheck2 = mock(DatabaseCheck.class);

  DatabaseValidator instance =
    new DatabaseValidator(graph, databaseCheck1, databaseCheck2);

  instance.check();

  InOrder inOrder = inOrder(databaseCheck1, databaseCheck2);
  inOrder.verify(databaseCheck1).init(any(Graph.class), any(GraphDatabaseService.class));
  inOrder.verify(databaseCheck2).init(any(Graph.class), any(GraphDatabaseService.class));
  inOrder.verify(databaseCheck1).check(any(Vertex.class));
  inOrder.verify(databaseCheck2).check(any(Vertex.class));
  inOrder.verify(databaseCheck1).finish();
  inOrder.verify(databaseCheck2).finish();
}
 
Example 2
Source Project: extended-objects   Source File: GraphDbBootstrapTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void bootstrap() throws URISyntaxException {
    GraphDatabaseService graphDatabaseService = new TestGraphDatabaseFactory().newImpermanentDatabase();
    Properties properties = new Properties();
    properties.put(GraphDatabaseService.class.getName(), graphDatabaseService);
    XOUnit xoUnit = XOUnit.builder().uri(new URI("graphDb:///")).provider(EmbeddedNeo4jXOProvider.class).types(singletonList(A.class))
            .properties(properties).build();
    XOManagerFactory xoManagerFactory = XO.createXOManagerFactory(xoUnit);
    XOManager xoManager = xoManagerFactory.createXOManager();
    xoManager.currentTransaction().begin();
    A a = xoManager.create(A.class);
    a.setName("Test");
    xoManager.currentTransaction().commit();
    xoManager.close();
    xoManagerFactory.close();
    try (Transaction transaction = graphDatabaseService.beginTx()) {
        ResourceIterator<Node> iterator = graphDatabaseService.findNodes(label("A"), "name", "Test");
        assertThat(iterator.hasNext(), equalTo(true));
        Node node = iterator.next();
        assertThat(node.hasLabel(label("A")), equalTo(true));
        assertThat(node.getProperty("name"), equalTo((Object) "Test"));
        transaction.success();
    }
}
 
Example 3
Source Project: SnowGraph   Source File: MailListExtractor.java    License: Apache License 2.0 6 votes vote down vote up
public void run(GraphDatabaseService db) {
    this.db = db;
    MboxHandler myHandler = new MboxHandler();
    myHandler.setDb(db);
    MimeConfig config=new MimeConfig();
    config.setMaxLineLen(-1);
    parser = new MimeStreamParser(config);
    parser.setContentHandler(myHandler);
    parse(new File(mboxPath));
    try (Transaction tx = db.beginTx()) {
        for (String address : myHandler.getMailUserNameMap().keySet()) {
            Node node = myHandler.getMailUserMap().get(address);
            node.setProperty(MAILUSER_NAMES, String.join(", ", myHandler.getMailUserNameMap().get(address)));
        }
        tx.success();
    }
    try (Transaction tx = db.beginTx()) {
        for (String mailId : myHandler.getMailReplyMap().keySet()) {
            Node mailNode = myHandler.getMailMap().get(mailId);
            Node replyNode = myHandler.getMailMap().get(myHandler.getMailReplyMap().get(mailId));
            if (mailNode != null & replyNode != null)
                mailNode.createRelationshipTo(replyNode, RelationshipType.withName(MailListExtractor.MAIL_IN_REPLY_TO));
        }
        tx.success();
    }
}
 
Example 4
Source Project: graphify   Source File: NodeManager.java    License: Apache License 2.0 6 votes vote down vote up
public Object getNodeProperty(Long id, String key, GraphDatabaseService graphDb)
{
    boolean success;

    // Update the node's property in cache
    Map<String, Object> node = globalNodeCache.getIfPresent(id);

    if(node == null)
    {
        // The node isn't available in the cache, go to the database and retrieve it
        success = addNodeToCache((gdb, cache) -> getNodeHashMap(id, gdb, cache), graphDb);
        if(success) node = globalNodeCache.getIfPresent(id);
    }

    return node != null ? node.get(key) : null;
}
 
Example 5
@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 6
Source Project: graphify   Source File: VectorUtilTest.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean testOnText(String text, String label, GraphDatabaseService db, GraphManager graphManager) {
    Map<String, List<LinkedHashMap<String, Object>>> hashMap = VectorUtil.similarDocumentMapForVector(db, graphManager,
            cleanText(text), graphManager.getDecisionTree(getRootPatternNode(db, graphManager).getId(), db));

    // Validate guess
    ArrayList classes = (ArrayList) hashMap.get("classes");

    if (classes.size() > 0) {
        LinkedHashMap className = (LinkedHashMap) classes.stream().findFirst().get();

        return className.get("class").equals(label);
    }
    else
    {
        return false;
    }
}
 
Example 7
Source Project: SciGraph   Source File: Neo4jModule.java    License: Apache License 2.0 6 votes vote down vote up
public static void setupSchemaIndexes(GraphDatabaseService graphDb, Neo4jConfiguration config) {
  Map<String, Set<String>> schemaIndexes = config.getSchemaIndexes();
  for (Map.Entry<String, Set<String>> entry : schemaIndexes.entrySet()) {
    Label label = Label.label(entry.getKey());
    for (String property : entry.getValue()) {
      try (Transaction tx = graphDb.beginTx()) {
        Schema schema = graphDb.schema();
        IndexDefinition indexDefinition = schema.indexFor(label).on(property).create();
        tx.success();
        tx.close();

        Transaction tx2 = graphDb.beginTx();
        schema.awaitIndexOnline(indexDefinition, 2, TimeUnit.MINUTES);
        tx2.success();
        tx2.close();
      }
    }
  }
}
 
Example 8
Source Project: graphify   Source File: NodeManagerTest.java    License: 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 9
Source Project: neo4jena   Source File: LUBM.java    License: Apache License 2.0 6 votes vote down vote up
public static void write(GraphDatabaseService njgraph) {
	Logger log= Logger.getLogger(Wine.class);
	InputStream in = FileManager.get().open( inputFileName );
	if (in == null) {
           throw new IllegalArgumentException( "File: " + inputFileName + " not found");
       }
       
	Model model = ModelFactory.createDefaultModel();
       model.read(in,"","RDF");
       double triples = model.size();
       log.info("Model loaded with " +  triples + " triples");
       System.out.println("Model loaded with " +  triples + " triples");
       
	NeoGraph graph = new NeoGraph(njgraph);
	graph.startBulkLoad();
	log.info("Connection created");
	Model njmodel = ModelFactory.createModelForGraph(graph);
	log.info("NeoGraph Model initiated");
	System.out.println("NeoGraph Model initiated");
	StopWatch watch = new StopWatch();
	//log.info(njmodel.add(model));
	njmodel.add(model);
	log.info("Storing completed (ms): " + watch.stop());
	graph.stopBulkLoad();
	System.out.println("Storing completed (ms): " + watch.stop());
}
 
Example 10
Source Project: Project   Source File: Neo4jConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean(destroyMethod="shutdown")
public GraphDatabaseService graphDatabaseService() {	
	/*
	 * 配置嵌入式数据库
	 * 在Neo4j中,嵌入式数据库不要与内存数据库相混淆。
	 * 在这里,“嵌入式”指的是数据库引擎与应用运行在同一个JVM中,作为应用的一部分,
	 * 而不是独立的服务器。数据依然会持久化到文件系统中(在本例中,也就是“/tmp/graphdb”中)。
	 */
	return new GraphDatabaseFactory()
			.newEmbeddedDatabase("/tmp/graphdb");
}
 
Example 11
Source Project: ongdb-lab-apoc   Source File: ShortestPathTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void allPathsTightness() {
    GraphDatabaseService db = neo4j.getGraphDatabaseService();

    try (Transaction tx = db.beginTx()) {

        List<Long> sourceIds = new ArrayList<>();
        sourceIds.add(123l);
        sourceIds.add(223l);
        sourceIds.add(223l);

        List<Long> targetIds = new ArrayList<>();
        targetIds.add(32423l);
        targetIds.add(4353l);
        targetIds.add(4353l);

        List<Double> distanceSTE = new ArrayList<>();
        distanceSTE.add(23.0);
        distanceSTE.add(324.0);
        distanceSTE.add(324.0);

        Map<String, Object> map = new HashMap<>();
        map.put("sourceIds", sourceIds);
        map.put("targetIds", targetIds);
        map.put("distanceSTE", distanceSTE);

        Result res = db.execute("CALL zdr.shortestPath.allPathsTightness({sourceIds},{targetIds},{distanceSTE}) YIELD source,target,distance,tightnessSort RETURN source,target,distance,tightnessSort", map);

        while (res.hasNext()) {
            Map map2 = res.next();
            System.out.println(map2.get("source") + " " + map2.get("target") + " " + map2.get("distance") + " " + map2.get("tightnessSort"));
        }

    }
}
 
Example 12
Source Project: neo4jena   Source File: Wine.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	GraphDatabaseService njgraph = new GraphDatabaseFactory().newEmbeddedDatabase(NEO_STORE);
	
	Wine.write(njgraph);
	Wine.search(njgraph);
	njgraph.shutdown();
}
 
Example 13
Source Project: neo4j-mazerunner   Source File: MazerunnerService.java    License: Apache License 2.0 5 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/warmup")
public Response warmup(@Context GraphDatabaseService db) {
    return Response.status(200)
            .entity("{ \"result\": \"success\" }")
            .type(MediaType.APPLICATION_JSON).build();
}
 
Example 14
Source Project: ongdb-lab-apoc   Source File: TestUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void testCallCount(GraphDatabaseService db, String call, Map<String, Object> params, final int count) {
    testResult(db, call, params, (res) -> {
        int left = count;
        while (left > 0) {
            assertTrue("Expected " + count + " results, but got only " + (count - left), res.hasNext());
            res.next();
            left--;
        }
        assertFalse("Expected " + count + " results, but there are more ", res.hasNext());
    });
}
 
Example 15
Source Project: graph_processing   Source File: DegreeCentralityTest.java    License: 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 16
Source Project: SciGraph   Source File: OntologyGraphRuleTest.java    License: 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 17
Source Project: graphify   Source File: GraphManagerTest.java    License: 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 Node getRootPatternNode(GraphDatabaseService db, GraphManager graphManager) {
    Node patternNode;
    patternNode = graphManager.getOrCreateNode(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 18
Source Project: atlas   Source File: TestUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static void testCall(GraphDatabaseService db, String call,Map<String,Object> params, Consumer<Map<String, Object>> consumer) {
    testResult(db, call, params, (res) -> {
        try {
            assertTrue(res.hasNext());
            Map<String, Object> row = res.next();
            consumer.accept(row);
            assertFalse(res.hasNext());
        } catch(Throwable t) {
            printFullStackTrace(t);
            throw t;
        }
    });
}
 
Example 19
Source Project: neo4j-mazerunner   Source File: WriterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteToHadoop() throws Exception {
    GraphDatabaseService db = setUpDb();

    // Use test configurations
    ConfigurationLoader.testPropertyAccess = true;

    createSampleGraph(db);

    Writer.exportSubgraphToHDFS(db);
}
 
Example 20
Source Project: SciGraph   Source File: TransactionalInterceptorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
  tx = mock(Transaction.class);
  graphDb = mock(GraphDatabaseService.class);
  interceptor.graphDb = graphDb;
  when(interceptor.graphDb.beginTx()).thenReturn(tx);
  invocation = mock(MethodInvocation.class);
}
 
Example 21
Source Project: atlas   Source File: TestUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static void registerProcedure(GraphDatabaseService db, Class<?>...procedures) throws KernelException {
    Procedures proceduresService = ((GraphDatabaseAPI) db).getDependencyResolver().resolveDependency(Procedures.class);
    for (Class<?> procedure : procedures) {
        proceduresService.registerProcedure(procedure,true);
        proceduresService.registerFunction(procedure, true);
        proceduresService.registerAggregationFunction(procedure, true);
    }
}
 
Example 22
Source Project: graphify   Source File: NodeManager.java    License: Apache License 2.0 5 votes vote down vote up
public boolean setNodeProperty(Long id, String key, Object value, GraphDatabaseService graphDb)
{
    boolean success = true;

    // Update the node's property in cache
    Map<String, Object> node = globalNodeCache.getIfPresent(id);

    if(node == null)
    {
        // The node isn't available in the cache, go to the database and retrieve it
        success = addNodeToCache((gdb, cache) -> getNodeHashMap(id, gdb, cache), graphDb);
        if(success) node = globalNodeCache.getIfPresent(id);
    }

    // Set the node property
    if (node != null) {
        node.put(key, value);
    }

    // TODO: Remove this in favor of a distributed messaging bus architecture
    Transaction tx = graphDb.beginTx();
    graphDb.getNodeById(id).setProperty(key, value);
    tx.success();
    tx.close();

    return success;
}
 
Example 23
Source Project: graphify   Source File: PatternRecognitionResource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Classify a body of text using the training model stored in the graph database.
 * @param body The JSON model that binds to the LabeledText class model.
 * @param db The Neo4j graph database service.
 * @return Returns a sorted list of classes ranked on probability.
 * @throws IOException
 */
@POST
@Path("/classify")
@Produces(MediaType.APPLICATION_JSON)
public Response classify(String body, @Context GraphDatabaseService db) throws IOException {
    HashMap<String, Object> input;
    try {

        input = objectMapper.readValue(body, HashMap.class);

        String text;

        if(input.containsKey("text")) {
            text = ((String) input.get("text"));
        }
        else
        {
            throw new Exception("Error parsing JSON");
        }

        DecisionTree<Long> tree = new DecisionTree<>(getRootPatternNode(db).getId(), new scala.collection.mutable.HashMap<>(), db, GRAPH_MANAGER);
        // This method trains a model on a supplied label and text content
        String result = new Gson().toJson(VectorUtil.similarDocumentMapForVector(db, GRAPH_MANAGER, cleanText(text), tree));

        return Response.ok()
                .entity(result)
                .type(MediaType.APPLICATION_JSON)
                .build();

    } catch (Exception e) {
        return Response.status(400).entity(String.format("{\"error\":\"%s %s\"}", e.toString(), Arrays.toString(e.getStackTrace()))).build();
    }
}
 
Example 24
Source Project: neo4j-versioner-core   Source File: RollbackBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldBuildCorrectProcedureInstance() {
    GraphDatabaseService db = mock(GraphDatabaseService.class);
    Log log = mock(Log.class);

    Optional<Rollback> result = new RollbackBuilder().withDb(db).withLog(log).build();

    assertThat(result.isPresent(), is(true));
    assertThat(result.get().db, is(db));
    assertThat(result.get().log, is(log));
}
 
Example 25
Source Project: neo4j-versioner-core   Source File: InitBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldBuildCorrectProcedureInstance() {
    GraphDatabaseService db = mock(GraphDatabaseService.class);
    Log log = mock(Log.class);

    Optional<Init> result = new InitBuilder().withDb(db).withLog(log).build();

    assertThat(result.isPresent(), is(true));
    assertThat(result.get().db, is(db));
    assertThat(result.get().log, is(log));
}
 
Example 26
Source Project: graph_processing   Source File: LabelPropagationTest.java    License: 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 27
Source Project: neo4jena   Source File: Course.java    License: Apache License 2.0 5 votes vote down vote up
public static void write(GraphDatabaseService njgraph) {
	InputStream in = FileManager.get().open( inputFileName );
	if (in == null) {
           throw new IllegalArgumentException( "File: " + inputFileName + " not found");
       }
       
	Model model = ModelFactory.createDefaultModel();
       model.read(in,"","TTL");
       double triples = model.size();
       log.info("Model loaded with " +  triples + " triples");
       System.out.println("Model loaded with " +  triples + " triples");
       Map<String, String> prefixMap = model.getNsPrefixMap();
      // System.out.println("Prefix Mapping: " + prefixMap);
       
	NeoGraph graph = new NeoGraph(njgraph);
	graph.getPrefixMapping().setNsPrefixes(prefixMap);
	graph.startBulkLoad();
	log.info("Connection created");
	Model njmodel = ModelFactory.createModelForGraph(graph);
	log.info("NeoGraph Model initiated");
	System.out.println("NeoGraph Model initiated");
	
	//log.info(njmodel.add(model));
	//njmodel.add(model);
	StmtIterator iterator = model.listStatements();
	StopWatch watch = new StopWatch();
	int count = 0;
	while(iterator.hasNext()){
		njmodel.add(iterator.next());
		count++;
	}
	System.out.println("Total triples loaded are:"+ count);
	graph.stopBulkLoad();
	//log.info("Storing completed (ms): " + watch.stop());
	System.out.println("Storing completed (ms): " + watch.stop());
}
 
Example 28
Source Project: graphify   Source File: VectorUtilTest.java    License: Apache License 2.0 5 votes vote down vote up
private static Node getRootPatternNode(GraphDatabaseService db, GraphManager graphManager) {
    Node patternNode;
    patternNode = new NodeManager().getOrCreateNode(graphManager, 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 29
Source Project: SciGraph   Source File: GraphDump.java    License: Apache License 2.0 5 votes vote down vote up
public static void dumpGraph(GraphDatabaseService graphDb) {
  for (Node node: graphDb.getAllNodes()) {
    dumpNode(node);
  }
  for (Relationship relationship: graphDb.getAllRelationships()) {
    dumpRelationship(relationship);
  }
}
 
Example 30
Source Project: SnowGraph   Source File: SnowGraphBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private void run(){
    GraphDatabaseService graph=new GraphDatabaseFactory().newEmbeddedDatabase( new File(config.getGraphPath()) );
    for (int i=0;i<extractors.size();i++) {
        System.out.println(extractors.get(i).getClass().getName()+" started.");
        extractors.get(i).run(graph);
        extractors.set(i, new DefaultExtractor());
        System.gc();
    }
}