Skip to content

Table splitting and generated columns (specifically full text search) #26423

Closed as not planned

Description

@benstevens48

Ask a question

I have decided to use table splitting to split my Product model into two classes - Product and ProductExtraDetail, because the latter contains a long description field that I don't usually want to return in queries. However, I would like to add a generated NpgsqlTsVector column for a full text search on the product. This contains fields from both the main Product itself, such as display name, and fields from the ProductExtraDetail such as description. I don't really want to repeat the fields from Product in the definition of ProductExtraDetail. I'm wondering what the best way to achieve this is. Is it allowed to reference a navigation property in the fields for the HasGeneratedTsVectorColumn function? For example can I do something like this?

namespace PictureflectLicenseServer.DbModels {
    [Table("Products")]
    public class Product {
        [Key]
        [Column("Id")]
        public Guid Id { get; set; }
        [Required]
        [Column("DisplayName")]
        public string DisplayName { get; set; }

        public ProductExtraDetail ExtraDetail { get; set; }
    }

    [Table("Products")]
    public class ProductExtraDetail {
        [Key]
        [Column("Id")]
        public Guid Id { get; set; }
        [Column("Description")]
        public string Description { get; set; }
     
        [Column("FullSearchVector")]
        public NpgsqlTsVector FullSearchVector { get; set; } //A generated column for text search

        public Product Parent { get; set; }
    }

    public class ProductEntityTypeConfiguration : IEntityTypeConfiguration<Product> {
        public void Configure(EntityTypeBuilder<Product> builder) {
            builder.HasOne(item => item.ExtraDetail).WithOne(item => item.Parent).HasForeignKey<ProductExtraDetail>(item => item.Id);
        }
    }

    public class ProductExtraDetailEntityTypeConfiguration : IEntityTypeConfiguration<ProductExtraDetail> {
        public void Configure(EntityTypeBuilder<ProductExtraDetail> builder) {
            builder.HasGeneratedTsVectorColumn(item => item.FullSearchVector, "english", item => new { item.Parent.DisplayName, item.Description }).HasIndex(item => item.FullSearchVector).HasMethod("GIN");
        }
    }
}

Note the reference to Parent.DisplayName in the last line - is that valid?

If not, can I use shadow properties somehow? Or do I just have to repeat the DisplayName property in ProductExtraDetail? Also, in the case of repeating the property, I'm not quite sure how that works when updating. Do I have to update the property in both places?

