Back to "डाटा- लाइब्रेरी पार्ट 1. 3: ईएफ कोर के साथ भौतिक पथ"

This is a viewer only at the moment see the article on how this works.

To update the preview hit Ctrl-Alt-R (or ⌘-Alt-R on Mac) or Enter to refresh. The Save icon lets you save the markdown file to disk

This is a preview from the server running through my markdig pipeline

EF Hierarchies Entity Framework PostgreSQL

डाटा- लाइब्रेरी पार्ट 1. 3: ईएफ कोर के साथ भौतिक पथ

Saturday, 06 December 2025

भौतिक रूप से बनायी गयी पथ संपूर्ण याद किए गए वाक्यांश - जैसे हैं /1/3/7/ - किसी भी साथ में शामिल होने के बिना पूर्वज तेजी से पढ़ने के लिए. रोटीबलिक पीढ़ी और मानव पढ़ने योग्य डिबगिंग के लिए बिल्कुल सही है, हालांकि उप- वृक्ष आगे बढ़ने का मतलब है हर वंशज के पथ स्ट्रिंग को रोकने का मतलब है.

श्रेणी नेविगेशन


धन - दौलत के पीछे भागने का रास्ता क्या है?

वस्तुयुक्त पथ पैटर्न (जिसे "लाइट" भी कहा जाता है) जो कोलको के पेड़ और हिमीटर्स) "मेरे माता पिता नोड ५ है" को जमा करने के बजाय, हम "मैं 1 नोड्स 1 के माध्यम से पहुँच रहा हूँ 3

इसके बारे में सोचो पूर्ण यूआरएल को सिर्फ पृष्ठ नाम के बजाए जमा करता है. /blog/posts/2024/my-article आप कहाँ हैं वास्तव में आपको बताता है, कोई तलाश की जरूरत नहीं है.

मुख्य अन्तर्दृष्टि: हम व्यापार प्रश्नों के लिए सहज रूप से काम कर रहे हैं . Calth हर पंक्ति में सामान्य है, लेकिन यह पूर्वजों को मामूली - सिर्फ स्ट्रिंग का विश्लेषण करता है.

कन्वरेड दृश्‍य

flowchart TD
    subgraph "Comment Tree"
        C1["Comment 1<br/>Path: /1/"]
        C2["Comment 2<br/>Path: /1/2/"]
        C3["Comment 3<br/>Path: /1/3/"]
        C4["Comment 4<br/>Path: /1/3/4/"]
    end

    C1 --> C2
    C1 --> C3
    C3 --> C4

    subgraph "What the paths tell us"
        P1["Comment 4's path /1/3/4/ means:<br/>• Ancestors are 1, 3 (parse the path)<br/>• Depth is 3 (count separators - 1)<br/>• Root is 1 (first element)"]
    end

    style C1 stroke:#6366f1,stroke-width:2px
    style C2 stroke:#8b5cf6,stroke-width:2px
    style C3 stroke:#8b5cf6,stroke-width:2px
    style C4 stroke:#a855f7,stroke-width:2px

पथ आत्म- भुलावे में है.

  • पूर्वज पढ़ा जा रहा है: व्याख्या /1/3/4/ बंद करें (C) [1, 3, 4]
  • संतति ढूंढ रहे: प्रश्न WHERE path LIKE '/1/3/%' _FAQ सभी नोड 3 के तहत हो जाता है
  • गहराई की गणना कर रहा है: विभाजक शून्य से एक गणना करें
  • भाई - बहन खोज रहे हैं: प्रश्न WHERE path LIKE '/1/3/_/' ( 3) बच्चों को अलग करना

एंटिटी परिभाषा

एंटिटी एक ही पथ स्तम्भ जोड़ता है:

public class Comment
{
    public int Id { get; set; }
    public string Content { get; set; } = string.Empty;
    public string Author { get; set; } = string.Empty;
    public DateTime CreatedAt { get; set; }

    public int PostId { get; set; }
    public BlogPost Post { get; set; } = null!;

    // ========== MATERIALISED PATH ==========

