自动映射时可以展平对象的一部分

时间:2018-07-06 12:48:03

标签: c# elasticsearch nest

我对使用Elasticsearch并不陌生,我正在对服务进行搜索,在服务中,我得到的部分结果的格式如下(从其他语言翻译过来的名称):

accounting: {
    properties: {
        accountingInterval: {
            properties: {
                endDate: {
                    type: "date",
                    format: "dateOptionalTime"
                },
                startDate: {
                    type: "date",
                    format: "dateOptionalTime"
                }
            }
        }
    }
}

我可以像这样自动将其映射到对象上

class MyBaseObject
{
    public Accounting Accounting { get; set; }
    //...some other values on base object
}

class Accounting
{
    public AccountingInterval AccountingInterval { get; set; }
}

class AccountingInterval
{
    [Date(Format = "dateOptionalTime")]
    public DateTime? StartDate { get; set; }
    [Date(Format = "dateOptionalTime")]
    public DateTime? EndDate { get; set; }
}

是否有一种方法可以将其映射到像这样的简单对象:

class MyBaseObject
{
    [Date(Format = "dateOptionalTime")]
    public DateTime? AccountingStartDate { get; set; }
    [Date(Format = "dateOptionalTime")]
    public DateTime? AccountingEndDate { get; set; }
    //...some other values on base object
}

我尝试设置name属性,但似乎不起作用

class MyBaseObject
{
    [Date(Name ="accounting.accountingInterval.startDate", Format = "dateOptionalTime")]
    public DateTime? AccountingStartDate { get; set; }
    [Date(Name ="accounting.accountingInterval.endDate", Format = "dateOptionalTime")]
    public DateTime? AccountingEndDate { get; set; }
    //...some other values on base object
}

1 个答案:

答案 0 :(得分:1)

正如panchicore在评论中说的那样,有可能在索引时使用Ingest node and pipelines进行这种扁平化,并且索引中的类型映射将反映这种结构。

如果您不负责索引编制,那么这样做会比较棘手。 NEST中的映射用于Elasticsearch的文档输入和输出。通过连接Nest.JsonSerializer nuget packageusing Json.NET as the serializer for the client,并为MyBaseObject定义自定义JsonConverter,可以控制如何将JSON反序列化为MyBaseObject类型。但是,如果您只想为字体美化做这件事,那么付出的努力可能不仅仅是价值!