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

项目:open-kilda    文件:TestConfig.java   
/**
 * Neo4j Server bean.
 * Runs Neo4j server for integration tests and returns {@link GraphDatabaseService} instance.
 *
 * @return {@link GraphDatabaseService}
 */
@Bean(destroyMethod = "shutdown")
public GraphDatabaseService graphDatabaseService() {
    String homeDir = "./target";
    String configFile = "./src/test/resources/neo4j.conf";
    ServerBootstrapper serverBootstrapper = new CommunityBootstrapper();
    int i = serverBootstrapper.start(new File(homeDir), Optional.of(new File(configFile)));
    switch (i) {
        case ServerBootstrapper.OK:
            logger.debug("Server started");
            break;
        case ServerBootstrapper.GRAPH_DATABASE_STARTUP_ERROR_CODE:
            logger.error("Server failed to start: graph database startup error");
            break;
        case ServerBootstrapper.WEB_SERVER_STARTUP_ERROR_CODE:
            logger.error("Server failed to start: web server startup error");
            break;
        default:
            logger.error("Server failed to start: unknown error");
            break;
    }
    NeoServer neoServer = serverBootstrapper.getServer();
    return neoServer.getDatabase().getGraph();
}
项目:Multi-Sentence-Compression    文件:NaiveGraphWeigher.java   
@Override
public void weight(GraphDatabaseService graph) {
    requireNonNull(graph, "'graph' is null");

    int total = 0;
    try (Transaction tx = graph.beginTx()) {
        long elapsed = System.nanoTime();
        logger.debug("Computing weights between words...");
        for (Relationship follows : graph.getAllRelationships()) {
            if (follows.isType(FOLLOWS)) {
                double weight = 1.0 / (double) follows.getProperty("freq", 1.0);
                follows.setProperty("weight", weight);
                total += 1;
                if (total % 50 == 0) {
                    logger.debug("{} relationships analysed so far...", total);
                }
            }
        }
        elapsed = System.nanoTime() - elapsed;
        logger.info("{} relationship/s analysed in {} ms.",
                total, String.format("%,.3f", elapsed / 1_000_000_000.0));
        tx.success();
    }
}
项目:neo4j-sparql-extension-yars    文件:RDFServerExtensionTest.java   
@BeforeClass
public static void setUp() throws IOException, RepositoryException, RDFParseException {
    int port;
    try (final ServerSocket serverSocket = new ServerSocket(0)) {
        port = serverSocket.getLocalPort();
    }
    server = CommunityServerBuilder.server()
        .onPort(port)
        .withThirdPartyJaxRsPackage("de.unikiel.inf.comsys.neo4j", "/rdf")
        .build();
    server.start();
    GraphDatabaseService db = server.getDatabase().getGraph();
    Repository rep = RepositoryRegistry.getInstance(db).getRepository();
    conn = rep.getConnection();
    InputStream testdata = RDFServerExtensionTest.class.getResourceAsStream("/sp2b.n3");
    conn.add(testdata, "http://example.com/", RDFFormat.N3);
}
项目: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();

}
项目:jqa-maven-plugin    文件:ExportDatabaseMojo.java   
@Override
protected void aggregate(MavenProject rootModule, List<MavenProject> projects, Store store) throws MojoExecutionException, MojoFailureException {
    File file = ProjectResolver.getOutputFile(rootModule, exportFile, EXPORT_FILE);
    getLog().info("Exporting database to '" + file.getAbsolutePath() + "'");
    EmbeddedGraphStore graphStore = (EmbeddedGraphStore) store;
    store.beginTransaction();
    try {
        GraphDatabaseService databaseService = graphStore.getGraphDatabaseService();
        SubGraph graph = DatabaseSubGraph.from(databaseService);
        new SubGraphExporter(graph).export(new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")));
    } catch (IOException e) {
        throw new MojoExecutionException("Cannot export database.", e);
    } finally {
        store.commitTransaction();
    }
}
项目: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    文件: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    文件:LINE.java   
public void readData(GraphDatabaseService db) {
    Graph graph = CsnExtractor.extract(db);
    graph.getVertexes().forEachRemaining(v1->{
        v1.getNeighbors(true,true).stream().forEach(v2->{
            double weight=v1.weightTo(v2,true,true);
            edges.add(new EmbeddingRelation(v1.getId(),v2.getId(),weight));
            EmbeddingPoint v1p;
            if (vertex.containsKey(v1.getId()))
                v1p=vertex.get(v1.getId());
            else {
                v1p = new EmbeddingPoint(0.0);
                vertex.put(v1.getId(),v1p);
            }
            v1p.degree += weight;
        });
    });
    System.out.println("Vertex count: "+vertex.size());
    System.out.print("Edge count: "+edges.size());
}
项目:doc2graph    文件:JsonHelperConfiguration.java   
/**
 * Get current configuration manager
 * @return
 */
public static DocumentGrapherExecutionContext newContext(GraphDatabaseService db, Log log)
{

    if(instance == null)
    {
        Node configurationNode = db.findNode(Label.label("JSON_CONFIG"), "configuration", "byNode");
        if(configurationNode == null)
        {
            log.info("Load default configuration: "+JsonHelperConfigurationDefault.class);
            instance = new JsonHelperConfigurationDefault();                
        }else
        {
            log.info("Load configuration from node: "+JsonHelperConfigurationByNode.class);
            instance = new JsonHelperConfigurationByNode(configurationNode);    
        }
    }

    return instance.buildContext(db, log);
}
项目:doc2graph    文件:JsonHelperConfigurationDefault.java   
@Override
public DocumentGrapherExecutionContext buildContext(GraphDatabaseService db, Log log) {
    DocumentGrapherExecutionContext context = new DocumentGrapherExecutionContext();

    context.setRootNodeKeyProperty("_document_key");
    context.setDocumentIdBuilder(new DocumentIdBuilderTypeId());

    DocumentRelationBuilderHasTypeArrayKey relBuilder = new DocumentRelationBuilderHasTypeArrayKey();
    relBuilder.setDb(db);
    relBuilder.setLog(log);

    context.setDocumentRelationBuilder(relBuilder);
    DocumentLabelBuilderByType documentLabelBuilder = new DocumentLabelBuilderByType();
    documentLabelBuilder.setDefaultLabel("DocNode");
    context.setDocumentLabelBuilder(documentLabelBuilder);
    context.setDb(db);
    context.setLog(log);
    context.setLogDiscard(false);

    return context;
}
项目: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();
}
项目:quranic-graph    文件:ManagersSet.java   
public ManagersSet(GraphDatabaseService database) {

        session = new MapSession();
        HashMap<Class<?>, Factory> factories = new HashMap<>();
        factories.put(Chapter.class, new ChapterFactory(session));
        factories.put(Verse.class, new VerseFactory(session));
        factories.put(Word.class, new WordFactory(session));
        factories.put(Token.class, new TokenFactory(session));
        factories.put(Root.class, new RootFactory(session));
        factories.put(Lemma.class, new LemmaFactory(session));
        ((MapSession) session).setFactories(factories);

        rootManager = new RootManagerImpl(session, database);
        verseManager = new VerseManagerImpl(session, database);
        tokenManager = new TokenManagerImpl(session, database);
    }
