Java 类org.neo4j.graphdb.Transaction 实例源码

项目:codemodel-rifle    文件:ExportGraph.java   
public void cfg(String branchId) throws IOException {
    Transaction transaction = dbServices.beginTx();

    final File dot = File.createTempFile("dot", null);
    dot.deleteOnExit();

    Walker walker = new CfgWalker(dbServices);

    NewlineFilterStream fileOutputStream = new NewlineFilterStream(new FileOutputStream(dot));
    new GraphvizWriter().emit(fileOutputStream, walker);
    fileOutputStream.close();

    ProcessBuilder builder = new ProcessBuilder("dot", "-Tpng", dot.getAbsolutePath());
    builder.redirectErrorStream(true);
    Process process = builder.start();

    final InputStream inputStream = process.getInputStream();
    final BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);

    ByteStreams.copy(bufferedInputStream, out);
}
项目:flight-management-system-java    文件:MainWindow.java   
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
    // TODO add your handling code here:
    try (Transaction tx = db.beginTx()) {
        Node vols = db.createNode(Main.Tables.Vol);
        Node avions = db.createNode(Main.Tables.Avion);
        Node departs = db.createNode(Main.Tables.Depart);
        Node passagers = db.createNode(Main.Tables.Passager);
        Node personnels = db.createNode(Main.Tables.Personnel);
        Node naviguants = db.createNode(Main.Tables.Naviguant);
        Node nonNaviguants = db.createNode(Main.Tables.NonNaviguant);
        Node pilotes = db.createNode(Main.Tables.Pilote);
        Node quantiteAvion = db.createNode(Main.Tables.QuantiteAvion);
        Relationship constituer = vols.createRelationshipTo(departs, Relations.Constituer);
        Relationship enregistrer = passagers.createRelationshipTo(departs, Relations.Enregistrer);
        Relationship affecterPersonnel = personnels.createRelationshipTo(departs, Relations.AffecterPersonnel);
        Relationship affecterAvion = avions.createRelationshipTo(departs, Relations.AffecterAvion);
    }
}
项目:flight-management-system-java    文件:Depart.java   
public void insertBd() {
    Result res;
    try (Transaction tx = db.beginTx()) {
        Node depart = db.createNode(Main.Tables.Depart);
        depart.setProperty("numero",numero);
        depart.setProperty("date",date);
        res = db.execute("MATCH (a:Avion), (d:Depart) WHERE a.numero="+avion+" AND d.numero="+numero+" CREATE (a)-[:Affecter]->(d)");
        res = db.execute("MATCH (v:Vol), (d:Depart) WHERE v.numero="+vol+" AND d.numero="+numero+" CREATE (v)-[:Constituer]->(d)");
        for (int i=0; i<passagers.size(); i++) {

            res = db.execute("MATCH (p:Passagers), (d:Depart) WHERE p.cin='"+passagers.get(i)+"' AND d.numero="+numero+" CREATE (p)-[:Enregistrer]->(d)");
        }
        for (int i=0; i<personnels.size(); i++) {
            res = db.execute("MATCH (p:Passagers), (d:Depart) WHERE p.cin='"+personnels.get(i)+"' AND d.numero="+numero+" CREATE (p)-[:Enregistrer]->(d)");
        }
        tx.success();
    }
     //res = db.execute("MATCH (d:Depart{date:'"+date+"'}), (p:Passager{cin:'"+passagers.get(0)+"'}) CREATE (p)-[r:Enregistrer]->(d)");
}
项目:neo4j-talend-component    文件:Neo4jBatchInserterNodeTest.java   
@Test
public void insert_node_should_succeed_with_populated_index() throws Exception {
    Neo4jBatchInserterNode nodeInserter = getNeo4jBatchInserterNode(false);

    // populate the db
    List<String> columns = DummyTalendPojo.getColumnList();
    for (int i = 0; i < 100; i++) {
        DummyTalendPojo pojo = DummyTalendPojo.getDummyTalendPojo();
        nodeInserter.create(pojo, columns);
    }
    nodeInserter.finish();

    // check if index size
    Assert.assertEquals(100, batchDb.batchInserterIndexes.get(INDEX_NAME).query("*:*").size());

    // check the database data
    batchDb.shutdown();
    // Testing it with real graphdb
    GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(dbPath);
    try (Transaction tx = graphDb.beginTx()) {
        String result = graphDb.execute("MATCH (n:" + LABEL_NAME + ") RETURN count(n) AS count").resultAsString();
        Assert.assertEquals("+-------+\n| count |\n+-------+\n| 100   |\n+-------+\n1 row\n", result);
    }
    graphDb.shutdown();
}
项目:neo4j-talend-component    文件:Neo4jBatchInserterNodeTest.java   
@Test
public void update_node_should_succeed() throws Exception {
    // populate the db
    Neo4jBatchInserterNode nodeInserter = getNeo4jBatchInserterNode(false);
    List<String> columns = DummyTalendPojo.getColumnList();
    DummyTalendPojo pojo = DummyTalendPojo.getDummyTalendPojo();
    nodeInserter.create(pojo, columns);
    nodeInserter.finish();

    // By indexing the import id, I update the last node
    pojo.propString = "A new String";
    nodeInserter = getNeo4jBatchInserterNode(true);
    nodeInserter.create(pojo, columns);
    nodeInserter.finish();

    // check the result into the database
    batchDb.shutdown();
    GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(dbPath);
    try (Transaction tx = graphDb.beginTx()) {
        String result = graphDb.execute("MATCH (n:" + LABEL_NAME + ") WHERE exists(n.id) RETURN n.propString AS string").resultAsString();
        Assert.assertEquals("+----------------+\n| string         |\n+----------------+\n| \"A new String\" |\n+----------------+\n1 row\n", result);
    }
    graphDb.shutdown();
}
项目:neo4j-talend-component    文件:Neo4jBatchDatabaseTest.java   
@Test
public void create_node_uniqueness_constraint_should_work() {
    // Test const.
    String label = "Test";
    String property = "myProp";

    // crete the schema
    batchDb.createSchema("NODE_PROPERTY_UNIQUE", label, property);
    batchDb.shutdown();

    // Testing it with real graphdb
    GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(dbPath);
    try (Transaction tx = graphDb.beginTx()) {
        Assert.assertTrue(graphDb.schema().getConstraints(DynamicLabel.label(label)).iterator().hasNext());
    }
    graphDb.shutdown();
}
项目:neo4j-talend-component    文件:Neo4jBatchDatabaseTest.java   
@Test
public void create_node_index_should_work() {
    // Test const.
    String label = "Test";
    String property = "myProp";

    // crete the schema
    batchDb.createSchema("NODE_PROPERTY_INDEX", label, property);
    batchDb.shutdown();

    // Testing it with real graphdb
    GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(dbPath);
    try (Transaction tx = graphDb.beginTx()) {
        Assert.assertTrue(graphDb.schema().getIndexes(DynamicLabel.label(label)).iterator().hasNext());
    }
    graphDb.shutdown();

}
项目:neo4j-couchbase-connector    文件:Neo4jEventHandlerTest.java   
@Test
    public void shouldTransformCypherAlbumsToJSONDoc() throws SQLException {

//      GraphDatabaseService database = new TestGraphDatabaseFactory().newImpermanentDatabase();
        GraphDatabaseService database = new GraphDatabaseFactory().newEmbeddedDatabase(new File("/Applications/Development/Neo4j-2.3.2/neo4j-community-2.3.2/data/graph.db"));

        database.registerTransactionEventHandler(new Neo4jEventListener(database));

        String cypher = "MATCH (n) "
                        + "WHERE n.name = \"Volcano\" "
                        + "WITH n "
                        + "SET n.explicit = true "
                        + "RETURN n";

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

            database.execute(cypher);
            tx.success();
        }
    }
