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

Is is possible to flatten parts of object when auto mapping

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

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

如果您不负责编制索引,那么这就比较棘手了。 NEST 中的映射用于 Elasticsearch 文档的输入和输出。可以通过连接 Nest.JsonSerializer nuget package, and using Json.NET as the serializer for the client 并为 MyBaseObject 类型定义自定义 JsonConverter 来控制 JSON 反序列化为 MyBaseObject 的方式。不过,如果您只是为了字体美观而这样做,那么付出的努力可能超过其价值!