I am trying to write a custom procedure for the Neo4J GraphDB in accordance to the documentation and the there referenced template. The procedure should ultimately generate a graph projection using the GDSL, for nodes with a certain label that is provided as a procedure parameter. For this it is, of course, necessary to pass the label to the query that is to be executed within the custom procedure. However, I cannot seem to find out how to pass parameters to a query string.
#Procedure(value = "custom.projectGraph")
#Description("Generates a projection of the graph.")
public Stream<ProRecord> projectGraph(#Name("graph") String graph) {
Map<String, Object> params = Map.of (
"graph", graph
);
return tx.execute("call gds.graph.project.cypher(\"$graph\", "
+ "\"MATCH (n:$graph) return id(n) as id\", "
+ "\"MATCH (src:$graph)-[]-(dst:$graph) "
+ "RETURN id(src) AS source, id(dst) AS target\") "
+ "YIELD graphName", params)
.stream()
.map(result -> (String) result.get("graphName"))
.map(ProRecord::new);
}
public static final class ProRecord {
public final String graphName;
public ProRecord(String graphName) {
this.graphName = graphName;
}
}
This code, unfortunately, does not work as intended, throwing the following exception:
Invalid input '$': expected an identifier
I did copy the syntax of prefixing placeholders with $-characters from other examples, as I could not find any hints on the passing of query parameters in the JavaDoc of the library. Is this even the correct documentation for custom neo4j procedures? Am I possibly using the wrong method here to issue my queries? It'd be very kind if someone could lead me into the right direction on that matter.
In general, when you use a string parameter the $param is automatically quoted, unlike the String.format for example.
Therefore there are 2 problems in your query:
\"$graph\" : in this case you are doubly quoting the parameter, try to write only $graph instead
Things like this n:$graph cannot be done unfortunately, the neo4j parameter handling is not able to recognize where to quote and where not, so you could use String.format or concat string with parameters (e.g. "MATCH (n:" + $graph + ") return id(n)...").
So, in short, this piece of code should work in your case:
return tx.execute("call gds.graph.project.cypher($graph, " +
"'MATCH (n:' + $graph + ') return id(n) as id', " +
"'MATCH (src:' + $graph + ')-[]-(dst:' + $graph + ') RETURN id(src) AS source, id(dst) AS target') YIELD graphName",
params)
.stream()
.map(result -> (String) result.get("graphName"))
.map(ProRecord::new);
Related
I am creating nodes in Neo4j using neo4j-java driver with the help of following Cipher Query.
String cipherQuery = "CREATE (n:MLObsTemp { personId: " + personId + ",conceptId: " + conceptId
+ ",obsId: " + obsId + ",MLObsId: " + mlObsId + ",encounterId: " + encounterId + "}) RETURN n";
Function for creating query
createNeo4JObsNode(String cipherQuery);
Implementation of the Function
private void createNeo4JObsNode(String cipherQuery) throws Exception {
try (ConNeo4j greeter = new ConNeo4j("bolt://localhost:7687", "neo4j", "qwas")) {
System.out.println("Executing query : " + cipherQuery);
try (Session session = driver.session()) {
StatementResult result = session.run(cipherQuery);
} catch (Exception e) {
System.out.println("Error" + e.getMessage());
}
} catch (Exception e) {
e.printStackTrace();
}
}
Making relation for the above nodes using below code
String obsMatchQuery = "MATCH (m:MLObsTemp),(o:Obs) WHERE m.obsId=o.obsId CREATE (m)-[:OBS]->(o)";
createNeo4JObsNode(obsMatchQuery);
String personMatchQuery = "MATCH (m:MLObsTemp),(p:Person) WHERE m.personId=p.personId CREATE (m)-[:PERSON]->(p)";
createNeo4JObsNode(personMatchQuery);
String encounterMatchQuery = "MATCH (m:MLObsTemp),(e:Encounter) WHERE m.encounterId=e.encounterId CREATE (m)-[:ENCOUNTER]->(e)";
createNeo4JObsNode(encounterMatchQuery);
String conceptMatchQuery = "MATCH (m:MLObsTemp),(c:Concept) WHERE m.conceptId=c.conceptId CREATE (m)-[:CONCEPT]->(c)";
createNeo4JObsNode(conceptMatchQuery);
It is taking me 13 seconds on average for creating nodes and 12 seconds for making relations. I have 350k records in my database for which I have to create nodes and their respective relations.
How can I improve my code? Moreover, is this the best way for creating nodes in Neo4j using bolt server and neo4j-java driver?
EDIT
I am now using the query parameter in my code
HashMap<String, Object> parameters = new HashMap<String, Object>();
((HashMap<String, Object>) parameters).put("personId", 1390);
((HashMap<String, Object>) parameters).put("obsId", 14001);
((HashMap<String, Object>) parameters).put("conceptId", 5978);
((HashMap<String, Object>) parameters).put("encounterId", 10810);
((HashMap<String, Object>) parameters).put("mlobsId", 2);
String cypherQuery=
"CREATE (m:MLObsTemp { personId: $personId, ObsId: $obsId, conceptId: $conceptId, MLObsId: $mlobsId, encounterId: $encounterId}) "
+ "WITH m MATCH (p:Person { personId: $personId }) CREATE (m)-[:PERSON]->(p) "
+ "WITH m MATCH (e:Encounter {encounterId: $encounterId }) CREATE (m)-[:Encounter]->(e) "
+ "WITH m MATCH (o:Obs {obsId: $obsId }) CREATE (m)-[:OBS]->(o) "
+ "WITH m MATCH (c:Concept {conceptId: $conceptId }) CREATE (m)-[:CONCEPT]->(c) "
+ " RETURN m";
Creating Node function
try {
ConNeo4j greeter = new ConNeo4j("bolt://localhost:7687", "neo4j", "qwas");
try {
Session session = driver.session();
StatementResult result = session.run(cypherQuery, parameters);
System.out.println(result);
} catch (Exception e) {
System.out.println("[WARNING] Null Row");
}
} catch (Exception e) {
e.printStackTrace();
}
I am also performing the indexing in order to speed up the process
CREATE CONSTRAINT ON (P:Person) ASSERT P.personId IS UNIQUE
CREATE CONSTRAINT ON (E:Encounter) ASSERT E.encounterId IS UNIQUE
CREATE CONSTRAINT ON (O:Obs) ASSERT O.obsId IS UNIQUE
CREATE CONSTRAINT ON (C:Concept) ASSERT C.conceptId IS UNIQUE
Here is the plan for 1 cypher query-profile
Now the performance has improved but not significant. I am using neo4j-java-driver version 1.6.1. How can I batch my cipher queries to improve the performance further.
You should try to minimize redundant work in your cyphers.
MLObsTemp has a lot of redundant properties, and you are searching for it to create every link. Relationships defeat the need to create properties for foreign keys (node ids)
I would recommend a Cypher that does everything together, and uses parameters like this...
CREATE (m:MLObsTemp)
WITH m MATCH (p:Person {id:"$person_id"}) CREATE (m)-[:PERSON]->(p)
WITH m MATCH (e:Encounter {id:"$encounter_id"}) CREATE (m)-[:Encounter]->(e)
WITH m MATCH (c:Concept {id:"$concept_id"}) CREATE (m)-[:CONCEPT]->(c)
// SNIP more MATCH/CREATE
RETURN m
This way, Neo4j doesn't have to find m repeatedly for every relationship. You don't need the ID properties, because that is effectively what the relationship you just created is. Neo4j is very efficient at walking edges (relationships), so just follow the relationship if you need the id value.
TIPS: (mileage may very across Neo4j versions)
Inline is almost always more efficent than WHERE (MATCH (n{id:"rawr"}) vs MATCH (n) WHERE n.id="rawr")
Parameters make frequent, similar queries more efficient, as Neo4j will cache how to do it quickly (the $thing_id syntax used in the above query.) Also, It protects you from Cypher injection (See SQL injection)
From a Session, you can create a Transaction (Session.run() actually creates a transaction for each run call). You can batch multiple Cyphers using a single transaction (Even using the results of previous Cyphers from the same transaction), because transactions live in memory until you mark it a success and close it. Note that if you are not careful, your transaction can fail with "outofmemory". So remember to commit periodically/between batches. (commit batches of 10k records seems to be the norm when ingesting large data sets)
I'm using the Neo4j JDBC driver 2.0.1.
When I run the following query on by browser, I get the right data back.
MATCH (u:Person) RETURN u.name, u.lastname
I am executing this statement with the NeoJDBC driver (I am connected to the db, otherwise I would not have been able to create nodes before):
public static ResultSet executeCypher(String query)
{
try (Statement stmt = TestUtils.connection.createStatement())
{
return stmt.executeQuery(query);
}
catch (SQLException e)
{
System.out.println(e.getMessage() + "\n\n" + e.getCause().toString() + "\n\n" + e.getErrorCode());
}
}
When I'm iterating over the result set, there are 2 colums as expected. But only one row in the result set. I wrote this according to the minimum viable snippet:
//create some users here
//...
//check the database content
ResultSet rs = TestUtils.executeCypher("MATCH (u:Person) RETURN u.name, u.lastname");
while(rs.next())
{
System.out.println(rs.getString("u.name"));
System.out.println("print anything for test purposes");
}
Output:
Executing query: MATCH (u:Person) RETURN u.name as name, u.lastname
as lastname with params {} Starting the Apache HTTP client
John
print anything for test purposes
Why do I only get one row back although it should return multiple rows? I found some data in the "data" field of the ResultSet while debugging (see also Michael Hunger's answer here) where the "last" property is false. So I guess there is more data. But I don't know how to extract it.
How can I get all the data that is in the ResultSet (using an iterator)?
I have the following java code snippet that demonstrates the problem. The error I receive is also included below.
It correctly pulls the correct set, but I am having trouble printing.
I'm using the org.neo4j.graphdb.Node node. Is this the wrong class?
If not, how do I obtain the results movieid, avgrating and movie_title from the ExecutionEngine?
Java Code
GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);
ExecutionEngine engine = new ExecutionEngine(db);
String cypherQuery = "MATCH (n)-[r:RATES]->(m) \n"
+ "RETURN m.movieid as movieid, avg(toFloat(r.rating)) as avgrating, m.title as movie_title \n"
+ "ORDER BY avgrating DESC \n"
+ "LIMIT 20;";
ExecutionResult result = engine.execute(cypher);
for (Map<String, Object> row : result) {
Node x = (Node) row.get("movie_title");
for (String prop : x.getPropertyKeys()) {
System.out.println(prop + ": " + x.getProperty(prop));
}
}
Error
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to org.neo4j.graphdb.Node
at beans.RecommendationBean.queryMoviesWithCypher(RecommendationBean.java:194)
at beans.RecommendationBean.main(RecommendationBean.java:56)
Node x = (Node) row.get("movie_title");
...looks to be the culprit.
In your Cypher statement, you return m.title as movie_title, i.e. you're returning a node property (in this case, a string), and, in the offending line, you're trying to cast that string result as a Node.
If you want Cypher to return a series of nodes you can iterate through, try returning m (the whole node) instead of just individual properties and aggregates, e.g.
"...RETURN m AS movie;"
...
Node x = (Node) row.get("movie");
Etc.
I found the solution Burt Beckwith offered in this question: add user define properties to a domain class and think this could be a viable option for us in some situations. In testing this, I have a domain with a Map property as described in the referenced question. Here is a simplified version (I have more non-map properties, but they are not relevant to this question):
class Space {
String spaceDescription
String spaceType
Map dynForm
String toString() {
return (!spaceType)?id:spaceType + " (" + spaceDescription + ")"
}
}
I have some instances of space saved with some arbitrary data in the dynForm Map like 'Test1':'abc' and 'Test2':'xyz'.
I am trying to query this data and have succesfully used HQL to filter doing the following:
String className = "Space"
Class clazz = grailsApplication.domainClasses.find { it.clazz.simpleName == className }.clazz
def res = clazz.executeQuery("select distinct space.id, space.spaceDescription from Space as space where space.dynForm['Test1'] = 'abc' " )
log.debug "" + res
I want to know if there is a way to select an individual item from the Map dynForm in a select statement. Somehting like this:
def res = clazz.executeQuery("select distinct space.id, elements(space.dynForm['Test1']) from Space as space where space.dynForm['Test1'] = 'abc' " )
I can select the entire map like this:
def res = clazz.executeQuery("select distinct elements(space.dynForm) from Space as space where space.dynForm['Test1'] = 'abc' " )
But I just want to get a specific instance based on the string idx.
how about to use Criteria, but i don't have any sql server so i haven't tested yet.
def results = Space.createCriteria().list {
dynForm{
like('Test1', 'abc')
}
}
I have a forms collection (fc) and I'm attempting to append to an email the values of the 'key' and the 'value'. I'm having no problem with the key (newKey), but I can't seem to code the 'value' properly. The 'for' loop checks to see if the key's first 3 characters of the key are 'ddl' indicating it came from a dropdownlist. if so, the loop should append the value from the dropdownlist control (the value of the key-value pair). (If not, the loop calls another method to append either a yes or no based upon the value of a checkbox control) Thanks in advance.
//Append new key-value pairs implemented since legacy keys
for (int i = 0; i < newKeys.Length; i++ )
{
//Checks for prefix of element to determine type of element
if(newKeys[i].Substring(0,3) == "ddl"){
sb.Append(newKeys[i] + ": " + fc.GetValue(newKeys[i]) + "\",<br />");
sb.Append(newKeys[i] + ": " + fc.GetValues(newKeys[i].ToString()) + "\",<br />");
}
else{
sb.Append(newKeys[i] + ",\"" + Boolean(fc[newKeys[i]]) + "\",<br />");
}
}
The 2 sb.append commands return the following:
ddlStratacacheConstellationManagerRole: System.Web.Mvc.ValueProviderResult"
ddlStratacacheConstellationManagerRole: System.String[]",
The values you are writing aren't of type String, nor they have the ToString() method overridden.
That's why the standard object.ToString() method is called and the object's type name is appended to the string.
To remedy this, you either need to override the ToString() method of all possible form collection's values, or think of some other algorithm, which would iterate over collections and output the corresponding values.