项目:SnowGraph    文件:ReferenceExtractor.java   
public void run(GraphDatabaseService db) {
    this.db = db;
    codeIndexes = new CodeIndexes(db);
    try (Transaction tx=db.beginTx()){
        for (Node node:db.getAllNodes()){
            if (!node.hasProperty(TextExtractor.IS_TEXT)||!(boolean)node.getProperty(TextExtractor.IS_TEXT))
                continue;
            if (node.hasLabel(Label.label(JavaCodeExtractor.CLASS)))
                continue;
            if (node.hasLabel(Label.label(JavaCodeExtractor.METHOD)))
                continue;
            if (node.hasLabel(Label.label(JavaCodeExtractor.INTERFACE)))
                continue;
            if (node.hasLabel(Label.label(JavaCodeExtractor.FIELD)))
                continue;
            textNodes.add(node);
        }
        fromHtmlToCodeElement();
        fromTextToJira();
        fromDiffToCodeElement();
        tx.success();
    }
}
项目:SnowGraph    文件:ReferenceExtractor.java   
private void fromTextToJira(){
    Map<String, Node> jiraMap=new HashMap<>();
    try (Transaction tx = db.beginTx()) {
        for (Node node:db.getAllNodes()){
            if (node.hasLabel(Label.label(JiraExtractor.ISSUE))){
                String name=(String) node.getProperty(JiraExtractor.ISSUE_NAME);
                jiraMap.put(name, node);
            }
        }
        tx.success();
    }
    try (Transaction tx = db.beginTx()) {
        for (Node srcNode : textNodes) {
            String content = text(srcNode);
            Set<String> tokenSet=new HashSet<>();
            for (String e:content.split("[^A-Za-z0-9\\-_]+"))
                tokenSet.add(e);
            for (String jiraName:jiraMap.keySet()){
                if (tokenSet.contains(jiraName))
                    srcNode.createRelationshipTo(jiraMap.get(jiraName), RelationshipType.withName(REFERENCE));
            }
        }
        tx.success();
    }
}
项目:SnowGraph    文件:MailListExtractor.java   
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();
    }
}
项目:SnowGraph    文件:WordKnowledgeExtractor.java   
private void parseDocxFile(String path) {
    File file = new File(path);
    if(file == null || !file.getName().toLowerCase().endsWith(".docx"))
        return;

    // Parse docx file
    DocumentInfo doc = DocumentParser.parseFileToDocumentInfo(file);
    if(!(doc instanceof WordDocumentInfo)) {
        //System.out.println("Not a docx file: " + path);
        return;
    }
    //System.out.println("Parse docx file finished: " + path);

    // Build graph
    //System.out.println("Begin to insert nodes to graph");
    try (Transaction tx = db.beginTx()) {
        dfs((WordDocumentInfo) doc);
        tx.success();
        tx.close();
    }
    //System.out.println("Insertion finished: " + path);
    //System.out.println("----------------------------");
}
项目:SnowGraph    文件:TransExtractor.java   
private void writeVecLines() {
    Map<String, double[]> embeddings = transE.getEntityVecMap();
    List<String> keys = new ArrayList<>(embeddings.keySet());
    for (int i = 0; i < keys.size(); i += 1000) {
        try (Transaction tx = db.beginTx()) {
            for (int j = 0; j < 1000; j++) {
                if (i + j >= keys.size())
                    break;
                String nodeIdString = keys.get(i + j);
                Node node = db.getNodeById(Long.parseLong(nodeIdString));
                String line = "";
                for (double d : embeddings.get(nodeIdString))
                    line += d + " ";
                line = line.trim();
                setVec(node, line);
            }
            tx.success();
        }
    }
}
项目:WhiteLab2.0-Neo4J-Plugin    文件:CypherExecutor.java   
public Long getTypedNodeTokenCount(String type, String pattern, Boolean sensitive) {
    Long frequency = (long) 0;

    try ( Transaction ignored = database.beginTx(); ) {
        IndexManager index = database.index();
        Index<Node> nodeIndex = index.forNodes(type);
        for (Node match : nodeIndex.get("label", pattern)) {
            if (!sensitive || ((String) match.getProperty("label")).equals(pattern)) {
                Object count = match.getProperty("token_count");
                if (count instanceof Integer)
                    frequency = frequency + new Long((Integer) count);
                else if (count instanceof Long)
                    frequency = frequency + (Long) count;
            }
        }
    }

    return frequency;
}
项目:WhiteLab2.0-Neo4J-Plugin    文件:CypherExecutor.java   
private void executeQuery(JsonGenerator jg, Query query) throws IOException {
    query.setStart(System.currentTimeMillis());
    try ( Transaction ignored = database.beginTx(); Result result = database.execute(query.toCypher()) ) {
        query.setEnd(System.currentTimeMillis());
        jg.writeNumberField("duration", query.getDuration());
        if (!query.isCountQuery())
            jg.writeArrayFieldStart(query.getResultHeader());
        while ( result.hasNext() ) {
            Map<String, Object> row = result.next();
            if (!query.isCountQuery())
                jg.writeStartObject();
            for ( Entry<String, Object> column : row.entrySet() ) {
                writeField(column, jg);
            }
            if (!query.isCountQuery())
                jg.writeEndObject();
        }
        if (!query.isCountQuery())
            jg.writeEndArray();
    }
}
项目:WhiteLab2.0-Neo4J-Plugin    文件:MetadatumSearcher.java   
protected Response getMetadataLabel(final String label) {
    StreamingOutput stream = new StreamingOutput()
    {
        @Override
        public void write( OutputStream os ) throws IOException, WebApplicationException
        {
            try ( Transaction tx = database.beginTx() ) {
                JsonGenerator jg = objectMapper.getFactory().createGenerator(os, JsonEncoding.UTF8);
                IndexManager index = database.index();
                Index<Node> metadata = index.forNodes("Metadatum");
                jg.writeStartArray();
                for ( Node metadatum : metadata.query( "label:"+label ) ) {
                    executor.writeField(metadatum, jg);
                }
                jg.writeEndArray();
                jg.flush();
                tx.success();
            }
        }
    };

    return Response.ok().entity( stream ).type( MediaType.APPLICATION_JSON ).build();
}
项目:WhiteLab2.0-Neo4J-Plugin    文件:MetadatumSearcher.java   
protected Response updateMetadataLabel(final String label, final String property, final String value) {
    StreamingOutput stream = new StreamingOutput()
    {
        @Override
        public void write( OutputStream os ) throws IOException, WebApplicationException
        {
            try ( Transaction tx = database.beginTx() ) {
                JsonGenerator jg = objectMapper.getFactory().createGenerator(os, JsonEncoding.UTF8);
                IndexManager index = database.index();
                Index<Node> metadata = index.forNodes("Metadatum");
                for ( Node metadatum : metadata.query( "label:"+label ) ) {
                    if (property.equals("explorable") || property.equals("searchable"))
                        metadatum.setProperty(property, Boolean.valueOf(value));
                    else
                        metadatum.setProperty(property, value);
                }
                jg.writeString("Updated "+label);
                jg.flush();
                tx.success();
            }
        }
    };

    return Response.ok().entity( stream ).type( MediaType.APPLICATION_JSON ).build();
}
项目:WhiteLab2.0-Neo4J-Plugin    文件:MetadatumSearcher.java   
protected Response getMetadataGroupKey(final String group, final String key) {
    StreamingOutput stream = new StreamingOutput()
    {
        @Override
        public void write( OutputStream os ) throws IOException, WebApplicationException
        {
            try ( Transaction tx = database.beginTx() ) {
                JsonGenerator jg = objectMapper.getFactory().createGenerator(os, JsonEncoding.UTF8);
                IndexManager index = database.index();
                Index<Node> metadata = index.forNodes("Metadatum");
                jg.writeStartArray();
                for ( Node metadatum : metadata.query( "group:"+group+" AND key:"+key ) ) {
                    executor.writeField(metadatum, jg);
                }
                jg.writeEndArray();
                jg.flush();
                tx.success();
            }
        }
    };

    return Response.ok().entity( stream ).type( MediaType.APPLICATION_JSON ).build();
}
项目:artificial-guy    文件:KnowledgeGraph.java   
private Node addNode(String token, String pos, String ner, String sentId) throws Exception {

        if (token == null || pos == null || ner == null) {
            throw new Exception("Invalid arguments");
        }

        // check for duplicate nodes
        Node node = getNode(token, pos, ner, sentId);
        if (node != null) {
            return node;
        }

        try (Transaction tx = graphDb.beginTx()) {
            // Database operations go here
            node = graphDb.createNode();
            node.setProperty("token", token);
            node.setProperty("pos", pos);
            node.setProperty("ner", ner);
            node.addLabel(DynamicLabel.label("S_" + sentId));

            // transaction complete
            tx.success();
        }

        return node;
    }
