🔍 Code Extractor

function check_node_exists

Maturity: 50

Checks if a node with a specified label and matching properties exists in a Neo4j graph database.

File:
/tf/active/vicechatdev/CDocs/db/db_operations.py
Lines:
836 - 881
Complexity:
moderate

Purpose

This function queries a Neo4j database to determine whether a node with a given label and set of properties already exists. It constructs a parameterized Cypher query to match nodes based on the provided label and property dictionary, returning a boolean indicating existence. This is useful for preventing duplicate node creation, validating data before operations, or implementing conditional logic based on node existence.

Source Code

def check_node_exists(label, properties):
    """
    Check if a node with the given label and properties exists.
    
    Parameters
    ----------
    label : str
        The node label
    properties : dict
        Properties to match for the node
    
    Returns
    -------
    bool
        True if the node exists, False otherwise
    """
    try:
        # Construct property match string
        property_matches = []
        params = {}
        
        for key, value in properties.items():
            property_matches.append(f"n.{key} = ${key}")
            params[key] = value
        
        property_match_str = " AND ".join(property_matches)
        
        # Build the query
        query = f"""
        MATCH (n:{label})
        WHERE {property_match_str}
        RETURN count(n) as count
        """
        
        # Execute the query
        result = run_query(query, params)
        
        # Check if any nodes were found
        if result and 'count' in result[0]:
            return result[0]['count'] > 0
            
        return False
        
    except Exception as e:
        logger.error(f"Error checking if node exists: {str(e)}")
        return False

Parameters

Name Type Default Kind
label - - positional_or_keyword
properties - - positional_or_keyword

Parameter Details

label: A string representing the Neo4j node label to search for (e.g., 'Person', 'Document', 'User'). This should be a valid Neo4j label name without special characters or spaces.

properties: A dictionary containing key-value pairs of properties to match against the node. All properties in this dictionary must match for the node to be considered existing. Keys should be valid property names (strings), and values can be any type supported by Neo4j (strings, numbers, booleans, etc.). An empty dictionary will match any node with the given label.

Return Value

Returns a boolean value: True if at least one node with the specified label and all matching properties exists in the database, False if no matching node is found or if an error occurs during the query execution.

Dependencies

  • neo4j
  • logging
  • typing

Required Imports

import logging
from typing import Dict

Usage Example

# Assuming run_query and logger are already defined in the module

# Check if a user node exists
user_exists = check_node_exists(
    label='User',
    properties={'email': 'john@example.com', 'active': True}
)

if user_exists:
    print('User already exists')
else:
    print('User not found, can create new user')

# Check if a document with specific ID exists
doc_exists = check_node_exists(
    label='Document',
    properties={'doc_id': '12345'}
)

# Check with multiple properties
node_exists = check_node_exists(
    label='Person',
    properties={
        'name': 'Alice',
        'age': 30,
        'department': 'Engineering'
    }
)

Best Practices

  • Always provide non-empty properties dictionary to avoid matching all nodes with the given label
  • Ensure property keys match exactly with the node properties in the database (case-sensitive)
  • Handle the False return value carefully as it can indicate both non-existence and error conditions
  • Consider checking logger output for errors when False is returned to distinguish between no match and query failure
  • Use indexed properties in the properties dictionary for better query performance on large databases
  • Be aware that this function uses parameterized queries to prevent Cypher injection attacks
  • The function catches all exceptions and returns False, so check logs for debugging if unexpected False results occur
  • Ensure the run_query function is properly implemented and returns results in the expected format (list of dictionaries with 'count' key)

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_nodes_by_label 65.5% similar

    Retrieves nodes from a Neo4j graph database by label with optional property filtering, pagination, and sorting capabilities.

    From: /tf/active/vicechatdev/CDocs/db/db_operations.py
  • function node_exists 62.8% similar

    Checks if a node with a specific UID exists in a Neo4j graph database by querying for the node and returning a boolean result.

    From: /tf/active/vicechatdev/CDocs/db/db_operations.py
  • function create_node_and_ensure_relationships 59.4% similar

    Creates a new node in a Neo4j graph database and establishes multiple relationships to existing nodes within a single atomic transaction.

    From: /tf/active/vicechatdev/CDocs/db/db_operations.py
  • function create_node_with_uid 58.4% similar

    Creates a new node in a Neo4j graph database with a specified UID, label, and properties, automatically adding a creation timestamp if not provided.

    From: /tf/active/vicechatdev/CDocs/db/db_operations.py
  • function create_node 55.9% similar

    Creates a node in a Neo4j graph database with a specified label and properties, automatically generating a unique ID and timestamp if not provided.

    From: /tf/active/vicechatdev/CDocs/db/db_operations.py
← Back to Browse