使用 NEST2 将类型分配给特定索引

Assign types to a specific index using NEST2

我希望能够使用 NEST2 客户端设置某种映射,以便将不同类型自动放入定义的索引中。这可能吗?

我试过像这样映射类型:

client.Map<A>(m => m.Index("index1"));
client.Map<B>(m => m.Index("index2"));

然后像这样索引它们:

client.Index(new SomethingThatGoesToTheDefaultIndex());
client.Index(new A());//Should end up in index1
client.Index(new B());//Should end up in index2

但是一切都以默认索引而不是设置索引结束。每次存储数据时是否都需要给出所需的索引,或者是否可以为每种类型设置一个定义的索引?

您可以在 .Index(..) 方法的第二个参数的帮助下传递索引名称。

就像这样:

client.Index(new A(), descriptor => descriptor.Index("index1"));
client.Index(new B(), descriptor => descriptor.Index("index2"));

更新

MapDefaultTypeIndices 将帮助您指定类型的默认索引名称。

var settings = new ConnectionSettings() 
    .MapDefaultTypeIndices(dictionary =>
    {
        dictionary.Add(typeof (A), "index1");
        dictionary.Add(typeof (B), "index2");
    });

var client = new ElasticClient(settings);

希望对您有所帮助。