项目:umls-graph-api    文件:GraphFunctions.java   
public static List<String> getHypernyms(String cui){
  List<String> hypers = new ArrayList<>();

  try ( Transaction tx = graphDb.beginTx() ){
    TraversalDescription td = graphDb.traversalDescription()
        .breadthFirst()
        .relationships(RelReader.RelTypes.ISA, Direction.OUTGOING)
        .evaluator(Evaluators.excludeStartPosition());

    Node cuiNode = graphDb.findNode(RelReader.DictLabels.Concept, RelReader.CUI_PROPERTY, cui);
    if(cuiNode == null) return hypers;

    Traverser traverser = td.traverse(cuiNode);
    for(Path path : traverser){
      hypers.add(path.endNode().getProperty(RelReader.CUI_PROPERTY).toString());
    }
    tx.success();
  }
  return hypers;
}
项目:umls-graph-api    文件:GraphFunctions.java   
public static List<String> getHyponyms(String cui){
  List<String> hypos = new ArrayList<>();

  try ( Transaction tx = graphDb.beginTx() ){
    TraversalDescription td = graphDb.traversalDescription()
        .breadthFirst()
        .relationships(RelReader.RelTypes.ISA, Direction.INCOMING)
        .evaluator(Evaluators.excludeStartPosition());

    Node cuiNode = graphDb.findNode(RelReader.DictLabels.Concept, RelReader.CUI_PROPERTY, cui);
    if(cuiNode == null) return hypos;

    Traverser traverser = td.traverse(cuiNode);
    for(Path path : traverser){
      hypos.add(path.endNode().getProperty(RelReader.CUI_PROPERTY).toString());
    }
    tx.success();
  }
  return hypos;    
}
项目:umls-graph-api    文件:GraphFunctions.java   
public static boolean isa(String cui1, String cui2){
  boolean match=false;
  try ( Transaction tx = graphDb.beginTx() ){
    Node cui1Node = graphDb.findNode(RelReader.DictLabels.Concept, RelReader.CUI_PROPERTY, cui1);
    Node cui2Node = graphDb.findNode(RelReader.DictLabels.Concept, RelReader.CUI_PROPERTY, cui2);
    if(cui1Node == null || cui2Node == null) return match;

    TraversalDescription td = graphDb.traversalDescription()
        .breadthFirst()
        .relationships(RelReader.RelTypes.ISA, Direction.OUTGOING)
        .evaluator(Evaluators.excludeStartPosition())
        .evaluator(Evaluators.includeWhereEndNodeIs(cui2Node));

    Traverser traverser = td.traverse(cui1Node);
    if(traverser.iterator().hasNext()){
      match = true;
    }
    tx.success();
  }
  return match;
}
项目:umls-graph-api    文件:GraphFunctions.java   
public static int minDistance(String cui1, String cui2){
  int distance = -1;
  try ( Transaction tx = graphDb.beginTx() ){
    Node cui1Node = graphDb.findNode(RelReader.DictLabels.Concept, RelReader.CUI_PROPERTY, cui1);
    Node cui2Node = graphDb.findNode(RelReader.DictLabels.Concept, RelReader.CUI_PROPERTY, cui2);
    if(cui1Node == null || cui2Node == null) return distance;

    TraversalDescription td = graphDb.traversalDescription()
        .breadthFirst()
        .relationships(RelReader.RelTypes.ISA, Direction.OUTGOING)
        .evaluator(Evaluators.excludeStartPosition())
        .evaluator(Evaluators.includeWhereEndNodeIs(cui2Node));

    Traverser traverser = td.traverse(cui1Node);
    for(Path path : traverser){
      int len = path.length();
      if(distance == -1 || len < distance){
        distance = len;
      }
    }
    tx.success();
  }
  return distance;
}
项目:umls-graph-api    文件:TestRelReader.java   
@Test
public void testRelReader() throws IOException{

  RelReader reader = new RelReader(neo4jLocation);
  reader.batchBuildGraph(new File("my_test_umls/"), "CtakesAllTuis.txt", "SNOMEDCT_US");
  GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase(new File(neo4jLocation));

  try ( Transaction tx = db.beginTx() ){
    TraversalDescription td = db.traversalDescription()
        .breadthFirst()
        .relationships(RelReader.RelTypes.ISA, Direction.INCOMING)
        .evaluator(Evaluators.excludeStartPosition());

    Node cuiNode = db.findNode(RelReader.DictLabels.Concept, RelReader.CUI_PROPERTY, "C0007102");
    Assert.assertNotNull(cuiNode);
    Traverser traverser = td.traverse(cuiNode);
    for(Path path : traverser){
      System.out.println("At depth " + path.length() + " => " + path.endNode().getProperty("cui"));
    }
  }
  db.shutdown();
}
项目:neo4j-lucene5-index    文件:UniqueIndexRecoveryTests.java   
@Test
public void shouldRecoverWhenCommandsTemporarilyViolateConstraints() throws Exception
{
    // GIVEN
    Node unLabeledNode = createUnLabeledNode();
    Node labeledNode = createLabeledNode();
    createUniqueConstraint();
    rotateLogAndCheckPoint(); // snapshot
    setPropertyOnLabeledNode( labeledNode );
    deletePropertyOnLabeledNode( labeledNode );
    addLabelToUnLabeledNode( unLabeledNode );
    flushAll(); // persist - recovery will do everything since last log rotate

    // WHEN recovery is triggered
    restart( snapshot( storeDir.absolutePath() ) );

    // THEN
    // it should just not blow up!
    try ( Transaction tx = db.beginTx() )
    {
        assertThat(
                db.findNode( LABEL, PROPERTY_KEY, PROPERTY_VALUE ),
                equalTo( unLabeledNode ) );
        tx.success();
    }
}
项目:welshare    文件:FollowingTest.java   
@Test
public void followingTest() throws Exception {
    Transaction tx = db.beginTx();
    User user = new User();
    user.setId("foo");
    user.setUsername("ufoo");
    User followed = new User();
    followed.setId("bar");
    followed.setUsername("ubar");
    Following f = new Following();
    f.setFollower(user);
    f.setFollowed(followed);
    try {
        dao.saveFollowing(f);
        tx.success();
    } catch (Exception ex) {
        tx.failure();
        throw ex;
    } finally {
        tx.finish();
    }
}
项目:NeoDD    文件:Propoli.java   
public void stamp() {
    if (null != graph && null != root) {
        try (Transaction tx = graph.beginTx()) {
            PathFinder<Path> finder = GraphAlgoFactory.allPaths(
                    PathExpanders.forTypesAndDirections(RelTypes.CHILD_HI, Direction.OUTGOING, RelTypes.CHILD_LO, Direction.OUTGOING), 5);
            // 5 is the number of original relationships + 1
            Iterable<Path> paths = finder.findAllPaths(root, one);
            for (Path path : paths) {
                boolean first = true;
                for (Relationship relationship : path.relationships()) {
                    if (first) {
                        System.out.format("(%s)", relationship.getStartNode().getProperty(ID));
                        first = false;
                    }

                    System.out.format(" --[%s,%.2f]-> ", relationship.getType().name(), relationship.getProperty(PROB, 1.0));
                    System.out.format("(%s)", relationship.getEndNode().getProperty(ID));
                }
                System.out.println();
            }
            tx.success();
        }
    }
}
项目:NeoDD    文件:BiDiDi.java   
public GraphDatabaseService connect() {
    if (null == graph) {
        graph = new GraphDatabaseFactory().newEmbeddedDatabase(path);
        try (Transaction tx = graph.beginTx()) {
            graph.schema().indexFor(LABEL).on(ID).create();
            tx.success();
        }
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                graph.shutdown();
            }
        });
    }
    return graph;
}
项目:NeoDD    文件:Application.java   
private void createDb() {
    graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);
    registerShutdownHook(graphDb);

    try (Transaction tx = graphDb.beginTx()) {
        // Database operations go here

        firstNode = graphDb.createNode();
        firstNode.setProperty("message", "Hello, ");
        secondNode = graphDb.createNode();
        secondNode.setProperty("message", "World!");

        relationship = firstNode.createRelationshipTo(secondNode, RelTypes.KNOWS);
        relationship.setProperty("message", "brave Neo4j ");

        System.out.print(firstNode.getProperty("message"));
        System.out.print(relationship.getProperty("message"));
        System.out.print(secondNode.getProperty("message"));

        greeting = ((String) firstNode.getProperty("message")) + ((String) relationship.getProperty("message"))
                + ((String) secondNode.getProperty("message"));

        tx.success();
    }
}
项目:welshare    文件:ViralLinkDaoNeo4j.java   
@Override
public void storeShortUrl(ShortUrl shortUrl) {
    Transaction tx = db.beginTx();
    try {
        Node node = template.createNode(new Property(KEY, shortUrl.getKey()));
        node.setProperty(LONG_URL, shortUrl.getLongUrl());
        node.setProperty(USER_ID, shortUrl.getUser().getId());
        index.index(node, KEY, shortUrl.getKey());
        tx.success();
    } catch (Exception ex) {
        logger.error("Problem shortening url in the graph", ex);
        tx.failure();
    } finally {
        tx.finish();
    }

}
项目:NeoDD    文件:Problem.java   
public final Relationship add(RelationshipType type, Node tail, Node head, double prob) {
    if (null == type)
        throw new IllegalArgumentException("Illegal 'type' argument in Problem.add(RelationshipType, Node, Node, double): " + type);
    if (null == tail)
        throw new IllegalArgumentException("Illegal 'tail' argument in Problem.add(RelationshipType, Node, Node, double): " + tail);
    if (null == head)
        throw new IllegalArgumentException("Illegal 'head' argument in Problem.add(RelationshipType, Node, Node, double): " + head);
    if (prob < 0.0 || prob > 1.0)
        throw new IllegalArgumentException("Illegal 'prob' argument in Problem.add(RelationshipType, Node, Node, double): " + prob);
    Relationship result = null;
    try (Transaction tx = graph.beginTx()) {
        result = tail.createRelationshipTo(head, type);
        result.setProperty("prob", prob);
        count += 1;
        tx.success();
    }
    return result;
}
项目:neo4j-lucene5-index    文件:IndexConstraintsTest.java   
@Test
public void convertConstraintToIndex()
{
    try( Transaction tx = graphDb.beginTx() )
    {
        graphDb.schema().constraintFor( LABEL ).assertPropertyIsUnique( PROPERTY_KEY ).create();
        tx.success();
    }

    try( Transaction tx = graphDb.beginTx() )
    {
        ConstraintDefinition constraint = first( graphDb.schema().getConstraints( LABEL ) );
        constraint.drop();

        graphDb.schema().indexFor( LABEL ).on( PROPERTY_KEY ).create();
        tx.success();
    }
    // assert no exception is thrown
}
项目:neo4j-lucene5-index    文件:SchemaIndexAcceptanceTest.java   
@Test
public void shouldIndexStringArrays() throws Exception
{
    String[] arrayPropertyValue = {"A, B", "C"};
    createIndex( db, label, propertyKey );
    Node node1;
    try ( Transaction tx = db.beginTx() )
    {
        node1 = createNode( label, propertyKey, arrayPropertyValue );
        tx.success();
    }

    restart();

    assertThat( getIndexes( db, label ), inTx( db, haveState( db, IndexState.ONLINE ) ) );
    assertThat( findNodesByLabelAndProperty( label, propertyKey, arrayPropertyValue, db ), containsOnly( node1 ) );
    assertThat( findNodesByLabelAndProperty( label, propertyKey, new String[]{"A", "B, C"}, db ), isEmpty() );
    assertThat( findNodesByLabelAndProperty( label, propertyKey, Arrays.toString( arrayPropertyValue ), db ), isEmpty() );

}
项目:NeoDD    文件:BDD.java   
public double traverse() {
    if (null != root && value < 0.0) {
        try (Transaction ignore = graph.beginTx()) {
            value = 0.0;
            PathFinder<Path> finder = GraphAlgoFactory.allPaths(
                    PathExpanders.forTypesAndDirections(RelType.LO_CHILD, Direction.OUTGOING, RelType.HI_CHILD, Direction.OUTGOING), max);
            Iterable<Path> paths = finder.findAllPaths(root, one);
            for (Path path : paths) {
                double current = 1.0;
                for (Relationship relationship : path.relationships()) {
                    current *= (double) relationship.getProperty(PROB, 1.0);
                }
                value += current;
            }
        }
    }
    return value;
}
项目:neo4j-lucene5-index    文件:IndexConstraintsTest.java   
@Test
public void shouldRemoveIndexForConstraintEvenIfDroppedInCreatingTransaction()
{
    try ( Transaction tx = graphDb.beginTx() )
    {
        // given
        graphDb.schema()
                .constraintFor( LABEL ).assertPropertyIsUnique( PROPERTY_KEY )
                .create()
                .drop();
        // when - rolling back
        tx.failure();
    }
    // then
    assertNull( "Should not have constraint index", getIndex( LABEL, PROPERTY_KEY ) );
}
项目:OASSIS    文件:NaiveAlgorithm.java   
@SuppressWarnings("deprecation")
/***
 * Sets significanceBit field of node to significanceBit.
 * @param node
 * @param significanceBit
 */
