Why is executing Cypher with Java so slow?

hello team
The version of neo4j is community-5.12.0.
Here is my java code

import org.neo4j.configuration.GraphDatabaseSettings;
import org.neo4j.dbms.api.DatabaseManagementServiceBuilder;
import org.neo4j.graphdb.Transaction;

import java.nio.file.Path;
import java.time.Duration;

import static org.neo4j.configuration.GraphDatabaseSettings.DEFAULT_DATABASE_NAME;

/**
 * @author SuperL
 */
public class TestShortestPath2 {
    private static final Path DB_DIR = Path.of("/Users/superl/tools/neo4j-community-5.11.0/data");
    private static final String CQL =
            """
            MATCH (n:Node {name:'node1'}) RETURN n
            """;

    public static void main(String[] args) {
        var managementServiceBuilder = new DatabaseManagementServiceBuilder(DB_DIR);
        var managementService = managementServiceBuilder.setConfig(GraphDatabaseSettings.pagecache_memory, 1024 * 1024 * 1024L)
                                                        .setConfig(GraphDatabaseSettings.transaction_timeout, Duration.ofSeconds(60))
                                                        .setConfig(GraphDatabaseSettings.preallocate_logical_logs, false)
                                                        .setConfig(GraphDatabaseSettings.debug_log_enabled, false)
                                                        .build();
        var graphDB = managementService.database(DEFAULT_DATABASE_NAME);

        try (Transaction tx = graphDB.beginTx()) {
            long startTime = System.currentTimeMillis();
            var result = tx.execute(CQL);
            System.out.println(System.currentTimeMillis() - startTime);
            while (result.hasNext()) {
            }
            tx.commit();
        }
    }
} 

Here is my graph.

The code tx.execute(CQL) took 683ms, but it took only 3ms in the Web UI.
Why is that happening ?

The first time a query is executed it must first be planned. This takes time. This is not necessary on subsequent executions if the query plan is still cached.

Try executing the query again in your code and compare the duration of the first and second executions.

Do you have an index on :Node name?

Thanks , you are correct. The duration of non-first-time requests is less than 3 ms.
How to reduce the took time of first time query ? There are so many cyphers of dynamic-build in my application and I can't warmup them all.

yes, I have created index for it.
image

What I suggest is that you always use parameters instead of building your queries.

In your example, replace ‘node1’ with a query parameter. The query will be parsed and cached, so it can be reused for any value of parameter passed.

2 Likes