从索引中排除属性

本文关键字:属性 排除 索引 | 更新日期: 2023-09-27 17:58:27

我已经创建了下面的对象,该对象将映射到ElasticSearch类型。我想将UnivId属性排除在索引之外:

[ElasticType(Name = "Type1")]
public class Type1
{
    // To be ignored
    public string UnivId { get; set; }
    [ElasticProperty(Name="Id")]
    public int Id { get; set; }
    [ElasticProperty(Name = "descSearch")]
    public string descSearch { get; set; }
}

从索引中排除属性

您应该能够设置ElasticProperty属性的OptOut值,如下所示:

 [ElasticProperty(OptOut = true)]
 public string UnivId { get; set; }

在NEST 2.0中,ElasticPropertyAttribute被每个类型的属性(StringAttribute,DateAttribute…)所取代。我使用Ignore参数来排除属性。

字符串示例:

[String(Ignore = true)]
public string Id {get;set;}

如果使用Nest 5.0+,根据文档有几种方法可以忽略字段:


Ignore属性应起作用:

using Nest;
[Ignore]
public string UnivId { get; set; }

也可以使用JsonIgnore,因为Newtonsoft.Json是Nest使用的默认序列化程序。


另一种方法是使用与属性相关联的特定于类型的属性映射。例如,由于它是string,则使用Text属性:

[Text(Ignore = true)]
public string UnivId { get; set; }

或者如果int使用Number:

[Number(Ignore = true)]
public int Id { get; set; }

此外,可以在ConnectionSettings上使用.DefaultMappingFor<...忽略映射,而不是在属性上使用显式属性(有关更多详细信息,请参阅文档)

var connectionSettings = new ConnectionSettings()
    .DefaultMappingFor<Type1>(m => m.Ignore(p => p.UnivId);

但是,如果想要有条件地忽略一个属性(如果值为null),则使用以下具有null处理设置的Newtonsoft.Json属性:

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string UnivId { get; set; }

当我对文档进行部分更新时,我发现上面的内容很有用,但我希望重用相同的C#类进行索引,并避免覆盖索引中的现有值。