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

graph-database.mddocs/

Graph Database Operations

Core graph database functionality providing transaction management, query execution, and direct access to the graph data model with comprehensive ACID transaction support.

Capabilities

Graph Database Service

Represents a graph database instance and provides the primary interface for creating transactions and executing queries.

/**
 * Represents a graph database and creates transactions
 */
public interface GraphDatabaseService {
    
    /**
     * Begin a new transaction with default timeout
     * @return New transaction instance
     */
    Transaction beginTx();
    
    /**
     * Begin a new transaction with specified timeout
     * @param timeout Transaction timeout value
     * @param unit Time unit for timeout
     * @return New transaction instance
     */
    Transaction beginTx(long timeout, TimeUnit unit);
    
    /**
     * Execute a Cypher query in an auto-commit transaction
     * @param query Cypher query string
     * @throws TransactionFailureException if query execution fails
     */
    void executeTransactionally(String query);
    
    /**
     * Execute a Cypher query with parameters in an auto-commit transaction
     * @param query Cypher query string
     * @param parameters Query parameters map
     * @throws TransactionFailureException if query execution fails
     */
    void executeTransactionally(String query, Map<String, Object> parameters);
    
    /**
     * Execute a Cypher query and transform results in an auto-commit transaction
     * @param query Cypher query string
     * @param parameters Query parameters map
     * @param resultTransformer Function to transform query results
     * @return Transformed result
     * @throws TransactionFailureException if query execution fails
     */
    <T> T executeTransactionally(String query, Map<String, Object> parameters, 
                                ResultTransformer<T> resultTransformer);
    
    /**
     * Check if the database is available for operations
     * @return true if database is available, false otherwise
     */
    boolean isAvailable();
    
    /**
     * Get the name of this database
     * @return Database name
     */
    String databaseName();
    
}

Usage Examples:

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Transaction;
import java.util.Map;
import java.util.concurrent.TimeUnit;

// Check database availability
GraphDatabaseService graphDb = managementService.database("neo4j");
if (graphDb.isAvailable()) {
    System.out.println("Database " + graphDb.databaseName() + " is available");
}

// Simple auto-commit query execution
graphDb.executeTransactionally("CREATE (p:Person {name: 'Alice', age: 30})");

// Query with parameters
Map<String, Object> params = Map.of("name", "Bob", "age", 25);
graphDb.executeTransactionally(
    "CREATE (p:Person {name: $name, age: $age})", 
    params
);

// Query with result transformation
List<String> names = graphDb.executeTransactionally(
    "MATCH (p:Person) RETURN p.name as name",
    Map.of(),
    result -> {
        List<String> nameList = new ArrayList<>();
        while (result.hasNext()) {
            nameList.add((String) result.next().get("name"));
        }
        return nameList;
    }
);

// Manual transaction management
try (Transaction tx = graphDb.beginTx(30, TimeUnit.SECONDS)) {
    // Perform operations within transaction
    tx.commit();
}

Transaction Management

ACID-compliant transaction interface providing full control over database operations with commit, rollback, and resource management capabilities.

/**
 * Programmatically handled transaction with ACID properties
 * Implements AutoCloseable for try-with-resources usage
 */
public interface Transaction extends AutoCloseable {
    
    /**
     * Commit all changes made in this transaction
     * @throws TransactionFailureException if commit fails
     */
    void commit();
    
    /**
     * Rollback all changes made in this transaction
     */
    void rollback();
    
    /**
     * Close the transaction, rolling back if not already committed
     */
    @Override
    void close();
    
    /**
     * Terminate the transaction forcibly
     * This will interrupt any running operations
     */
    void terminate();
    
    /**
     * Create a new node without labels
     * @return New node instance
     */
    Node createNode();
    
    /**
     * Create a new node with specified labels
     * @param labels Labels to assign to the new node
     * @return New node instance
     */
    Node createNode(Label... labels);
    
    /**
     * Get node by ID
     * @param id Node ID
     * @return Node instance
     * @throws NotFoundException if node doesn't exist
     */
    Node getNodeById(long id);
    
    /**
     * Get relationship by ID
     * @param id Relationship ID
     * @return Relationship instance
     * @throws NotFoundException if relationship doesn't exist
     */
    Relationship getRelationshipById(long id);
    
