Wolfgang-Schuetzelhofer / jcypher

Java access to Neo4J graph databases at multiple levels of abstraction
Apache License 2.0
86 stars 15 forks source link

DBUtil.isDatabaseEmpty() is producing very aggresive query #59

Open DonCziken opened 4 years ago

DonCziken commented 4 years ago

Wolfgang,

The method from DBUtil is used internally by the drviers to execute isDatabaseEmpty method and it looks as follows:

    public static boolean isDatabaseEmpty(IDBAccess dbAccess) {
        JcNode n = new JcNode("n");
        JcRelation r = new JcRelation("r");
        JcQuery query = new JcQuery();
        query.setClauses(new IClause[] {
                MATCH.node(n),
                SEPARATE.nextClause(),
                MATCH.node().relation(r).node(),
                RETURN.ALL()
        });
//      Util.printQuery(query, "CHECK", Format.PRETTY_1);
        JcQueryResult result = dbAccess.execute(query);
        if (result.hasErrors()) {
            List<JcError> errors = Util.collectErrors(result);
            throw new JcResultException(errors);
        }
//      Util.printResult(result, "CHECK", Format.PRETTY_1);

        // perform check
        List<GrNode> nodes = result.resultOf(n);
        List<GrRelation> relations = result.resultOf(r);
        return nodes.size() == 0 && relations.size() == 0;
    }

So basically as a result we run kind of following query to check if db is empty:

match (n), match ()-[r]-() return *

then we fetch the data from it and check if the fetched data is empty. This is really not the best way to follow as fetching whole db to check if its empty can cause issues (and in our case it does exactly that ;))

I would recommend to change the query to be as follows:

match (n) WITH n LIMIT 1 return count(n) as count

this would ensure that we would pull only 1 node if any exists, also there is no need to pull relationships as they are not able to exist without at least 1 node existing in db.

cheers, Krzysztof

Wolfgang-Schuetzelhofer commented 4 years ago

Hi Krzysztof,

I totally agree with you, if you could please make that change.

Thanks and cheers, Wolfang