Activity

  1. roji commented on Oct 21, 2021

    @roji
    Member

    @benstevens48 at the end of the day, your columns do co-inhabit the same table, so there's no problem with the generated column referencing the other column, even if in the EF Core model they're on different entity types. I'm not quite sure whether this would work with HasGeneratedTsVectorColumn - what are you seeing with the code above? But even if there's an issue, note that HasGeneratedVectorColumn is just sugar over specifying the computed column SQL; you can always just do that your self with HasComputedColumnSql.

  2. benstevens48 commented on Oct 21, 2021

    @benstevens48
    Author

    @roji - actually, no the above code doesn't work. I get the error

    The expression 'item => new <>f__AnonymousType0`2(DisplayName = item.Parent.DisplayName, Description = item.Description)' is not a valid member access expression. The expression should represent a simple property or field access: 't => t.MyProperty'. When specifying multiple properties or fields, use an anonymous type: 't => new { t.MyProperty, t.MyField }'. (Parameter 'propertyAccessExpression')
    

    Instead, I am following your suggestion and doing

            public void Configure(EntityTypeBuilder<ProductExtraDetailDbItem> builder) {
                builder.Property(item => item.FullSearchVector).HasComputedColumnSql("to_tsvector('english', coalesce(\"DisplayName\", '') || ' ' || coalesce(\"Description\", ''))", true);
                builder.HasIndex(item => item.FullSearchVector).HasMethod("GIN");
            }

    Does that look right?

    Is there any chance that the code which references the Parent navigation property, i.e.

    builder.HasGeneratedTsVectorColumn(item => item.FullSearchVector, "english", item => new { item.Parent.DisplayName, item.Description }).HasIndex(item => item.FullSearchVector).HasMethod("GIN");

    could be supported at some point? I like to avoid manually writing SQL and hard-coding the column names if possible. I imagine that this could be quite a common scenario for table splitting. Or perhaps just add a variant of the function that accepts the column names as strings instead of a LINQ expression? (PS part of the reason I'm using table splitting is due to the lack of a good solution to #1387, so enabling that would also solve the problem for me).

  3. roji commented on Oct 21, 2021

    @roji
    Member

    Is there any chance that the code which references the Parent navigation property [...] could be supported at some point?

    It's possible, but I doubt I'll have time any time soon to work on it, given that nobody's complained so far and there's a solid workaround with HasComputedColumnSql... But you can definitely open an issue on https://github.com/npgsql/efcore.pg.

    Or perhaps just add a variant of the function that accepts the column names as strings instead of a LINQ expression?

    At that point there really is no value over just using HasComputedColumnSql, no? You'd be hard-coding the names either way?

    PS part of the reason I'm using table splitting is due to the lack of a good solution to #1387, so enabling that would also solve the problem for me

    If partial loading is why you're using table splitting, then keep in mind that you can always project out whatever you want with Select, including the original entity type:

    var blogs = ctx.Blogs.Select(b => new Blog { /* populate whatever entities you want*/ }.ToList();

    While this allows you to partially load blogs, it doesn't track them so cannot be used for later automatically-tracked updates.

  4. benstevens48 commented on Oct 22, 2021

    @benstevens48
    Author

    @roji - before I forget, I think I encountered a migration bug. I made the above change to the FullSearchVector column. Then I generated a migration, which created code to drop and re-add the FullSearchVector column. However, it did not re-create the index on this column. Neither did it drop the index, but obviously the index was dropped automatically when the column was dropped. Should I report this as a migrations bug? I guess that the migration code should probably drop the index before dropping the column then re-add it after re-adding the column.

    But you can definitely open an issue on https://github.com/npgsql/efcore.pg.

    Will do at some point.

    At that point there really is no value over just using HasComputedColumnSql, no? You'd be hard-coding the names either way?

    Yeah I guess so. I wrote my own helper function for this. It's just if I have a helper function that I know I'm going to need in every project, I can't help thinking that either it should be built-in or I'm doing something wrong!

    keep in mind that you can always project out whatever you want with Select

    Yeah, I know this, but my Product model above is nested 1-3 levels deep in several other model classes. It's possible to reuse partial selection code reasonably easily for top level items, but for navigation properties it's pretty difficult/impossible I think. Having to write out all the properties each time became unmanageable, hence the move to table-splitting, which seems to provide a better, if not 100% satisfactory, solution.

  5. roji commented on Oct 22, 2021

    @roji
    Member

    before I forget, I think I encountered a migration bug [...]

    Yeah, can you please open an issue for that with the full details and repro steps?

  6. skyZcoding commented on Aug 24, 2022

    @skyZcoding

    @benstevens48 Hi Ben
    I'm running into the same issue.

    Yeah I guess so. I wrote my own helper function for this. It's just if I have a helper function that I know I'm going to need in every project, I can't help thinking that either it should be built-in or I'm doing something wrong!

    How did you got it fix with your helper function? Could you share it with me?

  7. benstevens48 commented on Aug 24, 2022

    @benstevens48
    Author

    @skyZcoding I have a very simple helper function like this

        public static class SqlHelpers {
            //Can throw error if argument is null or empty. May be database-specific (although all ought to support double quotes with the right settings).
            public static string GetIdentifierSql(string name) {
                if (string.IsNullOrEmpty(name)) {
                    throw new ArgumentException("The name must not be null or empty.");
                }
                return "\"" + name.Replace("\"", "") + "\"";
            }
    
            //PostgreSQL-specific. The columns must be text columns (which can be nullable). In general, config should be "english".
            public static string GetTsVectorComputedColumnSql(string config, IEnumerable<string> columns) {
                var filteredColumns = columns?.Where(item => !string.IsNullOrEmpty(item));
                if(filteredColumns == null || !filteredColumns.Any()) {
                    return "";
                }
                return "to_tsvector('" + config.Replace("\'", "") + "', " + string.Join(" || ' ' || ", filteredColumns.Select(item => "coalesce(" + GetIdentifierSql(item) + ", '')")) + ")";
            }
        }

    and I use it like this

    public class ProductExtraDetailEntityTypeConfiguration : IEntityTypeConfiguration<ProductExtraDetailDbItem> {
            public void Configure(EntityTypeBuilder<ProductExtraDetailDbItem> builder) {
                builder.Property(item => item.FullSearchVector).HasComputedColumnSql(SqlHelpers.GetTsVectorComputedColumnSql("english", new string[] { "Code", "FeatureCode", "DisplayName", "Description" }), true); //We have to manually specify the generated SQL since we are using columns spanning the split table.
                builder.HasIndex(item => item.FullSearchVector).HasMethod("GIN");
            }
        }

    (instead of something like this without table splitting)

        public class ProductEntityTypeConfiguration : IEntityTypeConfiguration<ProductDbItem> {
            public void Configure(EntityTypeBuilder<ProductDbItem> builder) {
                builder.HasGeneratedTsVectorColumn(item => item.FullSearchVector, "english", item => new { item.Code, item.FeatureCode, item.DisplayName, item.Description }).HasIndex(item => item.FullSearchVector).HasMethod("GIN");
            }
        }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions