【问题标题】:How to tell Nest ElasticSearch to only use InterfaceProperties如何告诉 Nest ElasticSearch 只使用 InterfaceProperties
【发布时间】:2015-03-27 20:00:31
【问题描述】:

我们正在研究 ElasticSearch (Nest),但遇到了问题。 在我们的应用程序中,我们只想为我们的对象使用接口。在这些接口中,我希望能够设置要索引的属性和不索引的属性。

public interface ISomething {
    string Name {get;set;}
    int Id {get;set;}
}

public class Something: ISomething {
  public string Name { get;set; }
  public int Id {get;set;}
  // This property should not be visible
  public string VerySecretCode {get;set}
}

当我们通过创建一个新的 ElasticClient() 来索引一个接口时,该对象的所有属性都被放入 json 中。是否可以告诉 ElasticClient 我们只希望显示接口公开的属性?

希望任何人都可以提供帮助。

【问题讨论】:

    标签: c# interface elasticsearch nest


    【解决方案1】:

    将数据模型与域模型分开是一种最佳做法。我建议您创建一个新的类/接口 ISomethingForES。然后,您可以使用 Automapper 或类似的东西为您映射字段。优点是您可以使用不属于您的域模型的 ES 特定属性来注释 SomethingForES。这是一个例子:

    [ElasticType(Name = "type123")]
    public class SomethingForES: ISomethingForES {
      public string Name { get;set; }
      public int Id {get;set;}
    }
    

    【讨论】:

      【解决方案2】:

      我们最终在设置中添加了一个自己的转换器: 公共类 MyConverter : ElasticContractResolver {

          public MyConverter(IConnectionSettingsValues connectionSettings)
              : base(connectionSettings)
          {
          }
      
          protected override JsonContract CreateContract(Type objectType)
          {
              if (objectType.Assembly.FullName.Contains("MyDefinition") && objectType.IsInterface)
              {
                  var name = objectType.Name;
                  //Check if name starts with an 'I' and the second char is a UpperCase aswell to be sure the given Type.Name is a interface.
                  if (name.StartsWith("I") && char.IsUpper(name[1]))
                  {
                      //Remove the I from the name
                      name = name.Substring(1);
                      Assembly assembly = Assembly.Load(<MyAssembly>);
                      Type t = assembly.GetType("MyNamespace" + name);
                      if (t != null)
                      {
                          objectType = t;
                      }
      
                  }
              }
      
              var baseReturn = base.CreateContract(objectType);
              return baseReturn;
          }
      
      }
      

      之后创建我们自己的对象,而不是尝试实例化接口。

      【讨论】:

        猜你喜欢
        • 2015-09-07
        • 1970-01-01
        • 2018-07-26
        • 1970-01-01
        • 2022-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多