    // The complete path from root to this node
    // Format: /ancestor1/ancestor2/.../thisNode/
    // Examples:
    //   Root comment: "/1/"
    //   Child of 1: "/1/5/"
    //   Grandchild: "/1/5/12/"
    //
    // The leading and trailing slashes make pattern matching easier:
    // - LIKE '/1/%' finds all descendants of 1 (includes /1/ itself)
    // - LIKE '/1/5/%' finds all descendants of 5 under 1
    public string Path { get; set; } = string.Empty;

    // We still keep ParentCommentId for:
    // 1. Quick "who is my parent" without parsing
    // 2. EF Core navigation properties
    // 3. Data integrity (can validate path matches parent relationship)
    public int? ParentCommentId { get; set; }
    public Comment? ParentComment { get; set; }
    public ICollection<Comment> Children { get; set; } = new List<Comment>();

    // ========== COMPUTED HELPERS ==========

    // Parse ancestors from path - not stored, computed on demand
    public IEnumerable<int> GetAncestorIds()
    {
        if (string.IsNullOrEmpty(Path)) yield break;

        // Split "/1/3/4/" into ["", "1", "3", "4", ""]
        var parts = Path.Split('/', StringSplitOptions.RemoveEmptyEntries);

        // Return all except the last (which is this node's ID)
        for (int i = 0; i < parts.Length - 1; i++)
        {
            if (int.TryParse(parts[i], out var id))
                yield return id;
        }
    }

    // Calculate depth from path
    public int GetDepth()
    {
        if (string.IsNullOrEmpty(Path)) return 0;
        // Count segments: "/1/3/4/" has 3 segments, depth is 2 (0-indexed from root)
        return Path.Split('/', StringSplitOptions.RemoveEmptyEntries).Length - 1;
    }
}

ईएफ कोर कॉन्फ़िगरेशन

public class CommentConfiguration : IEntityTypeConfiguration<Comment>
{
    public void Configure(EntityTypeBuilder<Comment> builder)
    {
        builder.HasKey(c => c.Id);

        builder.Property(c => c.Content)
            .IsRequired()
            .HasMaxLength(10000);

        builder.Property(c => c.Author)
            .IsRequired()
            .HasMaxLength(200);

        // ========== PATH COLUMN ==========
        // Set a reasonable max length - this limits your tree depth
        // /1/12345/12346/12347/...
        // Each segment is up to ~7 chars (ID + slash), so 1000 chars ≈ 140 levels
        builder.Property(c => c.Path)
            .IsRequired()
            .HasMaxLength(1000);

        // Relationship to blog post
        builder.HasOne(c => c.Post)
            .WithMany(p => p.Comments)
            .HasForeignKey(c => c.PostId)
            .OnDelete(DeleteBehavior.Cascade);

        // Self-referencing (optional but useful)
        builder.HasOne(c => c.ParentComment)
            .WithMany(c => c.Children)
            .HasForeignKey(c => c.ParentCommentId)
            .OnDelete(DeleteBehavior.Restrict);

        // ========== INDEXES ==========

        // Standard indexes
        builder.HasIndex(c => c.PostId);
        builder.HasIndex(c => c.ParentCommentId);

        // PATH INDEX - Critical for performance!
        // This makes LIKE 'prefix%' queries efficient
        // PostgreSQL can use a B-tree index for prefix LIKE patterns
        // (but NOT for '%suffix' or '%contains%' patterns)
        builder.HasIndex(c => c.Path);

        // For PostgreSQL, a text_pattern_ops index is even better for LIKE:
        // CREATE INDEX ix_comments_path ON comments (path text_pattern_ops);
        // You may want to add this via a raw migration
    }
}

डाटाबेस स्कीमा

