通用弹性搜索方法 c#
Generic Elastic Search Method c#
我正在使用 Nest。
https://www.nuget.org/packages/NEST/6.1.0
我有以下代码:
public class foo
{
public Guid id { get; set; }
}
public class foo2
{
public Guid id { get; set; }
}
public IReadOnlyCollection<T> GetDocumentAsync<T>(Guid id) where T: class
{
var searchResponse = _client.Search<T>(s => s
.Query(q => q
.Match(m => m
.Field(f => f.id) //f.id is not a property of T
.Query(id.ToString())
)
)
);
return searchResponse.Documents;
}
问:如何将字段作为Id传入?我知道我可以创建一个界面,但是我无权访问 类。还有其他映射方式吗?
T
是通用的,如果你想使用特定的属性,你需要使用 non-generic 方法或添加一个约束,给你 Id
属性 .例如,有一个这样的界面:
public interface IHasId
{
Guid id { get; }
}
这让您的模型看起来像这样:
public class foo : IHasId
{
public Guid id { get; set; }
}
public class foo2 : IHasId
{
public Guid id { get; set; }
}
现在您的方法将具有更新的约束:
public IReadOnlyCollection<T> GetDocumentAsync<T>(Guid id)
where T : class, IHasId // <--- Add this
{
// Snip
}
我正在使用 Nest。
https://www.nuget.org/packages/NEST/6.1.0
我有以下代码:
public class foo
{
public Guid id { get; set; }
}
public class foo2
{
public Guid id { get; set; }
}
public IReadOnlyCollection<T> GetDocumentAsync<T>(Guid id) where T: class
{
var searchResponse = _client.Search<T>(s => s
.Query(q => q
.Match(m => m
.Field(f => f.id) //f.id is not a property of T
.Query(id.ToString())
)
)
);
return searchResponse.Documents;
}
问:如何将字段作为Id传入?我知道我可以创建一个界面,但是我无权访问 类。还有其他映射方式吗?
T
是通用的,如果你想使用特定的属性,你需要使用 non-generic 方法或添加一个约束,给你 Id
属性 .例如,有一个这样的界面:
public interface IHasId
{
Guid id { get; }
}
这让您的模型看起来像这样:
public class foo : IHasId
{
public Guid id { get; set; }
}
public class foo2 : IHasId
{
public Guid id { get; set; }
}
现在您的方法将具有更新的约束:
public IReadOnlyCollection<T> GetDocumentAsync<T>(Guid id)
where T : class, IHasId // <--- Add this
{
// Snip
}