无需手动指定所有属性即可调用SourceInclude

时间:2016-01-18 10:24:09

标签: c# elasticsearch nest

我正在使用NEST 1.7来查询Elasticsearch。我在SourceInclude操作上使用Get,因为我只需要部分源代码。我有一个DTO类来表示我想从Elasticsearch返回的属性。但是,我需要手动指定SourceInclude方法的所有属性参数。

这是我正在做的最小的责备:

[ElasticType(Name = "productDoc")]
public class Product
{
    [ElasticProperty(Name = "doc_id")]
    public string Id { get; set; }

    [ElasticProperty(Name = "fullname")]
    public string Name { get; set; }

    [ElasticProperty(Name = "desc")]
    public string Description { get; set; }

    // Et cetera...
}

public class SearchRepo
{
    public Product RetrieveProduct(string id)
    {
        IElasticClient client = new ElasticClient();

        var getResponse = client.Get<Product>(p => p
            .Id(id)
            .SourceInclude(
                i => i.Id,
                i => i.Name,
                i => i.Description
                // Et cetera...
            )
        );

        return getResponse.Source;
    }
}

如果dto上有许多属性,则会出现劳动密集型且容易出错的情况。 我想以某种方式指定只有​​我的DTO类的属性包含在源代码中。

我试图完全忽略SourceInclude调用,希望NEST能够从泛型类型参数到Get推断出它需要什么,但是在调试器中检查Elasticsearch请求似乎告诉我整个文件已被检索。

是否有标准NEST功能的中间立场?或者我是否需要使用自己的方法来动态列出所有dto属性?

PS。我asked a similar question (/ feature request) on Github

1 个答案:

答案 0 :(得分:1)

不,您需要处理生成字段名称列表以自行检索。如果您未提及SourceInclude,则会检索整个_source。这就是Elasticsearch的行为。不过,如果字段名称匹配,Nest将能够在响应中创建Product对象。

相关问题