Skip to content

.NET Core Elasticsearch.Net and NEST

🏷️ .NET Core Elasticsearch

1. 安装包

powershell
Install-Package NEST
Install-Package Elasticsearch.Net

2. 在 appsettings.json 中增加配置项

关于 .net core 中的配置项的用法可以参照 .NET Core The New Configuration Model in ASP.NET Core

json
"B2bElasticSearch": {
    "Uris": [
        "http://192.168.0.72:9200"
    ]
}

3. 增加配置项对应的配置类 ElasticSearchConfig

cs
public class ElasticSearchConfig
{
    public IEnumerable<string> Uris { get; set; }
}

4. 增加自定义的连接池 B2bElasticConnectionPool

cs
public class B2bElasticConnectionPool : SniffingConnectionPool
{
    public B2bElasticConnectionPool(IOptions<ElasticSearchConfig> options) : base(options.Value.Uris.Select(uri => new Uri(uri)))
    {
    }
}

5. 增加自定义的客户端 ElasticClient

cs
public class B2bElasticClient : ElasticClient
{
    public B2bElasticClient(IConnectionPool pool) : base(new ConnectionSettings(pool))
    {
    }
}

6. 在 Startup.cs 中注册配置和服务

cs
public void ConfigureServices(IServiceCollection services)
{
    // ...

    // 注册 ElasticSearch 设定
    services.Configure<ElasticSearchConfig>(Configuration.GetSection("B2bElasticSearch"));
    // 注入 ElasticSearch 连接池
    services.AddSingleton<IConnectionPool, B2bElasticConnectionPool>();
    // 注入 ElasticSearch Client
    services.AddScoped<IElasticClient, B2bElasticClient>();

    services.AddMvc();

    // ...
}

7. 在 Controller 中创建、查询 ElasticSearch 文档

cs
[Produces("application/json")]
[Route("api/Line")]
public class LineController : Controller
{
    private readonly IElasticClient _elasticClient;

    private static string LINE_INDEX = "net-core-test-index";

    public LineController(IElasticClient elasticClient)
    {
        _elasticClient = elasticClient;
    }

    // GET api/line
    [HttpGet]
    public IEnumerable<Line> Get()
    {
        // 首次访问时追加初始数据
        var countResponse = _elasticClient.Count<Line>(c => c.Index(LINE_INDEX).Query(q => q.MatchAll()));
        if (countResponse.Count <= 0)
        {
            for (int i = 0; i < 10; i++)
            {
                // indexing
                var line = new Line()
                {
                    Id = i,
                    Title = $"测试线路 {i}",
                    Price = 1000 * i,
                };

                var indexResponse = _elasticClient.Index(line, id => id.Index(LINE_INDEX));
            }
        }

        // Searching
        var searchResponse = _elasticClient.Search<Line>(s => s
            .Index(LINE_INDEX)
            .From(0)
            .Size(10)
        );

        return searchResponse.Documents;
    }

    // GET api/line/5
    [HttpGet("{id}")]
    public IEnumerable<Line> Get(int id)
    {
        // Searching
        var searchResponse = _elasticClient.Search<Line>(s => s
            .Index(LINE_INDEX)
            .From(0)
            .Size(10)
            .Query(q => q
                    .Ids(i => i.Values(id)
                    )
            )
        );

        return searchResponse.Documents;
    }
}

参照