如何避免在提交对象时扩展映射

How to avoid to extend the mapping on commiting an object

让我们假设以下 class 我想索引:

private class User
{
    public User()
    {
        Id = Guid.NewGuid();
        Added = DateTime.Now;
    }

    public Guid Id { get; protected set; }
    public string LastName { get; set; }
    public DateTime Added { get; protected set; } // Unimportant for search
}

关键是我只需要索引中的 IdLastName 属性。使用流畅的 api 一切正常(只映射指定的属性):

_client.Map<User>(m => m.
    Index("nest_test").
    Properties(p => p.String(s => s.Name(u => u.LastName))));

现在,当我为一个对象建立索引时,映射将通过剩余的属性进行扩展。我怎样才能避免这些行为。 (对我来说也很奇怪:MapFromAttributes() 映射了所有属性,而 属性 甚至没有一个被装饰?!)。

这是一个非常小的例子,但我的一些域对象处于多对多关系中。我没有尝试过,但我认为在提交所有内容时不可能映射这些对象。

https://github.com/elastic/elasticsearch-net/issues/1278 中的答案复制:

这是由于 ES 在检测新字段时的 dynamic mapping 行为。您可以通过在映射中设置 dynamic: falseignore 来关闭此行为:

client.Map<Foo>(m => m
    .Dynamic(DynamicMappingOption.Ignore)
    ...
);

client.Map<Foo>(m => m
    .Dynamic(false)
    ...
);

不过请记住,属性 仍会出现在 _source 中。

或者,您可以使用上面提到的 fluent ignore 属性 API,这将从映射中完全排除 属性 和 _source,因为这样做会导致它不进行序列化:

var settings = new ConnectionSettings()
    .MapPropertiesFor<Foo>(m => m
        .Ignore(v => v.Bar)
);

var client = new ElasticClient(settings);

或不太理想,只需将 Json.NET 的 [JsonIgnore] 属性粘贴到要排除的属性上即可。