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

时间:2018-07-24 13:14:06

标签: .net-core full-text-search npgsql

我发布此问题是因为我尚未发现类似问题。我正在尝试确保.net核心应用程序中的全文搜索,并且根据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; }
    }

2)DatabaseContext:

  modelBuilder.Entity<User>()
       .HasIndex(p => p.SearchVector)
       .ForNpgsqlHasMethod("GIN");

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"");");

现在,我正在尝试在应用中使用FTS,其中Search方法从标头“ 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;
    }

我知道了

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

我也尝试通过标题lexeme和注释行发送:

NpgsqlTsQuery tsVestor = EF.Functions.ToTsQuery("english", phase);

但是我得到:PostgresException:42883:运算符不存在:tsvector @@文本

有人知道我在做什么错吗?

编辑----:

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

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

将此转换置于Matches方法外部会引发“ NotSupportedException”,并将纯文本作为函数参数引发42883 Exeception。

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

1 个答案:

答案 0 :(得分:1)

正如@sonofaforester建议的那样,我对自己的问题回答:

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

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

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