【问题标题】:Elasticsearch mapping DTO after source filtering in .NET在 .NET 中进行源过滤后的 Elasticsearch 映射 DTO
【发布时间】:2021-02-10 18:41:25
【问题描述】:

我有一个 POCO FooIndex 映射到 elasticsearch 中的索引,我想对该索引执行查询并仅返回特定字段。我创建了一个 DTO FooStatus,它只包含我要返回的字段的属性。

如果 DTO 中的属性名称与索引映射中的名称匹配,这可以正常工作,正如预期的那样,但我希望某些属性具有不同的名称并将它们映射到索引字段。我该怎么做?

var searchDescriptor = new SearchDescriptor<FooIndex>()
                       .Index(index)
                       .Source(sf => sf
                                   .Includes(i => i
                                                 .Fields(
                                                     f => f.FooId,
                                                     f => f.FirstName,
                                                     f => f.LastName,
                                                     f => f.PrimaryEmail,
                                                     f => f.UpdatedDate,
                                                     f => f.Statuses)))
                       .Query(q => q
                                  .Bool(b => b
                                            .Filter(f => f
                                                        .Terms(t => t
                                                                    .Field(p => p.Statuses.Select(
                                                                               x => x.blahId))
                                                                    .Terms(reqIds)))));
var results = await _elasticClient.SearchAsync<FooStatus>(searchDescriptor);
return results.Documents;


public class FooStatus
{
    public string FooId { get; set; }
    public string FirstName {get; set;}
    public string LastName {get; set; }
    public string Email {get; set;}              // Map this from FooIndex.PrimaryEmail
    public DateTime? DateModified {get; set; }  // Map this from FooIndex.UpdatedDate
    public List<FooStatus> Statuses { get; set; }
}

【问题讨论】:

    标签: c# .net elasticsearch nest


    【解决方案1】:

    我想为某些属性设置不同的名称并将它们映射到索引字段。我该怎么做?

    如果您要映射的属性在对象图中的深度相同,则可以使用DataMemberAttributePropertyNameAttribute 将字段映射到 POCO 上不同名称的属性。

    如果属性的深度不同,这不是使用内置序列化程序可以轻松完成的事情。您可以拥有应用了序列化程序将 JSON 字段反序列化到的属性的私有成员,以及具有所需名称的公共属性。要反序列化的对象图的整体形状需要与FooIndex 相同,但是例如映射FooIndex.Bar.Baz 需要FooStatus 的对象图深度为三层才能映射Baz

    要使用 JSON.NET 和 System.Text.Json 等其他序列化程序来完成此操作,需要编写自定义 JsonConverter,依次读取每个属性并分配值。这是一项相当大的工作量,并且需要随时重新访问FooStatus' 的属性需要更改。

    【讨论】:

      猜你喜欢
      • 2014-07-23
      • 1970-01-01
      • 2016-04-13
      • 1970-01-01
      • 2014-04-06
      • 1970-01-01
      • 1970-01-01
      • 2014-10-02
      • 2019-04-17
      相关资源
      最近更新 更多