public static String executeCypher(GraphDatabaseService db, String cypher, Map<String, Object> params) { org.neo4j.cypher.javacompat.ExecutionEngine engine; engine = new org.neo4j.cypher.javacompat.ExecutionEngine(db); List<Map<String, Object>> results = new ArrayList<>(); org.neo4j.cypher.javacompat.ExecutionResult result; try ( Transaction tx = db.beginTx() ) { result = engine.execute(cypher, params); for (Map<String,Object> row : result) { results.add(new LinkedHashMap<>(row)); } tx.success(); } return new Gson().toJson(results); } }
String query = "MATCH (n:Phone{id:'you'}) MATCH n-[r:calling]->m WHERE n<>m RETURN n, r, m"; ExecutionEngine engine = new ExecutionEngine( db ); ExecutionResult result; try ( Transaction ignored = db.beginTx() ) { result = engine.execute(query); ResourceIterator<Relationship> rels = result.columnAs("r"); while(rels.hasNext()) { Relationship r = rels.next(); // Do something cool here. } } catch(Exception exc) { System.err.println("ERHMAGEHRD!!!"); }
private void checkExecutionEngine() { if ( queryEngine == null ) { queryEngine = new ExecutionEngine( graph ); } }
private void dumpToFile( final String id, final String query, final Object params ) throws Exception { StringBuffer sb = new StringBuffer( 2048 ); String prettifiedJson = WRITER.writeValueAsString( params ); sb.append( "\n.Parameters\n[source,javascript]\n----\n" ) .append( prettifiedJson ) .append( "\n----\n\n.Query\n" ) .append( AsciidocHelper.createAsciiDocSnippet( "cypher", engine.prettify( query ) ) ); AsciiDocGenerator.dumpToSeparateFile( docsTargetDir, id, sb.toString() ); }
ExecutionEngine engine = new ExecutionEngine(db, StringLogger.wrap(new OutputStreamWriter(System.out))); ExecutionResult er = engine.execute(query);
public Neo4jSingleInsertion(GraphDatabaseService neo4jGraph, File resultsPath) { super(GraphDatabaseType.NEO4J, resultsPath); this.neo4jGraph = neo4jGraph; engine = new ExecutionEngine(this.neo4jGraph); }
@Test public void prettifier_makes_pretty() throws Exception { String given = "match (n)-->() return n"; String expected = String.format("MATCH (n)-->()%nRETURN n"); assertEquals(expected, engine.prettify(given)); }
@Override public ExecutionResult execute( final String cypher, final Map<String, Object> params ) { checkExecutionEngine(); logger.debug( "Running query:\n\n{}\n\nWith params:\n\n{}\n\n", cypher, params ); final String query = cypher.replaceAll( "(\\s)\\s+", "$1" ); final ExecutionResult result = params == null ? queryEngine.execute( query ) : queryEngine.execute( query, params ); // logger.info( "Execution plan:\n{}", result.executionPlanDescription() ); return result; }
static void writeResults(Appender appender, GraphDatabaseService dbService, List<String> queries, HashMap<String, Object> params, boolean includeHeader) throws IOException { for (String query : queries) { ExecutionResult rows = new ExecutionEngine(dbService).execute(query, params); List<String> columns = rows.columns(); if (includeHeader && queries.indexOf(query) == 0) { final String[] values = columns.toArray(new String[columns.size()]); appender.append(Stream.of(values)); } appendRow(appender, rows, columns); } }
@Produces public ExecutionEngine createQueryEngine(GraphDatabaseService service) { return new ExecutionEngine(service); }
GraphDatabaseService db = ...; // from version 2.2.x onwards db.execute("your cypher statement"); // before version 2.2.x ExecutionEngine engine = new ExecutionEngine(db) engine.execute("your cypher statement");
private void exportAllDistinctTaxa(ExportUtil.Appender writer, GraphDatabaseService graphDatabase) throws IOException { ExecutionEngine engine = new ExecutionEngine(graphDatabase); ExecutionResult results = engine.execute("START taxon = node:taxons('*:*') " + "MATCH taxon<-[:CLASSIFIED_AS]-specimen " + "WHERE has(taxon.externalId) AND taxon.externalId <> '" + PropertyAndValueDictionary.NO_MATCH + "' " + "AND has(taxon.name) AND taxon.name <> '" + PropertyAndValueDictionary.NO_MATCH + "' " + "RETURN distinct(taxon)" + ", taxon.name as scientificName" + ", taxon.path? as path" + ", taxon.pathNames? as pathNames" + ", taxon.rank? as rank" + ", taxon.externalId as taxonId"); Map<String, String> row = new HashMap<String, String>(); for (Map<String, Object> result : results) { resultsToRow(row, result); writeProperties(writer, row); row.clear(); } }
public Neo4j2Graph(final GraphDatabaseService rawGraph) { this.rawGraph = rawGraph; transactionManager = ((GraphDatabaseAPI) rawGraph).getDependencyResolver().resolveDependency(TransactionManager.class); cypher = new ExecutionEngine(rawGraph); init(); }
GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH ); ExecutionEngine engine = new ExecutionEngine( db ); ExecutionResult result = engine.execute( "start n=node(*) where n.name! = 'my node' return n, n.name" );
public static Node getReferenceNode(GraphDatabaseService db, String name) { if (engine == null || db != dbRef) { engine = new ExecutionEngine(db); ReferenceNodes.dbRef = db; } ExecutionResult result = engine.execute("MERGE (ref:ReferenceNode {name:{name}}) RETURN ref", map("name", name)); return IteratorUtil.single(result.<Node>columnAs("ref")); } }
/** * * @param graph */ public Neo4jStore(GraphDatabaseService graph) { transactions = new HashMap<Thread, Transaction>(); this.graph = graph; this.checkTransaction(); try { if (!graph.schema().getConstraints().iterator().hasNext()) { graph.schema().indexFor(NodeType.TERM); graph.schema().indexFor(NodeType.PREDICATE); // TODO manage constraints /*graph.schema().constraintFor(NodeType.TERM) .assertPropertyIsUnique("value").create(); graph.schema().constraintFor(NodeType.PREDICATE) .assertPropertyIsUnique("value").create();*/ } cypherEngine = new ExecutionEngine(graph); this.successTransaction(); } finally { this.reloadTransaction(); } }
public Iterator<Map<String,Object>> query(String query, Map<String,Object> params) { return cypher.execute(query,params==null ? Collections.<String,Object>emptyMap() : params).iterator(); }
protected void export(GraphDatabaseService graphService, OutputStreamFactory fileFactory) throws StudyImporterException { String query = "START taxon = node:taxons('*:*') " + "MATCH taxon-[?:SAME_AS*0..1]->linkedTaxon " + "WHERE has(linkedTaxon.externalId) AND linkedTaxon.externalId =~ 'NCBI:.*'" + "RETURN distinct(linkedTaxon.externalId) as id"; ExecutionResult rows = new ExecutionEngine(graphService).execute(query, new HashMap<String, Object>()); int rowCount = 0; OutputStream os = null; try { List<String> columns = rows.columns(); for (Map<String, Object> row : rows) { if (rowCount % getLinksPerResourceFile() == 0) { close(os); os = null; } for (String column : columns) { String taxonId = row.get(column).toString(); String ncbiTaxonId = StringUtils.replace(taxonId, TaxonomyProvider.ID_PREFIX_NCBI, ""); String aLink = String.format( " <ObjId>%s</ObjId>\n" , ncbiTaxonId); IOUtils.write(aLink, os == null ? (os = open(fileFactory, rowCount)) : os, StandardCharsets.UTF_8); } rowCount++; } close(os); } catch (IOException e) { throw new StudyImporterException("failed to export ncbi resources", e); } }
public Neo4j2Graph(final String directory, final Map<String, String> configuration) { try { GraphDatabaseBuilder builder = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(directory); if (null != configuration) this.rawGraph = builder.setConfig(configuration).newGraphDatabase(); else this.rawGraph = builder.newGraphDatabase(); transactionManager = ((GraphDatabaseAPI) rawGraph).getDependencyResolver().resolveDependency(TransactionManager.class); cypher = new ExecutionEngine(rawGraph); init(); } catch (Exception e) { if (this.rawGraph != null) this.rawGraph.shutdown(); throw new RuntimeException(e.getMessage(), e); } }
@Override public CloseableIterator<Term> termsByPredicatePosition(Predicate p, int position) throws AtomSetException { StringBuilder sb = new StringBuilder(); sb.append("MATCH "); predicateToCypher(sb, p); sb.append("<-[rel_predicate:PREDICATE]-(atom)-[:TERM { index: ").append(position).append(" }]->(term) "); sb.append("RETURN DISTINCT term"); String query = sb.toString(); if (LOGGER.isDebugEnabled()) { LOGGER.debug(query); } ResourceIterator<Map<String, Object>> result = this.cypherEngine.execute(query).iterator(); return new Neo4jTermIterator(this.getTransaction(), result); }