How to combine two different queries together into a single one


(Andrea Balzoni) #1

Hello everyone, i'm still new to neo4j and i'm trying to populate a neo4j database from a Java application using Neo4j Java Dirver and i just stumbled upon the necessity of combining two queries that so far i ran separately into a single one. Those queries are the following:

        params.put( "nodes", nodes );
        String query =
                "UNWIND $nodes AS n " +
                "MERGE (x:" + index + " {id: n.id}) " +
                "ON CREATE SET x += n " +
                "WITH x, n " +
                "CALL apoc.create.addLabels([ id(x) ], [ n.category ]) yield node " +
                "RETURN node";
        session.run( query, params );

and

        params.put( "relationships", relationships );
        String query =
                "UNWIND $relationships AS relationship " +
                "MATCH (x:" + index + " {id: relationship.source_id}), (y:" + index + " {id: relationship.target_id}) " +
                "MERGE (x)-[r:" + type + "]-(y)" +
                "ON CREATE SET r += relationship";
        session.run( query, params );

The first one creates nodes (if they already dont exist in the db) and adds a second label dinamically, the second one creates relationships by matching the nodes involved and creating a link if it doesnt exist. I would like to have those queries into a single method and possibly into the same query as follows:

        params.put( "nodes", nodes );
        params.put( "relationships", relationships );
        String query =
                "???";
        session.run( query, params );

How can i make them into a single query?

Thanks in advance


(Andrew Bowman) #2

The important thing is to reset your cardinality (rows) to 1, which you can do with either using DISTINCT with some value (usually a constant like WITH DISTINCT 1 as ignored), or with aggregation, such as WITH count(node) as nodeCount (in place of the RETURN). Then you can continue with the relationship query.

If there's the possibility for the nodes list to be empty, then favor the aggregation approach, as that will ensure you get a row even if the UNWIND of the empty collection wiped out rows (as it would result in a row with a count of 0), which the relationship query will execute upon).