public void setSignificanceBit(Node node, int significanceBit)
{
    String tempString = serializer.serialize(significanceBit);
    Transaction tx = graphDB.beginTx();
    try
    {
        node.setProperty("__significanceBit", tempString);
        tx.success();
    }finally
    {
        tx.finish();
    }
}
项目:golr-loader    文件:QueriesSanityCheck.java   
public static int runCypherQuery(String filePath, GolrCypherQuery query,
    GraphDatabaseService graphDb, CypherUtil cypherUtil) {
  Stopwatch sw = Stopwatch.createStarted();
  int count = 0;
  try {

    try (Transaction tx = graphDb.beginTx()) {
      Result result = cypherUtil.execute(query.getQuery());
      while (result.hasNext()) {
        result.next();
        count++;
      }
    }

  } catch (Exception e) {
    e.printStackTrace();
  }
  System.out.println(filePath + " - " + sw.stop() + " - " + count);
  return count;
}
项目:neo4j-lucene5-index    文件:SchemaIndexAcceptanceTest.java   
@Test
public void shouldIndexArraysPostPopulation() throws Exception
{
    long[] arrayPropertyValue = {42, 23, 87};
    Node node1;
    try ( Transaction tx = db.beginTx() )
    {
        node1 = createNode( label, propertyKey, arrayPropertyValue );
        tx.success();
    }

    createIndex( db, label, propertyKey );

    restart();

    assertThat( getIndexes( db, label ), inTx( db, haveState( db, IndexState.ONLINE ) ) );
    assertThat( findNodesByLabelAndProperty( label, propertyKey, arrayPropertyValue, db ), containsOnly( node1 ) );
    assertThat( findNodesByLabelAndProperty( label, propertyKey, new long[]{42, 23}, db ), isEmpty() );
    assertThat( findNodesByLabelAndProperty( label, propertyKey, Arrays.toString( arrayPropertyValue ), db ), isEmpty() );
}
项目:schemacrawler-plugin-neo4j    文件:AdditionalExecutable.java   
public void putSynonyms(final Catalog catalog) {
    try (Transaction tx = getDbService().beginTx()) {
        for (final Schema schema : catalog.getSchemas()) {

            for (final Synonym synonym : catalog.getSynonyms(schema)) {
                // add synonym to nodes
                // feed node with datas

                // attach synonym to schema
                // attach synonym to database object (?)
                //synonym.getReferencedObject().getClass();
            }
        }
        tx.success();
    }
}
项目:dnainator    文件:Neo4jSequenceNode.java   
/**
 * Construct a new {@link Neo4jSequenceNode} which wraps the given
 * Neo4j {@link Node}.
 * @param service The Neo4j service, for accessing the database.
 * @param node The Neo4j node.
 */
public Neo4jSequenceNode(GraphDatabaseService service, Node node) {
    loaded = false;

    this.service = service;
    this.node = node;
    this.annotations = new ArrayList<>();
    this.outgoing = new ArrayList<>();
    this.sources = new HashSet<>();
    this.scores = new HashMap<>();

    try (Transaction tx = service.beginTx()) {
        this.id         = (String) node.getProperty(SequenceProperties.ID.name());
        basedist        = (int) node.getProperty(SequenceProperties.BASE_DIST.name());
        interestingness = (int) node.getProperty(SequenceProperties.INTERESTINGNESS.name(), 0);

        node.getRelationships(RelTypes.NEXT, Direction.OUTGOING).forEach(e ->
            outgoing.add((String) e.getEndNode().getProperty(SequenceProperties.ID.name())));
        node.getRelationships(RelTypes.SOURCE, Direction.OUTGOING).forEach(e ->
            sources.add((String) e.getEndNode().getProperty(SourceProperties.SOURCE.name())));

        tx.success();
    }
}