项目:neo4j-websockets    文件:WebsocketsKernelExtensionFactory.java   
@Override
public Lifecycle newInstance(KernelContext context, Dependencies dependencies) throws Throwable {
    GraphDatabaseService graphDatabaseService = dependencies.getGraphDatabaseService();
    Config config = dependencies.getConfig();

    Setting<HostnamePort> hostnamePort = setting("websocket_host", HOSTNAME_PORT, "0.0.0.0:8765");
    Setting<List<String>> packageNames = setting("websocket_packages", STRING_LIST, "");
    Setting<String> managementPath = setting("websocket_management_path", STRING, "/ws/management");
    Setting<String> commandPath = setting("websocket_data_path", STRING, "/ws/data");

    ClusterMemberEvents clusterMemberEvents = null;

    if (graphDatabaseService instanceof HighlyAvailableGraphDatabase) {
        logger.info("[newInstance] cluster installation");
        clusterMemberEvents = dependencies.getClusterMemberEvents();
    }

    return new WebsocketsKernelExtension(
            graphDatabaseService, clusterMemberEvents, config.get(packageNames), config.get(hostnamePort),
            config.get(managementPath), config.get(commandPath));
}
项目:trainbenchmark    文件:Neo4JApiQueryRouteSensorInject.java   
@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;
}
项目:neo4j-websockets    文件:WebsocketsKernelExtension.java   
public WebsocketsKernelExtension(
        GraphDatabaseService graphDatabaseService, ClusterMemberEvents clusterMemberEvents,
        List<String> packageNames, HostnamePort hostnamePort, String managementPath, String dataPath)
        throws Exception
{
    logger.info("[Constructor] package names = '{}', port = '{}', management path = '{}', data path = '{}'",
            packageNames, hostnamePort.getPort(), managementPath, dataPath);

    DatabaseConfiguration.setGraphDatabaseService(graphDatabaseService);

    DatabaseCallAspect.setGraphDatabaseService(graphDatabaseService);

    ApplicationSettings.configure(packageNames, hostnamePort.getHost(), hostnamePort.getPort(), managementPath, dataPath);

    HighAvailabilityConfiguration.instance().configure(graphDatabaseService, clusterMemberEvents);

    websocketServer = new WebsocketServer();
}
项目: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;
}
项目:dnainator    文件:AllClustersQuery.java   
@Override
public Map<Integer, List<Cluster>> execute(GraphDatabaseService service) {
    Queue<Cluster> rootClusters = new PriorityQueue<>((e1, e2) -> 
        e1.getStartRank() - e2.getStartRank()
    );
    Map<Integer, List<Cluster>> result = new HashMap<>();

    rootClusters.addAll(clustersFrom(service, startNodes));

    // Find adjacent clusters as long as there are root clusters in the queue
    int minrank = rootClusters.stream().mapToInt(Cluster::getStartRank).min().orElse(0);
    while (!rootClusters.isEmpty()) {
        Cluster c = rootClusters.poll();
        if (c.getStartRank() < minrank || c.getStartRank() > maxRank) {
            continue;
        }
        result.putIfAbsent(c.getStartRank(), new ArrayList<>());
        result.get(c.getStartRank()).add(c);

        c.getNodes().forEach(sn ->
                rootClusters.addAll(clustersFrom(service, sn.getOutgoing())));
    }

    return result;
}
项目:quranic-graph    文件:LeedsCorpusNextDataFiller.java   
@Override
public void fillInTransaction(GraphDatabaseService database) throws ParserConfigurationException, IOException, SAXException {

    int verse = 1;

    Node current = database.index().forNodes(GraphIndices.VerseIndex).get(NodeProperties.General.address, NodeUtils.getNodeAddress(chapter, verse)).getSingle();
    Node next = database.index().forNodes(GraphIndices.VerseIndex).get(NodeProperties.General.address, NodeUtils.getNodeAddress(chapter, verse + 1)).getSingle();

    while (next != null) {
        current.createRelationshipTo(next, RelationshipTypes.NEXT_VERSE);
        System.out.println("add relationship :" + current.getProperty(NodeProperties.General.address) + " -NEXT_VERSE-> " + next.getProperty(NodeProperties.General.address));

        verse++;
        current = next;
        next = database.index().forNodes(GraphIndices.VerseIndex).get(NodeProperties.General.address, NodeUtils.getNodeAddress(chapter, verse + 1)).getSingle();
    }
}
项目:trainbenchmark    文件:Neo4JApiQuerySwitchSetInject.java   
@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;
}
项目:trainbenchmark    文件:Neo4JApiQueryPosLengthInject.java   
@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;
}
项目:golr-loader    文件:EvidenceProcessor.java   
@Inject
EvidenceProcessor(GraphDatabaseService graphDb, GraphAspect aspect, ClosureUtil closureUtil,
    BbopGraphUtil bbopUtil, CurieUtil curieUtil) {
  this.graphDb = graphDb;
  this.aspect = aspect;
  this.closureUtil = closureUtil;
  this.bbopUtil = bbopUtil;
  this.curieUtil = curieUtil;

  String hasEvidenceStr = "http://purl.obolibrary.org/obo/RO_0002558";
  this.hasEvidence = curieUtil.getCurie(hasEvidenceStr).orElse(hasEvidenceStr);

  String sourceStr = "http://purl.org/dc/elements/1.1/source";
  this.source = curieUtil.getCurie(sourceStr).orElse(sourceStr);

  String isDefinedByStr = OwlRelationships.RDFS_IS_DEFINED_BY.name();
  this.isDefinedBy = curieUtil.getCurie(isDefinedByStr).orElse(isDefinedByStr);
}
项目:mondo-hawk    文件:Neo4JBatchUtil.java   
public static void registerShutdownHook(final GraphDatabaseService database) {
    if (lastGraph == null) {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                try {
                    final long l = System.nanoTime();
                    lastGraph.shutdown();
                    LOGGER.info("SHUTDOWN HOOK INVOKED: (took ~{}s to commit changes)", (System.nanoTime() - l) / 1_000_000_000);
                } catch (Exception e) {
                    LOGGER.error("Error during shutdown hook", e);
                }
            }
        });
    }
    lastGraph = database;
}
项目:neo4j-lucene5-index    文件:RelatedNodesQuestionTest.java   
@Test
public void question5346011()
{
    GraphDatabaseService service = new TestGraphDatabaseFactory().newImpermanentDatabase();
    try ( Transaction tx = service.beginTx() )
    {
        RelationshipIndex index = service.index().forRelationships( "exact" );
        // ...creation of the nodes and relationship
        Node node1 = service.createNode();
        Node node2 = service.createNode();
        String a_uuid = "xyz";
        Relationship relationship = node1.createRelationshipTo( node2, DynamicRelationshipType.withName( "related" ) );
        index.add( relationship, "uuid", a_uuid );
        // query
        IndexHits<Relationship> hits = index.get( "uuid", a_uuid, node1, node2 );
        assertEquals( 1, hits.size() );
        tx.success();
    }
    service.shutdown();
}
项目:neo4j-lucene5-index    文件:TestMigration.java   
@Test
public void canReadAndUpgradeOldIndexStoreFormat() throws Exception
{
    File path = new File( "target/var/old-index-store" );
    Neo4jTestCase.deleteFileOrDirectory( path );
    startDatabase( path ).shutdown();
    InputStream stream = getClass().getClassLoader().getResourceAsStream( "old-index.db" );
    writeFile( stream, new File( path, "index.db" ) );
    GraphDatabaseService db = startDatabase( path );
    try ( Transaction ignore = db.beginTx() )
    {
        assertTrue( db.index().existsForNodes( "indexOne" ) );
        Index<Node> indexOne = db.index().forNodes( "indexOne" );
        verifyConfiguration( db, indexOne, LuceneIndexImplementation.EXACT_CONFIG );
        assertTrue( db.index().existsForNodes( "indexTwo" ) );
        Index<Node> indexTwo = db.index().forNodes( "indexTwo" );
        verifyConfiguration( db, indexTwo, LuceneIndexImplementation.FULLTEXT_CONFIG );
        assertTrue( db.index().existsForRelationships( "indexThree" ) );
        Index<Relationship> indexThree = db.index().forRelationships( "indexThree" );
        verifyConfiguration( db, indexThree, LuceneIndexImplementation.EXACT_CONFIG );
    }
    db.shutdown();
}
项目:quranic-graph    文件:NextVerseInQuranDataFiller.java   
@Override
public void fillInTransaction(GraphDatabaseService database) throws ParserConfigurationException, IOException, SAXException {

    int index = 1;
    VerseManager verseManager = managersSet.getVerseManager();
    Verse current = verseManager.get(1, 1);

    while (current != null) {

        node = current.getNode();
        NodeUtils.setPropertyAndIndex(node, NodeProperties.Verse.indexInQuran, GraphIndices.VerseIndex, index);

        current = nextVerse(current, verseManager);

        index++;
        logger.info("index verse #" + index);
    }
}
项目:golr-loader    文件:SmokeIT.java   
@Ignore
@Test
public void smoke() throws Exception {
  Injector i = Guice.createInjector(new GolrLoaderModule(), new AbstractModule() {
    @Override
    protected void configure() {
      bind(GraphDatabaseService.class).toInstance(graphDb);
      bind(GraphAspect.class).to(EvidenceAspect.class);
    }

    @Provides
    @IndicatesCurieMapping
    Map<String, String> getCurieMap() {
      return curieMap;
    }

  });
  GolrLoader processor = i.getInstance(GolrLoader.class);
  GolrCypherQuery query = new GolrCypherQuery("MATCH (thing)-[c:CAUSES]->(otherThing) RETURN *");
  StringWriter writer = new StringWriter();
  //processor.process(query, writer);
  System.out.println(writer);
  //TODO: Find a way to ignore some fields here...
  //JSONAssert.assertEquals(getFixture("fixtures/simpleResult.json"), writer.toString(), false);
}
项目:neo4j-lucene5-index    文件:BatchInsertionIT.java   
@Test
public void shouldBeAbleToMakeRepeatedCallsToSetNodeProperty() throws Exception
{
    BatchInserter inserter = BatchInserters.inserter( dbRule.getStoreDirAbsolutePath() );
    long nodeId = inserter.createNode( Collections.<String, Object>emptyMap() );

    final Object finalValue = 87;
    inserter.setNodeProperty( nodeId, "a", "some property value" );
    inserter.setNodeProperty( nodeId, "a", 42 );
    inserter.setNodeProperty( nodeId, "a", 3.14 );
    inserter.setNodeProperty( nodeId, "a", true );
    inserter.setNodeProperty( nodeId, "a", finalValue );
    inserter.shutdown();

    GraphDatabaseService db = dbRule.getGraphDatabaseService();
    try(Transaction ignored = db.beginTx())
    {
        assertThat( db.getNodeById( nodeId ).getProperty( "a" ), equalTo( finalValue ) );
    }
    finally
    {
        db.shutdown();
    }
}
项目:trainbenchmark    文件:Neo4JApiQuerySwitchMonitoredInject.java   
@Override
public Collection<Neo4jSwitchMonitoredInjectMatch> evaluate() {
    final Collection<Neo4jSwitchMonitoredInjectMatch> matches = new ArrayList<>();

    final GraphDatabaseService graphDb = driver.getGraphDb();
    try (final 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 Neo4jSwitchMonitoredInjectMatch(match));
        }
    }

    return matches;
}
项目:neo4j-lucene5-index    文件:NonUniqueIndexTests.java   
@Test
public void concurrentIndexPopulationAndInsertsShouldNotProduceDuplicates() throws IOException
{
    // Given
    GraphDatabaseService db = newEmbeddedGraphDatabaseWithSlowJobScheduler();

    // When
    try ( Transaction tx = db.beginTx() )
    {
        db.schema().indexFor( label( "SomeLabel" ) ).on( "key" ).create();
        tx.success();
    }
    Node node;
    try ( Transaction tx = db.beginTx() )
    {
        node = db.createNode( label( "SomeLabel" ) );
        node.setProperty( "key", "value" );
        tx.success();
    }
    db.shutdown();

    // Then
    assertThat( nodeIdsInIndex( 1, "value" ), equalTo( singletonList( node.getId() ) ) );
}
项目:neo4j-lucene5-index    文件:RecoveryTest.java   
public static void main( String[] args )
{
    GraphDatabaseService db = new TestGraphDatabaseFactory().newEmbeddedDatabase( args[0] );
    try ( Transaction tx = db.beginTx() )
    {
        Index<Relationship> index = db.index().forRelationships( "myIndex" );
        Node node = db.createNode();
        Relationship relationship = db.createNode().createRelationshipTo( node,
                DynamicRelationshipType.withName( "KNOWS" ) );

        index.add( relationship, "key", "value" );
        tx.success();
    }

    db.shutdown();
    System.exit( 0 );
}
项目:quranic-graph    文件:LeedsCorpusDataFiller.java   
@Override
public void fillInTransaction(GraphDatabaseService database) throws ParserConfigurationException, IOException, SAXException {

    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();

        String[] options = line.split("\t");
        if (options.length != 4)
            throw new RuntimeException();

        Node tokenNode = processAddressAndForm(database, options[0], options[1]);
        processTag(database, tokenNode, options[2]);
        processFeatures(database, tokenNode, options[3]);
    }

}
项目:neo4j-lucene5-index    文件:ConstraintIndexConcurrencyTest.java   
private static Function<GraphDatabaseService,Void> createNode(
        final Label label, final String key, final Object value )
{
    return new Function<GraphDatabaseService,Void>()
    {
        @Override
        public Void apply( GraphDatabaseService graphDb )
        {
            try ( Transaction tx = graphDb.beginTx() )
            {
                graphDb.createNode( label ).setProperty( key, value );
                tx.success();
            }
            return null;
        }
    };
}
项目:neo4j-ml-procedures    文件:LoadTest.java   
@Test
    @Ignore("While parsing a protocol message, the input ended unexpectedly in the middle of a field.  This could mean either that the input has been truncated or that an embedded message misreported its own length.")
    public void loadTensorFlow() throws Exception {
//        String url = getClass().getResource("/tensorflow_example.pbtxt").toString();
        String url = getClass().getResource("/saved_model.pb").toString();
        System.out.println("url = " + url);
        GraphDatabaseService db = new TestGraphDatabaseFactory().newImpermanentDatabase();
        try (Transaction tx = db.beginTx()) {
            LoadTensorFlow load = new LoadTensorFlow();
            load.loadTensorFlow(url);
            tx.success();
        }
    }
项目:hands-on-neo4j-devoxx-fr-2017    文件:ExerciseRepositoryTest.java   
private List<Map<String, Object>> read(String cql) {
    GraphDatabaseService gds = graphDatabase.getGraphDatabaseService();
    List<Map<String, Object>> rows = new ArrayList<>();
    try (Transaction transaction = gds.beginTx();
         Result result = gds.execute(cql)) {

        while (result.hasNext()) {
            rows.add(result.next());
        }
        transaction.success();
    }
    return rows;
}
项目:hands-on-neo4j-devoxx-fr-2017    文件:ExerciseRepositoryTest.java   
private void write(String cql) {
    GraphDatabaseService graphDatabaseService = graphDatabase.getGraphDatabaseService();
    try (Transaction tx = graphDatabaseService.beginTx()) {
        graphDatabaseService.execute(cql);
        tx.success();
    }
}
项目:kowalski    文件:Configuration.java   
@Bean
public Supplier<Job> jobFactory(JmsTemplate jmsTemplate, Artifact jreArtifact,
        GraphDatabaseService graphDatabaseService) throws SettingsBuildingException {
    return () -> {
        ItemReader<Page<Artifact, Artifact>> reader = new Reader(jmsTemplate, new ActiveMQQueue(this.output));
        ItemProcessor<Page<Artifact, Artifact>, Result> processor = new Processor(new AnalysisRunner(this.timeout),
                jreArtifact, new File(this.lastModifiedCache), this.groupIdFilter);
        ItemWriter<Result> writer = new Writer(graphDatabaseService);
        Step step = this.stepBuilderFactory.get("analysis").<Page<Artifact, Artifact>, Result>chunk(1)
                .faultTolerant().skipPolicy(new LoggingAlwaysSkipItemSkipPolicy()).noRollback(Throwable.class)
                .reader(reader).processor(processor).writer(writer).build();
        return this.jobBuilderFactory.get("analysis").start(step).build();
    };
}