Regenerate all MDC rules with fresh Exa data and December 2025 best practices

- Refreshed all 241 library rules with current best practices
- Updated Exa search results for all libraries with 2025 content
- Fixed --regenerate-all flag logic to properly process all libraries
- Removed duplicate astro entry in rules.json (merged tags)
- Added missing docker.mdc and vim.mdc files
- All rules now include modern patterns and anti-patterns
- Updated with framework-specific recommendations for 2025

Technical improvements:
- Fixed retry_failed_only logic in generate_mdc_files.py
- Improved progress tracking for regeneration scenarios
- Ensured proper handling of --refresh-exa flag
This commit is contained in:
sanjeed5
2025-12-17 22:40:28 +05:30
parent 331fb6ffac
commit 8fbf269085
244 changed files with 66701 additions and 52708 deletions
+229 -231
View File
@@ -1,278 +1,276 @@
---
description: This rule provides guidelines for best practices and coding standards when developing applications with Neo4j. It covers aspects from code organization and performance to security and testing.
globs: *.cypher
description: This guide defines the definitive best practices for writing Cypher queries and modeling data in Neo4j, ensuring readability, performance, and security for all team projects.
globs: **/*
---
# Neo4j Development Best Practices
# neo4j Best Practices
This document outlines best practices and coding standards for developing applications using Neo4j. These guidelines are designed to promote maintainability, performance, and security.
Library Information:
- Name: neo4j
- Tags: database, graph, nosql, relationships
This document outlines the mandatory guidelines for developing with Neo4j. Adhering to these rules ensures our Cypher queries are performant, secure, and maintainable.
## 1. Code Organization and Structure
### 1.1 Directory Structure
### 1.1. Standardize Naming Conventions
Consistency is paramount. Use the recommended casing for all identifiers to prevent subtle bugs due to Cypher's case-sensitivity.
* **Node Labels:** `PascalCase`
* **Relationship Types:** `UPPER_SNAKE_CASE`
* **Property Keys:** `camelCase`
* **Variables:** `camelCase`
**❌ BAD:**
```cypher
MATCH (p:person)-[r:friend_of]->(f:Friend)
WHERE p.first_name = 'Alice'
RETURN f.last_name
```
**✅ GOOD:**
```cypher
MATCH (p:Person)-[r:FRIEND_OF]->(f:Person)
WHERE p.firstName = 'Alice'
RETURN f.lastName
```
### 1.2. Escape Special Characters Judiciously
Only use backticks (`` ` ``) when an identifier *must* contain special characters, spaces, or start with a non-alphabetic character. Avoid them otherwise to keep queries clean.
**❌ BAD:**
```cypher
MATCH (`my node`:`User Label`)
WHERE `my node`.`user-id` = 123
RETURN `my node`.`user-name`
```
**✅ GOOD:**
```cypher
MATCH (u:User)
WHERE u.userId = 123
RETURN u.userName
```
*If a special character is truly unavoidable:*
```cypher
MATCH (n:`1stUser`)
WHERE n.`user-id` = 123
RETURN n.userName
```
### 1.3. Always Use Cypher 25
New features and performance improvements are exclusively added to Cypher 25. Avoid older versions like 5.x.
## 2. Data Modeling
### 2.1. Design for Query-Ability
Model your graph around the most common traversals and business questions. Prioritize relationships that directly answer real-world queries over mimicking relational schemas.
**❌ BAD:** (Relational thinking, too many properties on nodes, generic relationships)
```cypher
// Modeling a "User" and their "Address" as separate nodes, but linking them generically
CREATE (u:User {id: 'u1', name: 'Alice'})
CREATE (a:Address {id: 'a1', street: '123 Main St', city: 'Anytown'})
CREATE (u)-[:HAS]->(a) // Generic relationship
```
**✅ GOOD:** (Graph-native, explicit relationship type, Address properties on User if 1:1)
```cypher
// If Address is always tied to a User and not shared, keep properties on the User node.
// If Address can be shared or has complex relationships, make it a node with a specific relationship.
CREATE (u:User {userId: 'u1', name: 'Alice', street: '123 Main St', city: 'Anytown'})
// If Address is a separate entity (e.g., shared by multiple users, or has its own complex relationships)
CREATE (u:User {userId: 'u1', name: 'Alice'})
CREATE (a:Address {addressId: 'a1', street: '123 Main St', city: 'Anytown'})
CREATE (u)-[:LIVES_AT]->(a) // Specific relationship type
```
### 2.2. Leverage Constraints for Data Integrity
Enforce uniqueness, existence, and type constraints on key properties. This ensures data quality and automatically creates backing indexes for performance.
**❌ BAD:** (No constraints, allowing duplicate or missing critical data)
```cypher
CREATE (p:Person {email: 'alice@example.com'})
CREATE (p:Person {email: 'alice@example.com'}) // Duplicate allowed
```
**✅ GOOD:** (Unique constraint on email, existence constraint on name)
```cypher
// Run these DDL statements once during schema setup
CREATE CONSTRAINT FOR (p:Person) REQUIRE p.email IS UNIQUE;
CREATE CONSTRAINT FOR (p:Person) REQUIRE p.name IS NOT NULL;
CREATE CONSTRAINT FOR (p:Person) REQUIRE p.age IS OF TYPE INTEGER; // Cypher 25 type constraint
// Now, duplicate email will fail, and missing name will fail
CREATE (p:Person {email: 'alice@example.com', name: 'Alice', age: 30})
```
## 3. Common Patterns and Anti-patterns
### 3.1. Always Use Parameters for Dynamic Values
Parameterized queries prevent Cypher injection vulnerabilities and allow the query planner to cache execution plans, significantly improving performance.
**❌ BAD:** (String concatenation, injection risk, no plan caching)
```cypher
// In application code:
const userId = "123 OR 1=1"; // Malicious input
const query = `MATCH (u:User {userId: '${userId}'}) RETURN u.name`;
// Result: MATCH (u:User {userId: '123 OR 1=1'}) RETURN u.name
```
**✅ GOOD:** (Parameterized query, safe, plan caching)
```cypher
// In application code:
const userId = "123 OR 1=1"; // Malicious input
const query = `MATCH (u:User {userId: $userId}) RETURN u.name`;
const params = { userId: userId };
// Result: MATCH (u:User {userId: '123 OR 1=1'}) RETURN u.name (as a literal string value for $userId)
```
Organize your project with a clear directory structure that separates concerns. A recommended structure is as follows:
### 3.2. Leverage Native Map Projections
Use map projections (`{ .property }`) to return specific properties or computed values efficiently, especially with Cypher 25's enhancements.
project_root/
├── data/ # Contains data files for import/export
├── queries/ # Stores Cypher queries
├── src/ # Source code for the application
│ ├── models/ # Defines data models and graph schemas
│ ├── services/ # Contains business logic and Neo4j interactions
│ ├── utils/ # Utility functions and helper classes
│ ├── config/ # Configuration files
│ └── app.js # Main application file
├── tests/ # Unit, integration, and end-to-end tests
├── .env # Environment variables
├── package.json # Node.js project configuration
├── requirements.txt # Python project dependencies
└── README.md
**❌ BAD:** (Returning entire nodes/relationships, then filtering in application code)
```cypher
MATCH (u:User {userId: $userId})
RETURN u
// Application code then extracts u.name, u.email
```
**✅ GOOD:** (Returning only necessary properties)
```cypher
MATCH (u:User {userId: $userId})
RETURN { name: u.name, email: u.email, age: u.age } AS userDetails
// Or, for all properties: RETURN u { .* }
```
### 1.2 File Naming Conventions
## 4. Performance Considerations
* **Cypher Queries:** Use descriptive names (e.g., `get_user_friends.cypher`).
* **Models:** Name files according to the entity they represent (e.g., `user.js`, `movie.py`).
* **Services:** Use a service-based naming convention (e.g., `user_service.js`, `movie_service.py`).
* **Tests:** Match test file names to the source file names (e.g., `user_service.test.js`).
### 4.1. Create Indexes on Frequently Filtered Properties
### 1.3 Module Organization
Indexes drastically speed up `MATCH` and `WHERE` clauses on specific properties. Always create them for properties used in lookups, filtering, or ordering. Constraints often create indexes automatically.
Break down your application into modules based on functionality. Use well-defined interfaces and avoid circular dependencies.
**❌ BAD:** (Scanning all nodes for a property without an index)
```cypher
MATCH (p:Product)
WHERE p.sku = 'XYZ-789' // No index on Product.sku
RETURN p.name
```
* **Node.js:** Use ES modules (`import`, `export`) or CommonJS (`require`, `module.exports`).
* **Python:** Utilize packages and modules for organizing code.
**✅ GOOD:** (Index on `Product.sku`)
```cypher
// Run this DDL statement once during schema setup
CREATE INDEX FOR (p:Product) ON (p.sku);
### 1.4 Component Architecture
// Now, this query uses the index for fast lookup
MATCH (p:Product)
WHERE p.sku = 'XYZ-789'
RETURN p.name
```
Design a component architecture that promotes reusability and maintainability. Consider using patterns like Model-View-Controller (MVC) or a layered architecture.
### 4.2. Profile and Explain Hot Queries
* **Models:** Define data structures and interact with the Neo4j database.
* **Services:** Implement business logic and handle data manipulation.
* **Controllers (or equivalent):** Handle user requests and orchestrate interactions between models and services.
Always use `PROFILE` or `EXPLAIN` to understand query execution plans. This is the only way to identify bottlenecks and ensure indexes are being used correctly.
### 1.5 Code Splitting
**✅ GOOD:**
```cypher
PROFILE
MATCH (u:User)-[:PURCHASED]->(p:Product)
WHERE u.country = 'USA' AND p.category = 'Electronics'
RETURN u.name, p.name
```
Analyze the output to see operations, costs, and if indexes are utilized.
For large applications, use code splitting to improve initial load times. Load modules and components on demand when they are needed.
## 5. Common Pitfalls and Gotchas
* **Node.js:** Use dynamic imports (`import()`) for on-demand loading.
* **Frontend Frameworks (if applicable):** Use framework-specific code-splitting techniques (e.g., React.lazy, Vue.js's async components).
### 5.1. Case-Sensitivity of Identifiers
## 2. Common Patterns and Anti-patterns
Remember that Cypher identifiers are case-sensitive. `Person` is different from `person`. Adhere to naming conventions to avoid this.
### 2.1 Design Patterns
**❌ BAD:**
```cypher
MATCH (p:person) // Label is 'Person' in schema
RETURN p.name
```
* **Repository Pattern:** Abstract data access logic behind a repository interface. This makes it easier to switch database implementations or mock data access for testing.
* **Unit of Work:** Group multiple database operations into a single transaction to ensure atomicity.
* **Data Mapper:** Transfer data between domain objects and the database.
* **Graph Traversal Pattern:** Encapsulate common graph traversal logic into reusable functions or classes.
**✅ GOOD:**
```cypher
MATCH (p:Person) // Correct label casing
RETURN p.name
```
### 2.2 Recommended Approaches for Common Tasks
### 5.2. Variable Re-use Within Scope
* **Creating Nodes and Relationships:** Use Cypher queries with parameters to avoid SQL injection and improve performance.
* **Querying Data:** Use Cypher's `MATCH` clause for efficient graph traversal. Leverage indexes and constraints for optimal query performance.
* **Data Validation:** Validate data before inserting it into the database. Use constraints to enforce data integrity at the database level.
* **Error Handling:** Implement robust error handling to gracefully handle database errors and prevent application crashes.
Node and relationship variables must be unique within the same query scope.
### 2.3 Anti-patterns and Code Smells
**❌ BAD:**
```cypher
MATCH (a)-[a]->(b) // 'a' used for both node and relationship
RETURN a, b
```
* **Over-fetching Data:** Avoid retrieving unnecessary data from the database. Use projections in Cypher queries to select only the required properties.
* **Long Cypher Queries:** Break down complex Cypher queries into smaller, more manageable queries.
* **Lack of Indexing:** Ensure that frequently queried properties are indexed to improve query performance.
* **Ignoring Constraints:** Define and enforce constraints to maintain data integrity and consistency.
* **Hardcoding Values:** Avoid hardcoding values in Cypher queries. Use parameters instead.
* **Excessive Relationship Traversal in Application Code:** Prefer to execute complex relationship traversals within Cypher rather than in application code which reduces the amount of data transported and is significantly faster.
**✅ GOOD:**
```cypher
MATCH (a)-[r]->(b) // Unique variables 'a' and 'r'
RETURN a, b
```
### 2.4 State Management
## 6. Security Best Practices
* **Stateless Services:** Design services to be stateless to improve scalability and testability.
* **Session Management:** Use appropriate session management techniques for web applications.
* **Caching:** Implement caching to reduce database load and improve response times.
### 6.1. Parameterized Queries (Reiterated)
### 2.5 Error Handling
This is the single most important security measure for Cypher. Never concatenate user input directly into queries.
* **Centralized Error Handling:** Implement a centralized error handling mechanism to handle exceptions consistently.
* **Logging:** Log errors and warnings to help with debugging and monitoring.
* **Retry Logic:** Implement retry logic for transient database errors.
* **Custom Exceptions:** Define custom exceptions for specific error conditions.
* **Graceful Degradation:** Design the application to degrade gracefully in case of database failures.
### 6.2. Least Privilege Principle
## 3. Performance Considerations
Grant database users only the minimum necessary permissions. Avoid using a single, highly privileged user for all application interactions.
### 3.1 Optimization Techniques
## 7. Query Optimization
* **Indexing:** Create indexes on frequently queried properties.
* **Constraints:** Use constraints to enforce data integrity and improve query performance.
* **Query Optimization:** Analyze Cypher query execution plans and optimize queries for performance.
* **Connection Pooling:** Use connection pooling to reuse database connections and reduce connection overhead.
* **Batch Operations:** Use batch operations to insert or update multiple nodes and relationships in a single transaction.
* **Profile Queries:** Use `PROFILE` or `EXPLAIN` to understand query performance.
* **Use `apoc.periodic.iterate` for batch processing** When dealing with large datasets, `apoc.periodic.iterate` allows for batch processing and avoids exceeding memory limits.
### 7.1. Start `MATCH` Patterns with Indexed Nodes
### 3.2 Memory Management
When possible, begin your `MATCH` clause with a node that has a label and an indexed property used in the `WHERE` clause. This allows the query planner to efficiently find a starting point.
* **Limit Result Set Size:** Use `LIMIT` in Cypher queries to restrict the number of returned results.
* **Stream Data:** Stream data from the database to avoid loading large amounts of data into memory.
* **Garbage Collection:** Monitor garbage collection and tune JVM settings for optimal performance (Java-based implementations).
**❌ BAD:** (Starting with a generic pattern, then filtering)
```cypher
MATCH (n)-[r]->(m)
WHERE n.id = $id AND m.type = $type
RETURN n, m
```
### 3.3 Bundle Size Optimization
**✅ GOOD:** (Starting with a specific, indexed node)
```cypher
MATCH (n:User {id: $id})-[:OWNS]->(m:Product {type: $type})
RETURN n, m
```
* **Tree shaking** remove unused code
* **Minification:** Minify code to reduce bundle size.
* **Compression:** Compress bundles to reduce transfer size.
### 7.2. Limit Results Early
### 3.4 Lazy Loading
If you only need a subset of results, apply `LIMIT` as early as possible in your query to reduce the amount of data processed and transferred.
* **On-Demand Loading:** Load data and components on demand when they are needed.
* **Pagination:** Use pagination to load data in smaller chunks.
**❌ BAD:** (Returning many results, then limiting in application)
```cypher
MATCH (n:User)-[:FOLLOWS]->(f:User)
RETURN n, f
// Application takes first 10
```
## 4. Security Best Practices
**✅ GOOD:** (Limiting in Cypher)
```cypher
MATCH (n:User)-[:FOLLOWS]->(f:User)
RETURN n, f
LIMIT 10
```
### 4.1 Common Vulnerabilities
## 8. Testing Approaches
* **Cypher Injection:** Prevent Cypher injection by using parameterized queries.
* **Authentication Bypass:** Secure authentication mechanisms and avoid relying on client-side authentication.
* **Data Exposure:** Protect sensitive data by encrypting it at rest and in transit.
* **Authorization Flaws:** Implement robust authorization mechanisms to control access to resources.
### 8.1. Unit Test Cypher Query Construction
### 4.2 Input Validation
For complex queries built dynamically, write unit tests to ensure the generated Cypher strings are correct and adhere to naming conventions and parameterization.
* **Sanitize Inputs:** Sanitize user inputs to prevent Cross-Site Scripting (XSS) attacks.
* **Validate Inputs:** Validate user inputs to ensure they conform to expected formats and values.
* **Parameterize Queries:** Always use parameterized queries to prevent Cypher injection.
### 8.2. Integration Tests Against a Test Database
### 4.3 Authentication and Authorization
* **Secure Authentication:** Use strong authentication mechanisms such as OAuth 2.0 or JWT.
* **Role-Based Access Control (RBAC):** Implement RBAC to control access to resources based on user roles.
* **Least Privilege Principle:** Grant users only the minimum necessary permissions.
* **Neo4j's built-in security:** Utilize Neo4j's built-in authentication and authorization mechanisms for database access.
### 4.4 Data Protection
* **Encryption at Rest:** Encrypt sensitive data at rest using Neo4j's encryption features or third-party encryption solutions.
* **Encryption in Transit:** Use HTTPS to encrypt data in transit.
* **Data Masking:** Mask sensitive data in logs and reports.
* **Regular Backups:** Perform regular backups to protect against data loss.
* **Database Auditing:** Enable database auditing to track access and modifications to data.
* **Avoid Storing Sensitive Data:** Only store necessary sensitive data. Consider tokenization or anonymization where applicable.
### 4.5 Secure API Communication
* **HTTPS:** Use HTTPS for all API communication.
* **API Keys:** Use API keys to authenticate API requests.
* **Rate Limiting:** Implement rate limiting to prevent abuse.
* **Input Validation:** Validate API requests to prevent malicious input.
## 5. Testing Approaches
### 5.1 Unit Testing
* **Test Individual Components:** Unit test individual components in isolation.
* **Mock Dependencies:** Use mocking to isolate components from external dependencies.
* **Test Edge Cases:** Test edge cases and boundary conditions.
* **Test Data Validation** Unit tests should cover data validation logic.
### 5.2 Integration Testing
* **Test Interactions:** Test the interactions between different components.
* **Test Database Interactions:** Test the interactions between the application and the Neo4j database.
* **Use Test Databases:** Use separate test databases for integration tests.
### 5.3 End-to-End Testing
* **Test Full Workflows:** Test the complete end-to-end workflows of the application.
* **Automate Tests:** Automate end-to-end tests to ensure consistent results.
### 5.4 Test Organization
* **Organize Tests:** Organize tests in a clear and logical manner.
* **Use Test Suites:** Use test suites to group related tests together.
* **Naming Convention:** Follow a clear naming convention for test files and test methods.
### 5.5 Mocking and Stubbing
* **Mock Neo4j Driver:** Mock the Neo4j driver to isolate components from the database.
* **Stub Responses:** Stub database responses to control the data returned by the database.
* **Verify Interactions:** Verify that components interact with the database as expected.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes
* **Lack of Planning:** Failing to properly plan the graph schema and data model.
* **Ignoring Performance:** Neglecting to optimize Cypher queries and database configuration.
* **Poor Security:** Failing to implement proper security measures.
* **Insufficient Testing:** Insufficient testing leading to bugs and regressions.
* **Not Utilizing Indexes:** Neglecting to create indexes on frequently queried properties.
### 6.2 Edge Cases
* **Large Graphs:** Handling very large graphs with millions or billions of nodes and relationships.
* **Concurrent Access:** Managing concurrent access to the database.
* **Transaction Management:** Properly managing transactions to ensure data consistency.
* **Handling Null Values:** Understanding how Neo4j handles null values and handling them appropriately.
### 6.3 Version-Specific Issues
* **API Changes:** Be aware of API changes between different versions of the Neo4j driver and database.
* **Cypher Syntax:** Be aware of changes to the Cypher syntax in different versions of Neo4j.
* **Deprecated Features:** Avoid using deprecated features.
### 6.4 Compatibility Concerns
* **Driver Compatibility:** Ensure that the Neo4j driver is compatible with the version of the Neo4j database.
* **Operating System Compatibility:** Ensure that the application is compatible with the target operating system.
* **Java Version Compatibility:** Ensure the Java version is compatible (if using Java-based drivers).
### 6.5 Debugging Strategies
* **Logging:** Use logging to track the execution of the application and identify errors.
* **Debuggers:** Use debuggers to step through the code and inspect variables.
* **Neo4j Browser:** Use the Neo4j Browser to visualize the graph and execute Cypher queries.
* **Cypher Profiler:** Use the Cypher profiler to analyze the performance of Cypher queries.
* **APOC Procedures:** Use APOC Procedures to aid with debugging and monitoring.
## 7. Tooling and Environment
### 7.1 Recommended Development Tools
* **Neo4j Browser:** A web-based interface for interacting with the Neo4j database.
* **Neo4j Desktop:** A desktop application for managing Neo4j databases.
* **IntelliJ IDEA/PyCharm:** IDEs with excellent support for Neo4j development.
* **VS Code:** Popular code editor with Neo4j extensions.
* **APOC Library:** Provides many helpful stored procedures.
### 7.2 Build Configuration
* **Dependency Management:** Use a dependency management tool (e.g., npm, pip) to manage project dependencies.
* **Environment Variables:** Use environment variables to configure the application for different environments.
* **Build Scripts:** Use build scripts to automate the build process.
### 7.3 Linting and Formatting
* **ESLint/Pylint:** Use linters to enforce coding standards and identify potential errors.
* **Prettier/Black:** Use formatters to automatically format code.
* **Consistent Style:** Maintain a consistent coding style throughout the project.
### 7.4 Deployment Best Practices
* **Containerization:** Use containerization (e.g., Docker) to package the application and its dependencies.
* **Cloud Deployment:** Deploy the application to a cloud platform (e.g., AWS, Azure, GCP).
* **Load Balancing:** Use load balancing to distribute traffic across multiple instances of the application.
* **Monitoring:** Monitor the application to detect and respond to issues.
* **Immutable Infrastructure:** Treat servers as immutable; rebuild instead of modifying.
### 7.5 CI/CD Integration
* **Automated Builds:** Automate the build process using a CI/CD pipeline.
* **Automated Tests:** Run automated tests as part of the CI/CD pipeline.
* **Automated Deployments:** Automate the deployment process using a CI/CD pipeline.
* **Version Control:** Use version control (e.g., Git) to manage the codebase.
* **Trunk-Based Development:** Consider trunk-based development for faster feedback cycles.
By following these best practices, developers can build robust, scalable, and secure Neo4j applications.
Execute your application's Cypher queries against a dedicated, isolated test Neo4j instance. This validates query correctness, data integrity, and performance under realistic conditions. Use tools like Testcontainers for ephemeral Neo4j instances.