    /**
     * Find nodes with specific label
     * @param label Label to search for
     * @return Iterable of matching nodes
     */
    ResourceIterable<Node> findNodes(Label label);
    
    /**
     * Find nodes with label and property
     * @param label Label to search for
     * @param key Property key
     * @param value Property value
     * @return Iterable of matching nodes
     */
    ResourceIterable<Node> findNodes(Label label, String key, Object value);
    
    /**
     * Execute a Cypher query within this transaction
     * @param query Cypher query string
     * @return Query result
     */
    Result execute(String query);
    
    /**
     * Execute a Cypher query with parameters within this transaction
     * @param query Cypher query string
     * @param parameters Query parameters map
     * @return Query result
     */
    Result execute(String query, Map<String, Object> parameters);
    
    /**
     * Acquire a write lock on an entity
     * @param entity Entity to lock (Node or Relationship)
     * @return Lock instance
     */
    Lock acquireWriteLock(Entity entity);
    
    /**
     * Acquire a read lock on an entity
     * @param entity Entity to lock (Node or Relationship)
     * @return Lock instance
     */
    Lock acquireReadLock(Entity entity);
    
    /**
     * Get node by element ID (preferred over getNodeById)
     * @param elementId Element ID of the node
     * @return Node instance
     * @throws NotFoundException if node doesn't exist
     */
    Node getNodeByElementId(String elementId);
    
    /**
     * Get relationship by element ID (preferred over getRelationshipById)
     * @param elementId Element ID of the relationship
     * @return Relationship instance
     * @throws NotFoundException if relationship doesn't exist
     */
    Relationship getRelationshipByElementId(String elementId);
    
    /**
     * Find a single node with specific label and property
     * @param label Label to search for
     * @param key Property key
     * @param value Property value
     * @return Single matching node, or null if not found
     */
    Node findNode(Label label, String key, Object value);
    
    /**
     * Find nodes with specific label (returns iterator for resource management)
     * @param label Label to search for
     * @return Resource iterator of matching nodes
     */
    ResourceIterator<Node> findNodes(Label label);
    
    /**
     * Get all labels currently in use in the database
     * @return Iterable of labels in use
     */
    Iterable<Label> getAllLabelsInUse();
    
    /**
     * Get all relationship types currently in use in the database
     * @return Iterable of relationship types in use
     */
    Iterable<RelationshipType> getAllRelationshipTypesInUse();
    
    /**
     * Get all property keys currently in use in the database
     * @return Iterable of property keys
     */
    Iterable<String> getAllPropertyKeys();
    
    /**
     * Create a traversal description for this transaction
     * @return New traversal description
     */
    TraversalDescription traversalDescription();
    
    /**
     * Create a bidirectional traversal description for this transaction
     * @return New bidirectional traversal description
     */
    BidirectionalTraversalDescription bidirectionalTraversalDescription();
    
    /**
     * Find all nodes in the database
     * @return ResourceIterator of all nodes
     */
    ResourceIterator<Node> getAllNodes();
    
    /**
     * Find all relationships in the database
     * @return ResourceIterator of all relationships
     */
    ResourceIterator<Relationship> getAllRelationships();
    
    /**
     * Find nodes with label and string search
     * @param label Label to search for
     * @param key Property key
     * @param template Search template
     * @param searchMode Search mode (EXACT, PREFIX, SUFFIX, CONTAINS)
     * @return ResourceIterator of matching nodes
     */
    ResourceIterator<Node> findNodes(Label label, String key, String template, StringSearchMode searchMode);
    
    /**
     * Find nodes with multiple properties
     * @param label Label to search for
     * @param propertyValues Map of property key-value pairs
     * @return ResourceIterator of matching nodes
     */
    ResourceIterator<Node> findNodes(Label label, Map<String, Object> propertyValues);
    
    /**
     * Find nodes with two properties
     * @param label Label to search for
     * @param key1 First property key
     * @param value1 First property value
     * @param key2 Second property key
     * @param value2 Second property value
     * @return ResourceIterator of matching nodes
     */
    ResourceIterator<Node> findNodes(Label label, String key1, Object value1, String key2, Object value2);
    
    /**
     * Find relationships by type and property
     * @param relationshipType Relationship type to search for
     * @param key Property key
     * @param value Property value
     * @return ResourceIterator of matching relationships
     */
    ResourceIterator<Relationship> findRelationships(RelationshipType relationshipType, String key, Object value);
    
    /**
     * Find single relationship by type and property
     * @param relationshipType Relationship type to search for
     * @param key Property key
     * @param value Property value
     * @return Single matching relationship, or null if not found
     */
    Relationship findRelationship(RelationshipType relationshipType, String key, Object value);
    
    /**
     * Get the database's schema management interface
     * @return Schema management interface
     */
    Schema schema();
}

/**
 * String search modes for text-based property queries
 */
enum StringSearchMode {
    EXACT,     // Exact string match
    PREFIX,    // Starts with the given string
    SUFFIX,    // Ends with the given string 
    CONTAINS   // Contains the given string
}

/**
 * Auto-closeable iterator for graph database resources
 */
interface ResourceIterator<T> extends Iterator<T>, AutoCloseable {
    /**
     * Close the iterator and release associated resources
     */
    void close();
}

Usage Examples:

import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.Result;
import static org.neo4j.graphdb.Label.label;

// Basic transaction usage with try-with-resources
try (Transaction tx = graphDb.beginTx()) {
    // Create nodes and relationships
    Node alice = tx.createNode(label("Person"));
    alice.setProperty("name", "Alice");
    alice.setProperty("age", 30);
    
    Node bob = tx.createNode(label("Person"));
    bob.setProperty("name", "Bob");
    
    // Create relationship
    alice.createRelationshipTo(bob, RelationshipType.withName("KNOWS"));
    
    tx.commit();
} // Transaction automatically closed

// Query execution within transaction
try (Transaction tx = graphDb.beginTx()) {
    Result result = tx.execute("MATCH (p:Person) RETURN p.name, p.age");
    while (result.hasNext()) {
        Map<String, Object> row = result.next();
        System.out.println("Person: " + row.get("p.name") + ", Age: " + row.get("p.age"));
    }
    tx.commit();
}

// Node finding operations
try (Transaction tx = graphDb.beginTx()) {
    // Find all Person nodes
    ResourceIterable<Node> persons = tx.findNodes(label("Person"));
    for (Node person : persons) {
        System.out.println("Found person: " + person.getProperty("name"));
    }
    
    // Find specific person
    ResourceIterable<Node> alices = tx.findNodes(label("Person"), "name", "Alice");
    Node alice = alices.iterator().next();
    
    tx.commit();
}

// Lock management for concurrent access
try (Transaction tx = graphDb.beginTx()) {
    Node node = tx.getNodeById(123);
    Lock lock = tx.acquireWriteLock(node);
    try {
        // Perform operations requiring exclusive access
        node.setProperty("lastModified", System.currentTimeMillis());
    } finally {
        lock.release();
    }
    tx.commit();
}

// Error handling and rollback
try (Transaction tx = graphDb.beginTx()) {
    try {
        // Risky operations
        Node node = tx.createNode();
        node.setProperty("test", someComplexOperation());
        tx.commit();
    } catch (Exception e) {
        tx.rollback();
        throw e;
    }
}

Lock Management

Locking interface for managing concurrent access to graph entities within transactions.

/**
 * Lock for controlling concurrent access to entities
 */
public interface Lock {
    /**
     * Release this lock
     */
    void release();
}

Resource Management

Resource management interfaces for handling query results and iterables that need proper cleanup.

/**
 * Iterable that manages resources and must be properly closed
 */
public interface ResourceIterable<T> extends Iterable<T>, AutoCloseable {
    /**
     * Close any resources associated with this iterable
     */
    @Override
    void close();
}

/**
 * Iterator that manages resources and must be properly closed
 */
public interface ResourceIterator<T> extends Iterator<T>, AutoCloseable {
    /**
     * Close any resources associated with this iterator
     */
    @Override
    void close();
}

Exception Handling

Common exceptions in graph database operations.

/**
 * Thrown when a transaction operation fails
 */
public class TransactionFailureException extends RuntimeException {
    public TransactionFailureException(String message, Throwable cause);
}

/**
 * Thrown when attempting to access a non-existent entity
 */
public class NotFoundException extends RuntimeException {
    public NotFoundException(String message);
}

/**
 * Thrown when a deadlock is detected
 */
public class DeadlockDetectedException extends TransactionFailureException {
    public DeadlockDetectedException(String message);
}

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