erDiagram
    COMMENT {
        int id PK
        string content
        string author
        datetime created_at
        int post_id FK
        int parent_comment_id FK "optional"
        string path "e.g. /1/3/7/"
    }

    BLOG_POST {
        int id PK
        string title
        string content
    }

    BLOG_POST ||--o{ COMMENT : "has"
    COMMENT ||--o{ COMMENT : "parent-child"

संचालन

नया टिप्पणी प्रविष्ट करें

प्रविष्ट किया जा रहा है जनक के पथ से:

public async Task<Comment> AddCommentAsync(
    int postId,
    int? parentId,
    string author,
    string content,
    CancellationToken ct = default)
{
    string path;

    if (parentId.HasValue)
    {
        // Get parent's path to extend it
        var parentPath = await context.Comments
            .Where(c => c.Id == parentId.Value)
            .Select(c => c.Path)
            .FirstOrDefaultAsync(ct);

        if (parentPath == null)
        {
            throw new InvalidOperationException($"Parent comment {parentId} not found");
        }

        // We need the ID first, so we'll update the path after saving
        // (Chicken-and-egg: path contains our ID, but we don't have ID until saved)

        var comment = new Comment
        {
            PostId = postId,
            ParentCommentId = parentId,
            Author = author,
            Content = content,
            CreatedAt = DateTime.UtcNow,
            Path = string.Empty  // Temporary - will update after save
        };

        context.Comments.Add(comment);
        await context.SaveChangesAsync(ct);

        // Now we have the ID - build the real path
        // Parent path "/1/3/" + our ID "7" = "/1/3/7/"
        comment.Path = $"{parentPath}{comment.Id}/";
        await context.SaveChangesAsync(ct);

        logger.LogInformation("Added comment {CommentId} with path {Path}", comment.Id, comment.Path);
        return comment;
    }
    else
    {
        // Root comment - path is just our ID
        var comment = new Comment
        {
            PostId = postId,
            ParentCommentId = null,
            Author = author,
            Content = content,
            CreatedAt = DateTime.UtcNow,
            Path = string.Empty  // Temporary
        };

        context.Comments.Add(comment);
        await context.SaveChangesAsync(ct);

        comment.Path = $"/{comment.Id}/";
        await context.SaveChangesAsync(ct);

        logger.LogInformation("Added root comment {CommentId} with path {Path}", comment.Id, comment.Path);
        return comment;
    }
}

बच्चों की परवरिश कीजिए

माता-पिता के सम्बन्ध में प्रयोग किया जा रहा है (हमने माता-पिता को सुविधा के लिए रखा):

public async Task<List<Comment>> GetChildrenAsync(int commentId, CancellationToken ct = default)
{
    // Option 1: Use ParentCommentId (simple, always works)
    return await context.Comments
        .AsNoTracking()
        .Where(c => c.ParentCommentId == commentId)
        .OrderBy(c => c.CreatedAt)
        .ToListAsync(ct);

    // Option 2: Use path pattern (demonstrates path power)
    // var parentPath = await context.Comments
    //     .Where(c => c.Id == commentId)
    //     .Select(c => c.Path)
    //     .FirstOrDefaultAsync(ct);
    //
    // if (parentPath == null) return new List<Comment>();
    //
    // // Find paths that extend parent by exactly one segment
    // // Parent: /1/3/  Children: /1/3/X/ where X is one number
    // var childPathPattern = $"{parentPath}%";
    //
    // return await context.Comments
    //     .AsNoTracking()
    //     .Where(c => EF.Functions.Like(c.Path, childPathPattern)
    //              && c.Path != parentPath
    //              && c.ParentCommentId == commentId)  // Ensures immediate children only
    //     .ToListAsync(ct);
}

सभी अत्याचारियों को प्राप्त करें

यह वह जगह है जहाँ भौतिक पथ प्रकाश - पथ चमकते हैं, और कोई डाटाबेस तलाश की ज़रूरत नहीं:

public async Task<List<Comment>> GetAncestorsAsync(int commentId, CancellationToken ct = default)
{
    // Step 1: Get the path (single query)
    var path = await context.Comments
        .Where(c => c.Id == commentId)
        .Select(c => c.Path)
        .FirstOrDefaultAsync(ct);

    if (string.IsNullOrEmpty(path))
        return new List<Comment>();

    // Step 2: Parse ancestor IDs from path
    // Path "/1/3/7/" -> split -> ["1", "3", "7"] -> take all but last -> [1, 3]
    var ancestorIds = path
        .Split('/', StringSplitOptions.RemoveEmptyEntries)
        .SkipLast(1)  // Exclude self
        .Select(int.Parse)
        .ToList();

    if (!ancestorIds.Any())
        return new List<Comment>();

    // Step 3: Fetch ancestors (single query, uses primary key index)
    var ancestors = await context.Comments
        .AsNoTracking()
        .Where(c => ancestorIds.Contains(c.Id))
        .ToListAsync(ct);

    // Step 4: Order by position in path (root first)
    return ancestorIds
        .Select(id => ancestors.First(a => a.Id == id))
        .ToList();
}

सभी बच्चों को लाओ

पथ के साथ की तरह इस्तेमाल करें:

public async Task<List<Comment>> GetDescendantsAsync(int commentId, CancellationToken ct = default)
{
    // Get the path first
    var path = await context.Comments
        .Where(c => c.Id == commentId)
        .Select(c => c.Path)
        .FirstOrDefaultAsync(ct);

    if (string.IsNullOrEmpty(path))
        return new List<Comment>();

    // LIKE 'path%' finds all paths that START with this path
    // Path "/1/3/" matches "/1/3/", "/1/3/5/", "/1/3/5/9/", etc.
    // Using EF.Functions.Like for proper SQL generation
    return await context.Comments
        .AsNoTracking()
        .Where(c => EF.Functions.Like(c.Path, $"{path}%") && c.Id != commentId)
        .OrderBy(c => c.Path)  // Gives us depth-first order!
        .ToListAsync(ct);
}

गहराई से बच्चों को प्राप्त करें

हम पथ से गहराई की गणना कर सकते हैं:

public async Task<List<CommentWithDepth>> GetDescendantsWithDepthAsync(
    int commentId,
    int? maxDepth = null,
    CancellationToken ct = default)
{
    var comment = await context.Comments
        .AsNoTracking()
        .FirstOrDefaultAsync(c => c.Id == commentId, ct);

    if (comment == null)
        return new List<CommentWithDepth>();

    var basePath = comment.Path;
    var baseDepth = basePath.Split('/', StringSplitOptions.RemoveEmptyEntries).Length;

    // Get all descendants
    var query = context.Comments
        .AsNoTracking()
        .Where(c => EF.Functions.Like(c.Path, $"{basePath}%") && c.Id != commentId);

    var descendants = await query.ToListAsync(ct);

    // Calculate relative depth and filter if needed
    var result = descendants
        .Select(d =>
        {
            var absoluteDepth = d.Path.Split('/', StringSplitOptions.RemoveEmptyEntries).Length;
            var relativeDepth = absoluteDepth - baseDepth;
            return new CommentWithDepth
            {
                Id = d.Id,
                Content = d.Content,
                Author = d.Author,
                CreatedAt = d.CreatedAt,
                PostId = d.PostId,
                ParentCommentId = d.ParentCommentId,
                Path = d.Path,
                Depth = relativeDepth
            };
        })
        .Where(d => !maxDepth.HasValue || d.Depth <= maxDepth.Value)
        .OrderBy(d => d.Path)
        .ToList();

    return result;
}

public class CommentWithDepth
{
    public int Id { get; set; }
    public string Content { get; set; } = string.Empty;
    public string Author { get; set; } = string.Empty;
    public DateTime CreatedAt { get; set; }
    public int PostId { get; set; }
    public int? ParentCommentId { get; set; }
    public string Path { get; set; } = string.Empty;
    public int Depth { get; set; }
}

उपतरू मिटाएँ

मेल खाने वाले पथ के साथ सरल:

public async Task DeleteSubtreeAsync(int commentId, CancellationToken ct = default)
{
    var path = await context.Comments
        .Where(c => c.Id == commentId)
        .Select(c => c.Path)
        .FirstOrDefaultAsync(ct);

    if (string.IsNullOrEmpty(path))
    {
        throw new InvalidOperationException($"Comment {commentId} not found");
    }

    // Delete all comments whose path starts with this path
    // This includes the comment itself and ALL descendants
    var deleted = await context.Comments
        .Where(c => EF.Functions.Like(c.Path, $"{path}%"))
        .ExecuteDeleteAsync(ct);

    logger.LogInformation("Deleted {Count} comments with path prefix {Path}", deleted, path);
}

उपतरू खिसकाएँ

यह भौतिक पथों के लिए महँगी ऑपरेशन है - हमें सभी वंशज पथों को अद्यतन करना होगा:

public async Task MoveSubtreeAsync(
    int commentId,
    int newParentId,
    CancellationToken ct = default)
{
    await using var transaction = await context.Database.BeginTransactionAsync(ct);

    try
    {
        // Get the node being moved
        var comment = await context.Comments
            .FirstOrDefaultAsync(c => c.Id == commentId, ct);

        if (comment == null)
            throw new InvalidOperationException($"Comment {commentId} not found");

        // Get the new parent
        var newParent = await context.Comments
            .FirstOrDefaultAsync(c => c.Id == newParentId, ct);

        if (newParent == null)
            throw new InvalidOperationException($"New parent {newParentId} not found");

        // Prevent cycles: can't move under own descendant
        if (newParent.Path.StartsWith(comment.Path))
        {
            throw new InvalidOperationException("Cannot move a node under its own descendant");
        }

        var oldPath = comment.Path;
        var newPath = $"{newParent.Path}{comment.Id}/";

        // Get all descendants (including the node itself)
        var descendants = await context.Comments
            .Where(c => EF.Functions.Like(c.Path, $"{oldPath}%"))
            .ToListAsync(ct);

        // Update all paths by replacing the old prefix with the new one
        foreach (var descendant in descendants)
        {
            // Replace old path prefix with new one
            // Old: /1/3/7/  Node 7 moving under /2/
            // Node 7: /1/3/7/ -> /2/7/
            // Node 9 (child of 7): /1/3/7/9/ -> /2/7/9/
            descendant.Path = newPath + descendant.Path.Substring(oldPath.Length);
        }

        // Update the direct parent reference
        comment.ParentCommentId = newParentId;

        await context.SaveChangesAsync(ct);
        await transaction.CommitAsync(ct);

        logger.LogInformation("Moved subtree of {Count} nodes from {OldPath} to {NewPath}",
            descendants.Count, oldPath, newPath);
    }
    catch
    {
        await transaction.RollbackAsync(ct);
        throw;
    }
}

प्रवाहित दृश्य अनुमोदन क्वैरी करें

sequenceDiagram
    participant App as Application
    participant EF as EF Core
    participant DB as PostgreSQL

    Note over App,DB: Getting Ancestors (Path parsing)
    App->>EF: GetAncestorsAsync(commentId)
    EF->>DB: SELECT path FROM comments WHERE id = @id
    DB-->>EF: Path "/1/3/7/"
    Note over App: Parse path → [1, 3]
    EF->>DB: SELECT * FROM comments WHERE id IN (1, 3)
    DB-->>EF: Ancestor comments
    EF-->>App: List<Comment>

    Note over App,DB: Getting Descendants (LIKE query)
    App->>EF: GetDescendantsAsync(commentId)
    EF->>DB: SELECT path FROM comments WHERE id = @id
    DB-->>EF: Path "/1/3/"
    EF->>DB: SELECT * FROM comments WHERE path LIKE '/1/3/%'
    DB-->>EF: All descendants
    EF-->>App: List<Comment>

परफ़ॉर्मेंस कैरेक्टर्स

IMTAN ऑपरेशन GNOME जटिलता डाटाबेस क्वाटरल नोट्स |-----------|------------|------------------|-------| Libisofs प्रविष्ट करेंO( 1) 2BLARENVERE + अद्यतन पथ 0. 6 IMTANTOO( 1) 1 GiB का इस्तेमाल माता - पिता से करता हैComment IMLTANTO( d) 2LLLALP पथ + d पितरों को प्राप्त करें ऑस्कर बी( 1) के पत्ते प्राप्त करें* IMTAL( 0. 7) पथ + तरह का क्वेरी IMDINTHONTICHO( s") CURTCYAND अरबी पथ पथ IMTAN उप ट्रीOPO( 1) को मिटाएँ* IMSUN( 12. 5) पाया पथ + बड़ी मात्रा में मिटाया

*पथ स्तम्भ पर उचित निर्देशिका के साथ

निर्देशिका विचार

पथ निर्देशिका गंभीर है. एसक्यूएल के लिए, प्रयोग के लिए text_pattern_ops, जो कुशल प्रीफ़िक्सों को गैर सी लोकेलों में तोड़ने के रूप में सक्षम करता है:

-- Standard B-tree index (works for LIKE 'prefix%')
CREATE INDEX ix_comments_path ON comments (path);

-- Better for pattern matching in PostgreSQL
CREATE INDEX ix_comments_path_pattern ON comments (path text_pattern_ops);

उत्प्रवासन के द्वारा यह जोड़ें:

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.Sql(
        "CREATE INDEX ix_comments_path_pattern ON comments (path text_pattern_ops)");
}

पथ फ़ॉर्मेट विचार

अलग डेलिमिटर में व्यापार- बन्द है:

आपसी सहयोग (एक्सविद्वीप) |--------|---------|------|------| | /1/3/7/ SMTP यह लेख साफ - साफ बताता है, यूआरएल की तरह, शिर्क करने के लिए आसान जगह का प्रयोग करता है | 1.3.7 INBLLOSL ट्री शैली, lONTP अवधि के साथ काम करता है दशमलव के साथ परस्पर विरोध के साथ | 1,3,7 अतुल्यकालिक कौमा से अलग किए गए सादा अवतरित बाहरी विराम चिह्न को डाटा में बदल सकता हैcolombia. kgm | 001.003.007 IMTATE- चौड़ाई , समान सीमा आईडी सीमा, स्पेस हालत को तबाह करता है

वह /id/ संकेतक तथा ट्रेलिंग स्लैश के साथ प्रारूप क्योंकि सलाह दी जाती है:

  1. रूप में सही काम (संवर्स ठीक से)/1/% मिलान /1/ लेकिन नहीं /10/)
  2. अलग करने के लिए आसान
  3. डिबगिंग के लिए मानव पढ़े जाने योग्य

प्रोक्शन्स और कॉनस्ट्स

आपसी रिश्‍तों में दरार |------|------| अनुमान लगाया जा रहा है (कोई क्वैरी नहीं) सब बच्चों को अद्यतन करने की जरूरत है TARICPath पथ सीमा गहराई गहराई तक पहुँचने वाले बच्चों की तरह सरल बच्चों के लिए स्ट्रिंग का गलत इस्तेमाल किया जा सकता है डिबगिंग के लिए पढ़ा जा सकने योग्य मानव रोटीबली पीढ़ी के लिए अच्छा पथ एसआईडीएलएस के साथ सिंक में रखा जाना चाहिएComment INV एकल स्तंभ जोड़ता हैण्डा के लिए मानक बी- ट्री का प्रयोग नहीं कर सकता

वस्तुओं का उपयोग करने के लिए पथ

जबः

  • रोटी - कपड़ा एक आम माँग है
  • कई बार बच्चों से पूछताछ की जाती है
  • ट्री गहराई बाध्य किया गया है (आप 100+ स्तर के पेड़ नहीं होंगे)
  • उप- वृक्ष को खिसकाना विरल है
  • आप डिबगिंग के लिए मानवीय पढ़ने योग्य पदक्रम डाटा चाहते हैं

जब आप भौतिक पथ से दूर रहें:

  • आप अकसर उप- वृक्ष को खिसकाते हैं (सभी पथ महँगे होते हैं)
  • पेड़ बहुत गहरे हो सकते हैं (path वाक्यांशों सेले हो सकते हैं)
  • आप कुशल प्रत्यय मिलान की आवश्यकता है (सभी पेड़ों को एक नमूने में समाप्त करते हुए)
  • आप एल ट्री के साथ अधिक आराम कर रहे हैं (कार्यविग्नित लेकिन अधिक डेम्पमित)

एल ट्री से तुलना करें

आप किस्‌ पर हैं, विचार करें पार्ट 1. 5: l ट्री बदले में. lवां अनिवार्य रूप से एक डाटाबेस-non, के साथ विकृत भौतिक पथ है:

  • काम करने के लिए गीटी इंडेक्स समर्थन
  • अंतर्निर्मित ऑपरेटर्स (इन्स)@>, <@, ~हा॰ मीम॰
  • फंक्शन का पथ
  • स्केल्स के साथ मेल खाता पैटर्न

व्यापार बन्द है एसक्यूएल लॉक. टीप लें कि Nepgl प्रदाता अब एलईईईएस अनुवाद समर्थित करता है के बारे में ' दरख्त' का नाम LTree रिकर्सिव सीईएसएएस अभी भी रॉ एसक्यूएल की आवश्यकता है.

श्रेणी नेविगेशन

logo

© 2026 Scott Galloway — Unlicense — All content and source code on this site is free to use, copy, modify, and sell.