CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-neo4j--neo4j

Neo4j Community Edition - The world's leading Graph Database with Cypher query language and ACID transactions.

Pending
Overview
Eval results
Files

query-execution.mddocs/

Query Execution

Cypher query execution system providing result handling, parameter binding, execution plan analysis, and performance monitoring with support for both transactional and auto-commit query patterns.

Capabilities

Result Interface

Interface for handling query results with iteration, statistics access, and resource management.

/**
 * Iterable query result set with resource management
 */
public interface Result extends AutoCloseable {
    
    /**
     * Check if there are more results available
     * @return true if more results exist, false otherwise
     */
    boolean hasNext();
    
    /**
     * Get the next result record
     * @return Map containing column names and values
     * @throws NoSuchElementException if no more results
     */
    Map<String, Object> next();
    
    /**
     * Process each remaining result with a consumer function
     * @param action Consumer function to process each result record
     */
    void forEachRemaining(Consumer<Map<String, Object>> action);
    
    /**
     * Get the column names in the result set
     * @return List of column names
     */
    List<String> columns();
    
    /**
     * Get query execution statistics
     * @return Statistics about the query execution
     */
    QueryStatistics getQueryStatistics();
    
    /**
     * Get the execution plan description
     * @return Execution plan details for query optimization analysis
     */
    ExecutionPlanDescription getExecutionPlanDescription();
    
    /**
     * Get notifications about query execution
     * @return List of notifications (warnings, performance hints, etc.)
     */
    Iterable<Notification> getNotifications();
    
    /**
     * Convert all results to a list of maps
     * @return List containing all result records
     */
    List<Map<String, Object>> list();
    
    /**
     * Transform results using a function
     * @param mapper Function to transform each result record
     * @return Stream of transformed results
     */
    <T> Stream<T> stream(Function<Map<String, Object>, T> mapper);
    
    /**
     * Extract a specific column as a typed iterator
     * @param column Column name to extract
     * @return ResourceIterator of column values
     */
    <T> ResourceIterator<T> columnAs(String column);
    
    /**
     * Convert the entire result to a string representation
     * @return String representation of all results
     */
    String resultAsString();
    
    /**
     * Write the result as a string to a PrintWriter
     * @param writer PrintWriter to write results to
     */
    void writeAsStringTo(PrintWriter writer);
    
    /**
     * Remove operation (explicitly unsupported)
     * @throws UnsupportedOperationException always
     */
    default void remove() {
        throw new UnsupportedOperationException("Remove not supported on query results");
    }
    
    /**
     * Close the result set and free associated resources
     */
    @Override
    void close();
}

Usage Examples:

import org.neo4j.graphdb.Result;
import org.neo4j.graphdb.QueryStatistics;
import java.util.Map;
import java.util.List;

try (Transaction tx = graphDb.beginTx()) {
    // Basic query execution and result processing
    String query = "MATCH (p:Person)-[r:FRIENDS]->(f:Person) " +
                   "RETURN p.name as person, f.name as friend, r.since as since";
    
    try (Result result = tx.execute(query)) {
        // Check column names
        System.out.println("Columns: " + result.columns());
        
        // Process results one by one
        while (result.hasNext()) {
            Map<String, Object> row = result.next();
            System.out.println(row.get("person") + " is friends with " + 
                             row.get("friend") + " since " + row.get("since"));
        }
        
        // Get query statistics
        QueryStatistics stats = result.getQueryStatistics();
        System.out.println("Nodes created: " + stats.getNodesCreated());
        System.out.println("Relationships created: " + stats.getRelationshipsCreated());
    }
    
    tx.commit();
}

// Using forEachRemaining for functional processing
try (Transaction tx = graphDb.beginTx()) {
    try (Result result = tx.execute("MATCH (p:Person) RETURN p.name, p.age")) {
        result.forEachRemaining(row -> {
            System.out.println("Person: " + row.get("p.name") + 
                             ", Age: " + row.get("p.age"));
        });
    }
    tx.commit();
}

// Convert to list for further processing
try (Transaction tx = graphDb.beginTx()) {
    try (Result result = tx.execute("MATCH (p:Person) RETURN p.name as name")) {
        List<Map<String, Object>> allResults = result.list();
        List<String> names = allResults.stream()
            .map(row -> (String) row.get("name"))
            .collect(Collectors.toList());
    }
    tx.commit();
}

Result Transformer

Interface for transforming query results in a callback pattern with proper resource management.

/**
 * Transform query results in a callback pattern
 */
@FunctionalInterface
public interface ResultTransformer<T> {
    
    /**
     * Transform the query result
     * @param result Query result to transform
     * @return Transformed result
     * @throws Exception if transformation fails
     */
    T apply(Result result) throws Exception;
}

Usage Examples:

import org.neo4j.graphdb.ResultTransformer;
import java.util.ArrayList;
import java.util.List;

// Extract specific data from query results
List<String> personNames = graphDb.executeTransactionally(
    "MATCH (p:Person) RETURN p.name as name",
    Map.of(),
    result -> {
        List<String> names = new ArrayList<>();
        result.forEachRemaining(row -> names.add((String) row.get("name")));
        return names;
    }
);

// Calculate aggregations
Double averageAge = graphDb.executeTransactionally(
    "MATCH (p:Person) RETURN p.age as age",
    Map.of(),
    result -> {
        List<Integer> ages = new ArrayList<>();
        result.forEachRemaining(row -> {
            Integer age = (Integer) row.get("age");
            if (age != null) ages.add(age);
        });
        return ages.stream().mapToInt(Integer::intValue).average().orElse(0.0);
    }
);

// Complex data transformation
Map<String, List<String>> friendships = graphDb.executeTransactionally(
    "MATCH (p:Person)-[:FRIENDS]->(f:Person) RETURN p.name as person, f.name as friend",
    Map.of(),
    result -> {
        Map<String, List<String>> friendMap = new HashMap<>();
        result.forEachRemaining(row -> {
            String person = (String) row.get("person");
            String friend = (String) row.get("friend");
            friendMap.computeIfAbsent(person, k -> new ArrayList<>()).add(friend);
        });
        return friendMap;
    }
);

Query Statistics

Interface providing detailed information about query execution and database changes.

/**
 * Statistics about query execution and database changes
 */
public interface QueryStatistics {
    
    /**
     * Get the number of nodes created by the query
     * @return Number of nodes created
     */
    int getNodesCreated();
    
    /**
     * Get the number of nodes deleted by the query
     * @return Number of nodes deleted
     */
    int getNodesDeleted();
    
    /**
     * Get the number of relationships created by the query
     * @return Number of relationships created
     */
    int getRelationshipsCreated();
    
    /**
     * Get the number of relationships deleted by the query
     * @return Number of relationships deleted
     */
    int getRelationshipsDeleted();
    
    /**
     * Get the number of properties set by the query
     * @return Number of properties set
     */
    int getPropertiesSet();
    
    /**
     * Get the number of labels added by the query
     * @return Number of labels added
     */
    int getLabelsAdded();
    
    /**
     * Get the number of labels removed by the query
     * @return Number of labels removed
     */
    int getLabelsRemoved();
    
    /**
     * Get the number of indexes added by the query
     * @return Number of indexes added
     */
    int getIndexesAdded();
    
    /**
     * Get the number of indexes removed by the query
     * @return Number of indexes removed
     */
    int getIndexesRemoved();
    
    /**
     * Get the number of constraints added by the query
     * @return Number of constraints added
     */
    int getConstraintsAdded();
    
    /**
     * Get the number of constraints removed by the query
     * @return Number of constraints removed
     */
    int getConstraintsRemoved();
    
    /**
     * Check if the query contained any updates
     * @return true if any database changes were made
     */
    boolean containsUpdates();
    
    /**
     * Check if the query contained system updates
     * @return true if system-level changes were made
     */
    boolean containsSystemUpdates();
}

Execution Plan Description

Interface for accessing query execution plan information for performance analysis and optimization.

/**
 * Access to query execution plan information
 */
public interface ExecutionPlanDescription {
    
    /**
     * Get the name of this execution step
     * @return Step name (e.g., "NodeByLabelScan", "Expand")
     */
    String getName();
    
    /**
     * Get the children of this execution step
     * @return List of child execution steps
     */
    List<ExecutionPlanDescription> getChildren();
    
    /**
     * Get the arguments for this execution step
     * @return Map of argument names to values
     */
    Map<String, Object> getArguments();
    
    /**
     * Get identifiers introduced by this step
     * @return Set of identifier names
     */
    Set<String> getIdentifiers();
    
    /**
     * Check if this execution plan has profile information
     * @return true if profiling data is available
     */
    boolean hasProfilerStatistics();
    
    /**
     * Get profiler statistics for this step
     * @return Profiler statistics, or null if not available
     */
    ProfilerStatistics getProfilerStatistics();
}

Profiler Statistics

Interface for accessing detailed execution statistics when query profiling is enabled.

/**
 * Detailed execution statistics for query profiling
 */
public interface ProfilerStatistics {
    
    /**
     * Get the number of rows produced by this step
     * @return Number of rows
     */
    long getRows();
    
    /**
     * Get the number of database hits for this step
     * @return Number of database hits
     */
    long getDbHits();
    
    /**
     * Get the page cache hits for this step
     * @return Number of page cache hits
     */
    long getPageCacheHits();
    
    /**
     * Get the page cache misses for this step
     * @return Number of page cache misses
     */
    long getPageCacheMisses();
    
    /**
     * Get the time spent in this step
     * @return Time in milliseconds
     */
    long getTime();
}

Notification System

Interface for query execution notifications including warnings and performance hints.

/**
 * Notification about query execution
 */
public interface Notification {
    
    /**
     * Get the notification code
     * @return Notification code
     */
    String getCode();
    
    /**
     * Get the notification title
     * @return Notification title
     */
    String getTitle();
    
    /**
     * Get the notification description
     * @return Detailed description
     */
    String getDescription();
    
    /**
     * Get the severity level of this notification
     * @return Severity level (WARNING, INFORMATION)
     */
    NotificationSeverity getSeverity();
    
    /**
     * Get the position in the query where this notification applies
     * @return Input position, or null if not applicable
     */
    InputPosition getPosition();
}

/**
 * Severity levels for notifications
 */
public enum NotificationSeverity {
    WARNING,
    INFORMATION
}

Advanced Usage Examples:

// Query with execution plan analysis
try (Transaction tx = graphDb.beginTx()) {
    String query = "PROFILE MATCH (p:Person)-[:FRIENDS]->(f:Person) " +
                   "WHERE p.age > 25 RETURN p.name, f.name";
    
    try (Result result = tx.execute(query)) {
        // Process results
        result.forEachRemaining(row -> {
            System.out.println(row.get("p.name") + " -> " + row.get("f.name"));
        });
        
        // Analyze execution plan
        ExecutionPlanDescription plan = result.getExecutionPlanDescription();
        printExecutionPlan(plan, 0);
        
        // Check for notifications
        for (Notification notification : result.getNotifications()) {
            System.out.println("Notification: " + notification.getTitle());
            System.out.println("Description: " + notification.getDescription());
        }
    }
    
    tx.commit();
}

// Helper method to print execution plan
private void printExecutionPlan(ExecutionPlanDescription plan, int indent) {
    String indentStr = "  ".repeat(indent);
    System.out.println(indentStr + plan.getName());
    
    if (plan.hasProfilerStatistics()) {
        ProfilerStatistics stats = plan.getProfilerStatistics();
        System.out.println(indentStr + "  Rows: " + stats.getRows());
        System.out.println(indentStr + "  DB Hits: " + stats.getDbHits());
        System.out.println(indentStr + "  Time: " + stats.getTime() + "ms");
    }
    
    for (ExecutionPlanDescription child : plan.getChildren()) {
        printExecutionPlan(child, indent + 1);
    }
}

// Parameterized queries with error handling
try (Transaction tx = graphDb.beginTx()) {
    String query = "MATCH (p:Person {name: $name}) " +
                   "CREATE (p)-[:LIVES_IN]->(:City {name: $city}) " +
                   "RETURN p.name as person, $city as city";
    
    Map<String, Object> parameters = Map.of(
        "name", "Alice",
        "city", "New York"
    );
    
    try (Result result = tx.execute(query, parameters)) {
        if (result.hasNext()) {
            Map<String, Object> row = result.next();
            System.out.println(row.get("person") + " lives in " + row.get("city"));
        }
        
        QueryStatistics stats = result.getQueryStatistics();
        if (stats.containsUpdates()) {
            System.out.println("Created " + stats.getRelationshipsCreated() + " relationships");
            System.out.println("Created " + stats.getNodesCreated() + " nodes");
        }
    }
    
    tx.commit();
} catch (Exception e) {
    System.err.println("Query execution failed: " + e.getMessage());
}

Install with Tessl CLI

npx tessl i tessl/maven-org-neo4j--neo4j

docs

configuration.md

database-management.md

events.md

graph-database.md

graph-model.md

index.md

procedures.md

query-execution.md

schema.md

spatial.md

traversal.md

tile.json