首页 > 解决方案 > 自动映射时是否可以展平对象的某些部分

问题描述

我是使用 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
}

我尝试设置名称属性,但它似乎没有工作

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
}

标签: c#elasticsearchnest

解决方案


正如 panchicore 在评论中所说,可以在索引时使用Ingest node 和 pipelines执行这种扁平化,并且索引中的类型映射将反映这种结构。

如果您不负责索引,那么这将比较棘手。NEST 中的映射用于 Elasticsearch 文档的输入和输出。可以MyBaseObject通过连接Nest.JsonSerializernuget 包使用 Json.NET 作为客户端的序列化程序JsonConverter并为该类型定义自定义来控制 JSON 的反序列化方式MyBaseObject。但是,如果您只是为了字体美学而这样做,那么努力可能会超过价值!


推荐阅读