Elasticsearch.Nest 教程系列 9-1 转换:Index name inference | 索引名推断的3种方式


NEST 提供了多种方式来推断索引名,不同方式可以同时指定,但相互之间存在优先级关系,具体如下:

示例

配置类:

public class ElasticSearchSettings
{
    public string ServerUri { get; set; }
    public string DefaultIndex { get; set; } = "defaultindex";
}

配置:

public ElasticSearchClient(ElasticSearchSettings esSettings)
{
    _esSettings = esSettings;
    var settings = new ConnectionSettings(new Uri(_esSettings.ServerUri));
    settings.DefaultIndex(esSettings.DefaultIndex);
    _client = new ElasticClient(settings);
}

调用

var result = _client.Search<User>();

当调用 Search 方法的时候,因为使用的是 DefaultIndex,所以实际请求 URL 如下:

"http://localhost:9200/defaultindex/_search"

2.使用 .NET 类显式指定索引名称

配置:

public ElasticSearchClient(ElasticSearchSettings esSettings)
{
    _esSettings = esSettings;
    var settings = new ConnectionSettings(new Uri(_esSettings.ServerUri));
    settings.DefaultIndex(esSettings.DefaultIndex);
    // 针对 User.cs,显式指定该类对应的 ES 索引名称为 "User"
    settings.DefaultMappingFor<User>(ent=>ent.IndexName("user"));
    _client = new ElasticClient(settings);
}

调用:

var result = _client.Search<User>();

这个时候再调用搜索 User,此时的请求的 Url 如下:

"http://localhost:9200/user/_search"
  • 当同时通过 DefaultIndex 和 DefaultMappingFor 指定了索引名的时候,优先级顺序如下:
    • “DefaultMappingFor” >** “DefaultIndex”。

3.在创建请求的时候直接显式指定索引名

配置如下

public ElasticSearchClient(ElasticSearchSettings esSettings)
{
    _esSettings = esSettings;
    var settings = new ConnectionSettings(new Uri(_esSettings.ServerUri));
    settings.DefaultIndex(esSettings.DefaultIndex);
    settings.DefaultMappingFor<User>(ent=>ent.IndexName("user"));
    _client = new ElasticClient(settings);
}

在请求的时候指定索引名

var result = _client.Search<User>(user=>user.Index("anotheruser"));

最终请求的 url 为:

"http://localhost:9200/anotheruser/_search"
  • 当同时通过Request 上的 Index, DefaultIndex 和 DefaultMappingFor 来指定索引名的时候,优先级顺序如下:
    • “Request 上的 Index” > “DefaultMappingFor” > “DefaultIndex”。

【其他配置选项见此:3 - NEST 教程系列 3:配置选项】