2017-01-12 117 views
0

我使用Elastisearch.NET和NEST 2.3。我想使用属性映射,但我只想索引某些属性。据我了解,除非你忽略它们,例如[String(Ignore = true)],所有的属性都被编入索引。默认情况下可以忽略所有属性,只索引那些附加了nest属性的属性?像JSON.NETs MemberSerialization.OptInElastisearch.net属性选择?

回答

0

您可以使用自定义序列化程序来执行此操作,以忽略未标记为NEST ElasticsearchPropertyAttributeBase派生属性的任何属性。

void Main() 
{ 
    var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200")); 
    var connectionSettings = new ConnectionSettings(
     pool, 
     new HttpConnection(), 
     new SerializerFactory(s => new CustomSerializer(s))); 

    var client = new ElasticClient(connectionSettings); 

    client.CreateIndex("demo", c => c 
     .Mappings(m => m 
      .Map<Document>(mm => mm 
       .AutoMap() 
      ) 
     ) 
    ); 
} 

public class Document 
{ 
    [String] 
    public string Field1 { get; set;} 

    public string Field2 { get; set; } 

    [Number(NumberType.Integer)] 
    public int Field3 { get; set; } 

    public int Field4 { get; set; } 
} 

public class CustomSerializer : JsonNetSerializer 
{ 
    public CustomSerializer(IConnectionSettingsValues settings, Action<JsonSerializerSettings, IConnectionSettingsValues> settingsModifier) : base(settings, settingsModifier) { } 

    public CustomSerializer(IConnectionSettingsValues settings) : base(settings) { } 

    public override IPropertyMapping CreatePropertyMapping(MemberInfo memberInfo) 
    { 
     // if cached before, return it 
     IPropertyMapping mapping; 
     if (Properties.TryGetValue(memberInfo.GetHashCode(), out mapping)) 
      return mapping; 

     // let the base method handle any types from NEST 
     // or Elasticsearch.Net 
     if (memberInfo.DeclaringType.FullName.StartsWith("Nest.") || 
      memberInfo.DeclaringType.FullName.StartsWith("Elasticsearch.Net.")) 
      return base.CreatePropertyMapping(memberInfo); 

     // Determine if the member has an attribute 
     var attributes = memberInfo.GetCustomAttributes(true); 
     if (attributes == null || !attributes.Any(a => typeof(ElasticsearchPropertyAttributeBase).IsAssignableFrom(a.GetType()))) 
     { 
      // set an ignore mapping 
      mapping = new PropertyMapping { Ignore = true }; 
      Properties.TryAdd(memberInfo.GetHashCode(), mapping); 
      return mapping; 
     } 

     // Let base method handle remaining 
     return base.CreatePropertyMapping(memberInfo); 
    } 
} 

产生以下请求

PUT http://localhost:9200/demo?pretty=true 
{ 
    "mappings": { 
    "document": { 
     "properties": { 
     "field1": { 
      "type": "string" 
     }, 
     "field3": { 
      "type": "integer" 
     } 
     } 
    } 
    } 
}