嵌套具有多个索引的 ElasticClient 以索引文档

Nest ElasticClient with multiple indexes to index a document

起初我有 1 个索引,我的 elasticclient 在 startup.cs

中的设置如下所示
public static IServiceCollection AddElasticClient(this IServiceCollection services)
{
    var elasticSettings = services.BuildServiceProvider().GetService<IOptions<ElasticSettings>>().Value;

    var settings = new ConnectionSettings(new Uri(elasticSettings.Uri));
    settings
        .ThrowExceptions(elasticSettings.ThrowExceptions)
        .PrettyJson(elasticSettings.PrettyJson)
        .DefaultIndex(elasticSettings.Index)
        .BasicAuthentication(elasticSettings.Username, elasticSettings.Password)
        .DefaultMappingFor<CorrelationContext>(ms => ms.Ignore(p => p.DgpHeader));

    var client = new ElasticClient(settings);

    services.AddSingleton<IElasticClient>(client);

    return services;
}

我的作家长得像

public class ElasticWriter : IElasticWriter
{
    private readonly IElasticClient _elasticClient;

    public ElasticWriter(IElasticClient elasticClient)
    {
        _elasticClient = elasticClient ?? throw new ArgumentNullException(nameof(elasticClient));
    }

    public void Write(AuditElasticDoc doc)
    {
        var indexResponse = _elasticClient.IndexDocument(doc);

        if (!indexResponse.IsValid)
        {
                throw indexResponse.OriginalException ?? new Exception("Invalid Elastic response when writing document.");
        }
    }

}

现在有一个新要求,他们可以提供要写入的索引的名称。 不同索引的所有身份验证数据都是通过配置设置提供的,因此我在启动时拥有一切可用。 文档类型始终相同。

我找到了在查询时指定索引但在索引时不指定索引的示例。

能否在ElasticClient中提供多个索引,并在执行IndexDocument时指定索引? 还是每个索引都需要一个单独的客户端?

如果是后者,有没有办法我仍然可以使用 DI 将客户端注入我的编写器,或者我是否必须当场创建一个?

谢谢。

我正在使用 Nest 7.6.1

您可以使用 IndexAsync 方法来控制其他请求参数,而不是使用 IndexDocument

var indexResponse = await _elasticClient.IndexAsync(doc, descriptor => descriptor.Index("other"));

IndexDocument 是一种包装方法,对客户端隐藏了索引文档的复杂性。 Have a look.

请求授权配置

var indexResponse = await _elasticClient.IndexAsync(doc, 
    descriptor => descriptor
        .Index("other")
        .RequestConfiguration(rq => rq.BasicAuthentication("user", "pass")));