Postgresql 和 .Net Core 2.1 中的全文搜索问题

gre*_*g87 3 full-text-search npgsql .net-core

我发布这个问题是因为我还没有发现类似的问题。我试图确保 .net core 应用程序中的全文搜索,根据npgsql文档,我有:1)模型

 public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
        public long License { get; set; }
        public NpgsqlTsVector SearchVector { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

2)数据库上下文:

  modelBuilder.Entity<User>()
       .HasIndex(p => p.SearchVector)
       .ForNpgsqlHasMethod("GIN");
Run Code Online (Sandbox Code Playgroud)

3)迁移:

 migrationBuilder.Sql(
            @"CREATE TRIGGER user_search_vector_update BEFORE INSERT OR UPDATE 
            ON ""Users"" FOR EACH ROW EXECUTE PROCEDURE
            ts`enter code here`vector_update_trigger(""SearchVector"", 'pg_catalog.english', ""Name"", ""Surname"");");
Run Code Online (Sandbox Code Playgroud)

现在,我尝试在我的应用程序中使用 FTS,其中方法搜索从标头“phase”(字符串)获取。

[HttpGet]
    public async Task<IActionResult> Search([FromHeader] string phase)
    {
        NpgsqlTsQuery tsVestor = EF.Functions.ToTsQuery("english", phase);
        var response = Ok(_context.Users.Where(c => c.SearchVector.Matches(phase)).ToList());
        return response;
    }
Run Code Online (Sandbox Code Playgroud)

我有:

NotSupportedException:不支持指定的方法。NpgsqlFullTextSearchDbFunctionsExtensions.cs 中的 Microsoft.EntityFrameworkCore.NpgsqlFullTextSearchDbFunctionsExtensions.ToTsQuery(DbFunctions _,字符串配置,字符串查询)

我还尝试通过标题词法和注释行发送:

NpgsqlTsQuery tsVestor = EF.Functions.ToTsQuery("english", phase);
Run Code Online (Sandbox Code Playgroud)

但我得到: PostgresException:42883:运算符不存在:tsvector @@ text

有谁知道我做错了什么?

编辑 - - :

好的,我找到了我的问题的答案。从字符串转换为 NpgsqlTsQuery 必须在 Matches 方法内:

 public async Task<IActionResult> SearchUsers([FromHeader] string phase)
    {
        return Ok(_context.Users.Where(c => c.SearchVector.Matches(EF.Functions.ToTsQuery(phase))));
    }
Run Code Online (Sandbox Code Playgroud)

将此转换放在 Matches 方法之外会引发“NotSupportedException”,并将纯文本作为函数参数会引发 42883 异常。

现在,很明显我做错了什么。

gre*_*g87 5

正如 @sonofaforester 所建议的,我对自己的问题给出了答案:

从字符串转换为 NpgsqlTsQuery 必须在 Matches 方法内:

public async Task<IActionResult> SearchUsers([FromHeader] string phase)
{
    return Ok(_context.Users.Where(c => c.SearchVector.Matches(EF.Functions.ToTsQuery(phase))));
}
Run Code Online (Sandbox Code Playgroud)

将此对话放在 Matches 方法之外会引发“NotSupportedException”,并将纯文本作为函数参数会引发 42883 异常。