Skip to main content
ClaudeWave
Skill279 estrellas del repoactualizado 6d ago

spring-data-neo4j

This skill provides Spring Data Neo4j integration patterns for Spring Boot applications, including node entity mapping with @Node and @Relationship annotations, repository configuration for both imperative and reactive operations, custom Cypher queries using @Query, and embedded database testing setup. Use it when building graph database applications that require Neo4j node entities, relationship definitions, Cypher query execution, or Spring Data repository patterns within a Spring Boot environment.

Instalar en Claude Code
Copiar
git clone --depth 1 https://github.com/giuseppe-trisciuoglio/developer-kit /tmp/spring-data-neo4j && cp -r /tmp/spring-data-neo4j/plugins/developer-kit-java/skills/spring-data-neo4j ~/.claude/skills/spring-data-neo4j
Después abre una sesión nueva de Claude Code; el skill carga automáticamente.

SKILL.md

# Spring Data Neo4j Integration Patterns

## Overview

Provides Spring Data Neo4j integration patterns for Spring Boot applications. Covers node entity mapping with `@Node` and `@Relationship`, repository configuration (imperative and reactive), custom Cypher queries with `@Query`, and integration testing with embedded Neo4j databases.

## When to Use

Use this skill when working with:
- Graph databases and Neo4j integration in Spring Boot
- Node entities, relationships, and Cypher queries
- Spring Data Neo4j repositories (imperative or reactive)
- Neo4j testing with embedded databases

## Instructions

### 1. Set Up Spring Data Neo4j

**Add the dependency:**

Maven:
```xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-neo4j</artifactId>
</dependency>
```

Gradle:
```groovy
implementation 'org.springframework.boot:spring-boot-starter-data-neo4j'
```

**Configure connection in application.properties:**
```properties
spring.neo4j.uri=bolt://localhost:7687
spring.neo4j.authentication.username=neo4j
spring.neo4j.authentication.password=secret
```

**Configure Cypher-DSL dialect (recommended):**
```java
@Configuration
public class Neo4jConfig {
    @Bean
    Configuration cypherDslConfiguration() {
        return Configuration.newConfig()
            .withDialect(Dialect.NEO4J_5).build();
    }
}
```

> **Validation Checkpoint**: Run `MATCH (n) RETURN count(n)` via cypher-shell to verify the connection works before proceeding.

### 2. Define Node Entities

1. **Use `@`Node annotation** to mark entity classes
2. **Choose ID strategy:**
   - Business key as `@`Id (immutable, natural identifier)
   - Generated `@`Id `@`GeneratedValue (Neo4j internal ID)
3. **Define relationships** with `@`Relationship annotation
4. **Keep entities immutable** with final fields
5. **Use `@`Property** for custom property names

> **Validation Checkpoint**: If entity save fails, check for constraint violations—duplicate IDs violate uniqueness constraints.

### 3. Create Repositories

1. **Extend repository interface:**
   - `Neo4jRepository<Entity, ID>` for imperative operations
   - `ReactiveNeo4jRepository<Entity, ID>` for reactive operations
2. **Use query derivation** for simple queries
3. **Apply `@`Query annotation** for complex Cypher queries
4. **Use `$`paramName syntax** for parameters

> **Validation Checkpoint**: Test repository with `findAll()` first—if empty, verify the Neo4j instance is running and credentials are correct.

### 4. Test Your Implementation

1. **Use `@`DataNeo4jTest** for repository testing with test slicing
2. **Set up Neo4j Harness** with embedded database and fixtures
3. **Provide test data** via `withFixture()` Cypher queries
4. **Clean up test data** between tests

> **Validation Checkpoint**: If tests fail with "Connection refused", ensure the embedded Neo4j started successfully in `@BeforeAll`.

## Basic Entity Mapping

### Node Entity with Business Key

```java
@Node("Movie")
public class MovieEntity {

    @Id
    private final String title;  // Business key as ID

    @Property("tagline")
    private final String description;

    private final Integer year;

    @Relationship(type = "ACTED_IN", direction = Direction.INCOMING)
    private List<Roles> actorsAndRoles = new ArrayList<>();

    @Relationship(type = "DIRECTED", direction = Direction.INCOMING)
    private List<PersonEntity> directors = new ArrayList<>();

    public MovieEntity(String title, String description, Integer year) {
        this.title = title;
        this.description = description;
        this.year = year;
    }
}
```

### Node Entity with Generated ID

```java
@Node("Movie")
public class MovieEntity {

    @Id @GeneratedValue
    private Long id;

    private final String title;

    @Property("tagline")
    private final String description;

    public MovieEntity(String title, String description) {
        this.id = null;  // Never set manually
        this.title = title;
        this.description = description;
    }

    // Wither method for immutability with generated IDs
    public MovieEntity withId(Long id) {
        if (this.id != null && this.id.equals(id)) {
            return this;
        } else {
            MovieEntity newObject = new MovieEntity(this.title, this.description);
            newObject.id = id;
            return newObject;
        }
    }
}
```

## Repository Patterns

### Basic Repository Interface

```java
@Repository
public interface MovieRepository extends Neo4jRepository<MovieEntity, String> {

    // Query derivation from method name
    MovieEntity findOneByTitle(String title);

    List<MovieEntity> findAllByYear(Integer year);

    List<MovieEntity> findByYearBetween(Integer startYear, Integer endYear);
}
```

### Reactive Repository

```java
@Repository
public interface MovieRepository extends ReactiveNeo4jRepository<MovieEntity, String> {

    Mono<MovieEntity> findOneByTitle(String title);

    Flux<MovieEntity> findAllByYear(Integer year);
}
```

**Imperative vs Reactive:**
- Use `Neo4jRepository` for blocking, imperative operations
- Use `ReactiveNeo4jRepository` for non-blocking, reactive operations
- **Do not mix imperative and reactive in the same application**
- Reactive requires Neo4j 4+ on the database side

## Custom Queries with `@`Query

```java
@Repository
public interface AuthorRepository extends Neo4jRepository<Author, Long> {

    @Query("MATCH (b:Book)-[:WRITTEN_BY]->(a:Author) " +
           "WHERE a.name = $name AND b.year > $year " +
           "RETURN b")
    List<Book> findBooksAfterYear(@Param("name") String name,
                                   @Param("year") Integer year);

    @Query("MATCH (b:Book)-[:WRITTEN_BY]->(a:Author) " +
           "WHERE a.name = $name " +
           "RETURN b ORDER BY b.year DESC")
    List<Book> findBooksByAuthorOrderByYearDesc(@Param("name") String name);
}
```

**Custom Query Best Practices:**
- Use `$parameterName` for parameter placeholders
- Use
chunking-strategySkill

Provides chunking strategies for RAG systems. Generates chunk size recommendations (256-1024 tokens), overlap percentages (10-20%), and semantic boundary detection methods. Validates semantic coherence and evaluates retrieval precision/recall metrics. Use when building retrieval-augmented generation systems, vector databases, or processing large documents.

prompt-engineeringSkill

>

ragSkill

Implements document chunking, embedding generation, vector storage, and retrieval pipelines for Retrieval-Augmented Generation systems. Use when building RAG applications, creating document Q&A systems, or integrating AI with knowledge bases.

aws-cloudformation-auto-scalingSkill

Provides AWS CloudFormation patterns for Auto Scaling including EC2, ECS, and Lambda. Use when creating Auto Scaling groups, launch configurations, launch templates, scaling policies, lifecycle hooks, and predictive scaling. Covers template structure with Parameters, Outputs, Mappings, Conditions, cross-stack references, and best practices for high availability and cost optimization.

aws-cloudformation-bedrockSkill

Provides AWS CloudFormation patterns for Amazon Bedrock resources including agents, knowledge bases, data sources, guardrails, prompts, flows, and inference profiles. Use when creating Bedrock agents with action groups, implementing RAG with knowledge bases, configuring vector stores, setting up content moderation guardrails, managing prompts, orchestrating workflows with flows, and configuring inference profiles for model optimization.

aws-cloudformation-cloudfrontSkill

Provides AWS CloudFormation patterns for CloudFront distributions, origins (ALB, S3, Lambda@Edge, VPC Origins), CacheBehaviors, Functions, SecurityHeaders, parameters, Outputs and cross-stack references. Use when creating CloudFront distributions with CloudFormation, configuring multiple origins, implementing caching strategies, managing custom domains with ACM, configuring WAF, and optimizing performance.

aws-cloudformation-cloudwatchSkill

Provides AWS CloudFormation patterns for CloudWatch monitoring, metrics, alarms, dashboards, logs, and observability. Use when creating CloudWatch metrics, alarms, dashboards, log groups, log subscriptions, anomaly detection, synthesized canaries, Application Signals, and implementing template structure with Parameters, Outputs, Mappings, Conditions, cross-stack references, and CloudWatch best practices for monitoring production infrastructure.

aws-cloudformation-dynamodbSkill

Provides AWS CloudFormation patterns for DynamoDB tables, GSIs, LSIs, auto-scaling, and streams. Use when creating DynamoDB tables with CloudFormation, configuring primary keys, local/global secondary indexes, capacity modes (on-demand/provisioned), point-in-time recovery, encryption, TTL, and implementing template structure with Parameters, Outputs, Mappings, Conditions, cross-stack references.