Bundle: redb-route / redb.Route.Elasticsearch (redb.Route.Elasticsearch.txt), 12 files
Snapshot: development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt
====
Path: redb-route/redb.Route.Elasticsearch/ElasticsearchComponent.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Elasticsearch/ElasticsearchComponent.cs
----
using Elastic.Clients.Elasticsearch;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Extensions;
using redb.Route.Core;
namespace redb.Route.Elasticsearch;
///
/// Elasticsearch transport component for redb.Route.
/// Schemes: elasticsearch , es .
///
/// URI format: elasticsearch://index-name?nodes=http://localhost:9200
///
///
/// Short alias: es://index-name?nodes=http://localhost:9200
///
///
/// With operation: es:Search:index-name?nodes=http://localhost:9200&query={"match_all":{}}
///
///
public sealed class ElasticsearchComponent : ComponentBase
{
///
public override string Scheme => "elasticsearch";
///
public override IReadOnlyList AlternateSchemes => ["es"];
///
public override IEndpoint CreateEndpoint(EndpointUri uri)
{
ArgumentNullException.ThrowIfNull(uri);
var options = new ElasticsearchEndpointOptions();
options.BindFromUri(uri.RawParameters);
options.Validate();
return new ElasticsearchEndpoint(uri, this, options);
}
}
///
/// Elasticsearch endpoint. Creates either a consumer (polling search)
/// or a producer (index/bulk/search/get/update/delete/count/exists).
///
/// The path part of the URI is parsed as [OPERATION:]index-name .
/// When an operation prefix is present (e.g. es:Search:my-index ),
/// the producer dispatches that specific operation.
///
///
public sealed class ElasticsearchEndpoint : EndpointBase
{
private ElasticsearchClient? _client;
private readonly SemaphoreSlim _clientLock = new(1, 1);
/// Parsed operation type (default: Index for producer).
public ElasticsearchOperationType OperationType { get; }
/// Index name parsed from the URI path.
public string IndexName { get; }
/// Logger from the parent component.
internal ILogger? Logger { get; }
/// Typed options (exposed for consumer/producer).
internal ElasticsearchEndpointOptions EndpointOptions => Options;
/// Creates an Elasticsearch endpoint.
public ElasticsearchEndpoint(EndpointUri uri, ElasticsearchComponent component, ElasticsearchEndpointOptions options)
: base(uri, component, options)
{
Logger = component.Logger;
(OperationType, IndexName) = ParsePath(uri.Path);
}
///
public override IProducer CreateProducer() => new ElasticsearchProducer(this, Options);
///
public override IConsumer CreateConsumer(IProcessor processor)
{
ArgumentNullException.ThrowIfNull(processor);
return new ElasticsearchConsumer(this, processor, Options);
}
/// Gets or creates a shared .
internal async Task GetOrCreateClientAsync(CancellationToken ct = default)
{
if (_client is not null)
return _client;
await _clientLock.WaitAsync(ct).ConfigureAwait(false);
try
{
if (_client is not null)
return _client;
var (client, nodes) = BuildClient();
_client = client;
// The nodes the client was built with: the connection factory's when one is named, not the endpoint's
// default. They may be a comma-separated list of URLs carrying userinfo credentials
// (http://user:pass@host); each is sanitized before logging.
var sanitizedNodes = string.Join(",", nodes.Split(',').Select(EndpointUri.Sanitize));
Logger?.LogInformation("Elasticsearch client created: Nodes={Nodes}, Index={Index}, ConnectionFactory={ConnectionFactory}",
sanitizedNodes, IndexName, string.IsNullOrEmpty(Options.ConnectionFactory) ? "-" : Options.ConnectionFactory);
return _client;
}
finally
{
_clientLock.Release();
}
}
///
public override Task Stop(CancellationToken ct = default)
{
// ElasticsearchClient uses HttpClient internally — no explicit dispose needed
_client = null;
_clientLock.Dispose();
Logger?.LogInformation("Elasticsearch endpoint stopped: {Uri}", EndpointUri.ForLog(Uri.ToString(), Logger));
return base.Stop(ct);
}
// ── Helpers ──
/// The client, and the nodes it connects to (for the log).
private (ElasticsearchClient Client, string Nodes) BuildClient()
{
// 1. Named factory from registry — a set-but-unknown name fails loud, never a
// silent fallback to URI parameters.
if (!string.IsNullOrEmpty(Options.ConnectionFactory))
{
var context = (Component as ElasticsearchComponent)?.Context;
var registryFactory = context.GetRequiredFromRegistry(
Options.ConnectionFactory);
Logger?.LogDebug("Elasticsearch: using ConnectionFactory '{Name}' from registry",
Options.ConnectionFactory);
return (registryFactory.Build(), registryFactory.Nodes);
}
// 2. Build from options
var factory = new ElasticsearchConnectionFactory
{
Nodes = Options.Nodes,
ApiKey = Options.ApiKey,
Username = Options.Username,
Password = Options.Password,
CertificateFingerprint = Options.CertificateFingerprint,
EnableDebugMode = Options.EnableDebugMode,
RequestTimeout = Options.RequestTimeout,
PingTimeout = Options.PingTimeout,
DeadTimeout = Options.DeadTimeout,
MaxDeadTimeout = Options.MaxDeadTimeout,
MaxRetries = Options.MaxRetries,
};
return (factory.Build(), factory.Nodes);
}
private static (ElasticsearchOperationType Operation, string IndexName) ParsePath(string path)
{
// Path may be "OPERATION:index-name" or just "index-name"
var colonIdx = path.IndexOf(':');
if (colonIdx > 0)
{
var opPart = path[..colonIdx];
var indexPart = path[(colonIdx + 1)..];
if (Enum.TryParse(opPart, ignoreCase: true, out var op))
return (op, indexPart);
}
return (ElasticsearchOperationType.Index, path);
}
}
Path: redb-route/redb.Route.Elasticsearch/ElasticsearchConnectionFactory.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Elasticsearch/ElasticsearchConnectionFactory.cs
----
using Elastic.Clients.Elasticsearch;
using Elastic.Transport;
using redb.Route.Core;
namespace redb.Route.Elasticsearch;
///
/// Connection factory for Elasticsearch. Register via DI or in the route registry
/// and reference by name in endpoint URIs (connectionFactory=myFactory ).
///
public sealed class ElasticsearchConnectionFactory
{
/// Comma-separated list of Elasticsearch node URIs.
public string Nodes { get; set; } = "http://localhost:9200";
/// API key authentication (base64-encoded).
[Sensitive]
public string ApiKey { get; set; } = "";
/// Basic auth username.
public string Username { get; set; } = "";
/// Basic auth password.
[Sensitive]
public string Password { get; set; } = "";
/// SHA-256 certificate fingerprint for TLS verification.
public string CertificateFingerprint { get; set; } = "";
/// Enable debug mode. (default: false)
public bool EnableDebugMode { get; set; }
/// Enable node sniffing for cluster discovery. (default: false)
public bool EnableSniffing { get; set; }
/// Request timeout in milliseconds. (default: 30000)
public int RequestTimeout { get; set; } = 30_000;
/// Ping timeout in milliseconds. (default: 2000)
public int PingTimeout { get; set; } = 2000;
/// Dead node backoff timeout in milliseconds. (default: 60000)
public int DeadTimeout { get; set; } = 60_000;
/// Max dead node backoff timeout in milliseconds. (default: 600000)
public int MaxDeadTimeout { get; set; } = 600_000;
/// Maximum retries per request. (default: 3)
public int MaxRetries { get; set; } = 3;
///
/// Creates an from this factory's settings.
///
public ElasticsearchClient Build()
{
var nodeUris = Nodes
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(n => new Uri(n))
.ToArray();
ElasticsearchClientSettings settings;
if (nodeUris.Length == 1)
{
settings = new ElasticsearchClientSettings(nodeUris[0]);
}
else if (EnableSniffing)
{
settings = new ElasticsearchClientSettings(new SniffingNodePool(nodeUris));
}
else
{
settings = new ElasticsearchClientSettings(new StaticNodePool(nodeUris));
}
// Auth
if (!string.IsNullOrWhiteSpace(ApiKey))
settings.Authentication(new ApiKey(ApiKey));
else if (!string.IsNullOrWhiteSpace(Username))
settings.Authentication(new BasicAuthentication(Username, Password ?? ""));
// TLS
if (!string.IsNullOrWhiteSpace(CertificateFingerprint))
settings.CertificateFingerprint(CertificateFingerprint);
// Timeouts
settings.RequestTimeout(TimeSpan.FromMilliseconds(RequestTimeout));
settings.PingTimeout(TimeSpan.FromMilliseconds(PingTimeout));
settings.DeadTimeout(TimeSpan.FromMilliseconds(DeadTimeout));
settings.MaxDeadTimeout(TimeSpan.FromMilliseconds(MaxDeadTimeout));
settings.MaximumRetries(MaxRetries);
if (EnableDebugMode)
settings.EnableDebugMode();
return new ElasticsearchClient(settings);
}
}
Path: redb-route/redb.Route.Elasticsearch/ElasticsearchConsumer.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Elasticsearch/ElasticsearchConsumer.cs
----
using ActivityKind = System.Diagnostics.ActivityKind;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using Elastic.Clients.Elasticsearch;
using Elastic.Clients.Elasticsearch.Core.Search;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
namespace redb.Route.Elasticsearch;
///
/// Elasticsearch consumer — polls an index using the Search API (or Scroll API for large result sets).
/// Extends for graceful two-CTS shutdown.
///
/// Supports search_after deep pagination, scroll API (legacy),
/// source filtering, sort ordering, delete-after-read, and query DSL.
///
///
internal sealed class ElasticsearchConsumer : DrainableConsumer
{
private readonly ElasticsearchEndpoint _endpoint;
private readonly ElasticsearchEndpointOptions _options;
private ElasticsearchClient? _client;
// search_after state: sort values from last hit of previous poll
private IReadOnlyCollection? _lastSortValues;
///
protected override IEndpoint ConsumerEndpoint => _endpoint;
///
protected override string ConsumerName => $"es://{_endpoint.IndexName}";
internal ElasticsearchConsumer(ElasticsearchEndpoint endpoint, IProcessor processor,
ElasticsearchEndpointOptions options)
: base(processor)
{
_endpoint = endpoint;
_options = options;
}
///
protected override async Task OnStarting(CancellationToken ct)
{
_client = await _endpoint.GetOrCreateClientAsync(ct).ConfigureAwait(false);
}
///
protected override async Task RunAsync(CancellationToken pollCt, CancellationToken processingCt)
{
if (_options.InitialDelay > 0)
await Task.Delay(_options.InitialDelay, pollCt).ConfigureAwait(false);
while (!pollCt.IsCancellationRequested)
{
try
{
if (!string.IsNullOrEmpty(_options.ScrollTimeout))
await PollWithScrollAsync(processingCt).ConfigureAwait(false);
else
await PollWithSearchAsync(processingCt).ConfigureAwait(false);
}
catch (OperationCanceledException) when (pollCt.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
Logger?.LogError(ex, "Elasticsearch consumer poll error on index {Index}", _endpoint.IndexName);
_endpoint.RecordError(ex);
}
try
{
await Task.Delay(_options.Delay, pollCt).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break;
}
}
}
// ═══════════════════════════════════════════════════════════════════
// SEARCH (standard pagination via search_after)
// ═══════════════════════════════════════════════════════════════════
private async Task PollWithSearchAsync(CancellationToken ct)
{
var response = await _client!.SearchAsync(s =>
{
s.Indices(_endpoint.IndexName);
s.Size(_options.Size);
s.TrackTotalHits(new TrackHits(_options.TrackTotalHits));
ConfigureQuery(s);
ConfigureSort(s);
ConfigureSourceFilter(s);
if (_lastSortValues is { Count: > 0 })
s.SearchAfter(_lastSortValues.ToList());
}, ct).ConfigureAwait(false);
if (!response.IsValidResponse)
{
Logger?.LogWarning("Elasticsearch search failed: {Info}", response.DebugInformation);
return;
}
await ProcessHitsAsync(response.Hits, ct).ConfigureAwait(false);
// Update search_after cursor from last hit
if (response.Hits.Count > 0)
{
var lastHit = response.Hits.Last();
_lastSortValues = lastHit.Sort;
}
}
// ═══════════════════════════════════════════════════════════════════
// SCROLL (for large result sets — deprecated in ES 8.x but supported)
// ═══════════════════════════════════════════════════════════════════
private async Task PollWithScrollAsync(CancellationToken ct)
{
// Initial scroll search
var searchResponse = await _client!.SearchAsync(s =>
{
s.Indices(_endpoint.IndexName);
s.Size(_options.Size);
s.Scroll(_options.ScrollTimeout);
s.TrackTotalHits(new TrackHits(_options.TrackTotalHits));
ConfigureQuery(s);
ConfigureSort(s);
ConfigureSourceFilter(s);
}, ct).ConfigureAwait(false);
if (!searchResponse.IsValidResponse)
{
Logger?.LogWarning("Elasticsearch scroll search failed: {Info}", searchResponse.DebugInformation);
return;
}
string? scrollId = searchResponse.ScrollId?.ToString();
try
{
// Process first page
await ProcessHitsAsync(searchResponse.Hits, ct).ConfigureAwait(false);
int lastHitCount = searchResponse.Hits.Count;
// Continue scrolling while there are hits
while (lastHitCount > 0 && !ct.IsCancellationRequested && scrollId is not null)
{
var scrollResponse = await _client.ScrollAsync(s =>
{
s.ScrollId(scrollId);
s.Scroll(_options.ScrollTimeout);
}, ct).ConfigureAwait(false);
if (!scrollResponse.IsValidResponse || scrollResponse.Hits.Count == 0)
break;
scrollId = scrollResponse.ScrollId?.ToString();
await ProcessHitsAsync(scrollResponse.Hits, ct).ConfigureAwait(false);
lastHitCount = scrollResponse.Hits.Count;
}
}
finally
{
// Clear scroll context
if (scrollId is not null)
{
try
{
await _client.ClearScrollAsync(s => s.ScrollId(new[] { scrollId }), ct).ConfigureAwait(false);
}
catch (Exception ex)
{
Logger?.LogDebug(ex, "Failed to clear scroll context {ScrollId}", scrollId);
}
}
}
}
// ═══════════════════════════════════════════════════════════════════
// HIT PROCESSING
// ═══════════════════════════════════════════════════════════════════
private async Task ProcessHitsAsync(IReadOnlyCollection> hits, CancellationToken ct)
{
foreach (var hit in hits)
{
if (ct.IsCancellationRequested) break;
// Create exchange with document body
var bodyJson = hit.Source?.ToJsonString() ?? "{}";
var message = new Message { Body = bodyJson, ContentType = "application/json" };
var exchange = Exchange.Create(message, _endpoint.ScopeFactory);
// Set headers
var headers = exchange.In.Headers;
headers[ElasticsearchHeaders.IndexName] = hit.Index;
headers[ElasticsearchHeaders.DocumentId] = hit.Id;
if (hit.Version is not null)
headers[ElasticsearchHeaders.Version] = hit.Version;
if (hit.SeqNo is not null)
headers[ElasticsearchHeaders.SequenceNumber] = hit.SeqNo;
if (hit.PrimaryTerm is not null)
headers[ElasticsearchHeaders.PrimaryTerm] = hit.PrimaryTerm;
if (hit.Score is not null)
headers[ElasticsearchHeaders.Score] = hit.Score;
if (hit.Sort is { Count: > 0 })
headers[ElasticsearchHeaders.SortValues] = JsonSerializer.Serialize(hit.Sort);
// Pipeline statistics are the core StatisticsProcessor's (ownership audit).
await ProcessTracedAsync(exchange, ct).ConfigureAwait(false);
// Post-processing: delete after read
if (_options.DeleteAfterRead && hit.Id is not null &&
(exchange.Exception == null || exchange.ExceptionHandled))
{
await _client!.DeleteAsync(_endpoint.IndexName, hit.Id, ct).ConfigureAwait(false);
}
}
}
///
/// inside the span of the hit. A hit carries no trace context, so
/// the span is a root, never a child of the activity the poll loop holds. A failed route marks it, whether the failure
/// stays on the exchange or escapes the pipeline; our own stop does not.
///
private async Task ProcessTracedAsync(IExchange exchange, CancellationToken ct)
{
using var span = RouteTelemetryExtensions.StartConsumerSpan(
(_endpoint.Component as ComponentBase)?.Context,
$"es {_endpoint.IndexName} receive", ActivityKind.Consumer, "db.system", "elasticsearch",
_endpoint.Uri.NormalizedKey, null, static (_, _) => null, destination: _endpoint.IndexName, operation: "receive");
await ProcessWithTracking(exchange, span, ct).ConfigureAwait(false);
}
// ═══════════════════════════════════════════════════════════════════
// QUERY / SORT / SOURCE CONFIGURATION
// ═══════════════════════════════════════════════════════════════════
private void ConfigureQuery(SearchRequestDescriptor s)
{
if (!string.IsNullOrEmpty(_options.Query))
{
// Raw JSON query via WrapperQuery (base64-encoded)
s.Query(q => q.Wrapper(w =>
w.Query(Convert.ToBase64String(Encoding.UTF8.GetBytes(_options.Query)))));
}
// If no query specified, default is match_all (ES behavior)
}
private void ConfigureSort(SearchRequestDescriptor s)
{
if (!string.IsNullOrEmpty(_options.Sort))
{
// Parse "field:order,field2:order2" format
var sortParts = _options.Sort.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
s.Sort(sortBuilder =>
{
foreach (var part in sortParts)
{
var fieldOrder = part.Split(':', 2);
var fieldName = fieldOrder[0].Trim();
var order = fieldOrder.Length > 1 &&
fieldOrder[1].Trim().Equals("desc", StringComparison.OrdinalIgnoreCase)
? SortOrder.Desc
: SortOrder.Asc;
sortBuilder.Field(fieldName, f => f.Order(order));
}
});
}
else
{
// Default sort for search_after pagination
s.Sort(sortBuilder => sortBuilder.Field("_doc", f => f.Order(SortOrder.Asc)));
}
}
private void ConfigureSourceFilter(SearchRequestDescriptor s)
{
var hasIncludes = !string.IsNullOrEmpty(_options.SourceIncludes);
var hasExcludes = !string.IsNullOrEmpty(_options.SourceExcludes);
if (!hasIncludes && !hasExcludes) return;
s.Source(new SourceConfig(new SourceFilter
{
Includes = hasIncludes
? _options.SourceIncludes!.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(f => (Elastic.Clients.Elasticsearch.Field)f).ToArray()
: null,
Excludes = hasExcludes
? _options.SourceExcludes!.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(f => (Elastic.Clients.Elasticsearch.Field)f).ToArray()
: null,
}));
}
}
Path: redb-route/redb.Route.Elasticsearch/ElasticsearchEndpointOptions.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Elasticsearch/ElasticsearchEndpointOptions.cs
----
using redb.Route.Core;
namespace redb.Route.Elasticsearch;
///
/// Endpoint options for Elasticsearch transport. All properties are auto-bound from URI query parameters.
///
/// URI format: elasticsearch://index-name?nodes=http://localhost:9200
///
///
/// Short alias: es://index-name?nodes=http://localhost:9200
///
///
/// For producer operations: es:Search:index-name?nodes=http://localhost:9200&query={"match_all":{}}
///
///
public class ElasticsearchEndpointOptions : EndpointOptions
{
// ═══════════════════════════════════════════════════════════════════
// CONNECTION
// ═══════════════════════════════════════════════════════════════════
///
/// Comma-separated list of Elasticsearch node URIs.
/// Example: http://localhost:9200 or http://node1:9200,http://node2:9200 .
///
public string Nodes { get; set; } = "http://localhost:9200";
/// API key authentication (base64-encoded).
[Sensitive]
public string ApiKey { get; set; } = "";
/// Basic auth username.
public string Username { get; set; } = "";
/// Basic auth password.
[Sensitive]
public string Password { get; set; } = "";
/// SHA-256 certificate fingerprint for TLS verification.
public string CertificateFingerprint { get; set; } = "";
///
/// Named connection factory reference. If set, looks up an
/// from the DI registry by this name to build the client.
///
[RegistryReference(typeof(ElasticsearchConnectionFactory))]
public string ConnectionFactory { get; set; } = "";
/// Enable debug mode — log raw requests/responses. (default: false)
public bool EnableDebugMode { get; set; }
// ═══════════════════════════════════════════════════════════════════
// TIMEOUTS / RESILIENCE
// ═══════════════════════════════════════════════════════════════════
/// Request timeout in milliseconds. (default: 30000)
public int RequestTimeout { get; set; } = 30_000;
/// Ping timeout in milliseconds. (default: 2000)
public int PingTimeout { get; set; } = 2000;
/// Dead node backoff timeout in milliseconds. (default: 60000)
public int DeadTimeout { get; set; } = 60_000;
/// Max dead node backoff timeout in milliseconds. (default: 600000)
public int MaxDeadTimeout { get; set; } = 600_000;
/// Maximum number of retries per request. (default: 3)
public int MaxRetries { get; set; } = 3;
// ═══════════════════════════════════════════════════════════════════
// COMMON
// ═══════════════════════════════════════════════════════════════════
///
/// Producer operation type. Parsed from URI path prefix or query param.
/// (default: )
///
public ElasticsearchOperationType Operation { get; set; } = ElasticsearchOperationType.Index;
/// Ingest pipeline name to apply on index/bulk operations.
public string Pipeline { get; set; } = "";
/// Custom routing value.
public string Routing { get; set; } = "";
///
/// Dynamic document ID expression. Supports ${header.redbEs.DocumentId} etc.
/// If not set, Elasticsearch auto-generates an ID (for Index) or the header is used.
///
public DynamicValue? DocumentId { get; set; }
/// Refresh policy: "true", "false", or "wait_for". (default: "false")
public string Refresh { get; set; } = "";
// ═══════════════════════════════════════════════════════════════════
// BULK SETTINGS
// ═══════════════════════════════════════════════════════════════════
/// Max documents per bulk request. (default: 100)
public int BulkSize { get; set; } = 100;
// ═══════════════════════════════════════════════════════════════════
// CONSUMER (polling search)
// ═══════════════════════════════════════════════════════════════════
/// Polling delay between search cycles in milliseconds. (default: 5000)
public int Delay { get; set; } = 5000;
/// Initial delay before first poll in milliseconds. (default: 1000)
public int InitialDelay { get; set; } = 1000;
///
/// JSON query DSL string. If empty, uses match_all .
/// Example: {"term":{"status":"active"}}
///
public string Query { get; set; } = "";
/// Number of hits per search page. (default: 100, max 10000)
public int Size { get; set; } = 100;
///
/// Scroll timeout for Scroll API (e.g. "1m", "5m"). If empty, uses search_after pagination.
///
public string ScrollTimeout { get; set; } = "";
///
/// Sort field(s) for ordering. Format: timestamp:desc,_id:asc .
/// Required for search_after pagination. If empty, defaults to _doc:asc .
///
public string Sort { get; set; } = "";
/// Delete document after successful processing. (default: false)
public bool DeleteAfterRead { get; set; }
/// Track total hit count. (default: true)
public bool TrackTotalHits { get; set; } = true;
///
/// Comma-separated list of fields to include in _source.
/// Example: title,author,timestamp
///
public string SourceIncludes { get; set; } = "";
///
/// Comma-separated list of fields to exclude from _source.
/// Example: large_blob,internal_field
///
public string SourceExcludes { get; set; } = "";
// ═══════════════════════════════════════════════════════════════════
// VALIDATION
// ═══════════════════════════════════════════════════════════════════
///
public override void Validate()
{
if (string.IsNullOrWhiteSpace(Nodes) && string.IsNullOrWhiteSpace(ConnectionFactory))
throw new ArgumentOutOfRangeException(nameof(Nodes), "Nodes or ConnectionFactory is required");
if (Delay < 100)
throw new ArgumentOutOfRangeException(nameof(Delay), "Delay must be >= 100ms");
if (Size < 1 || Size > 10_000)
throw new ArgumentOutOfRangeException(nameof(Size), "Size must be 1-10000");
if (BulkSize < 1)
throw new ArgumentOutOfRangeException(nameof(BulkSize), "BulkSize must be >= 1");
if (RequestTimeout < 1000)
throw new ArgumentOutOfRangeException(nameof(RequestTimeout), "RequestTimeout must be >= 1000ms");
if (MaxRetries < 0)
throw new ArgumentOutOfRangeException(nameof(MaxRetries), "MaxRetries must be >= 0");
}
}
Path: redb-route/redb.Route.Elasticsearch/ElasticsearchHeaders.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Elasticsearch/ElasticsearchHeaders.cs
----
namespace redb.Route.Elasticsearch;
///
/// Well-known header constants used by the Elasticsearch component.
/// Follows the redbEs. prefix convention.
///
public static class ElasticsearchHeaders
{
/// Common prefix for all Elasticsearch component headers.
public const string Prefix = "redbEs.";
// ═══════════════════════════════════════════════════════════════════
// COMMON (set by consumer, read by producer)
// ═══════════════════════════════════════════════════════════════════
/// Index name.
public const string IndexName = "redbEs.IndexName";
/// Document ID (_id).
public const string DocumentId = "redbEs.DocumentId";
/// Document version (_version).
public const string Version = "redbEs.Version";
/// Sequence number (_seq_no) for optimistic concurrency.
public const string SequenceNumber = "redbEs.SequenceNumber";
/// Primary term (_primary_term) for optimistic concurrency.
public const string PrimaryTerm = "redbEs.PrimaryTerm";
/// Operation to perform (used to override endpoint operation).
public const string Operation = "redbEs.Operation";
// ═══════════════════════════════════════════════════════════════════
// INDEX / UPDATE / DELETE RESULT
// ═══════════════════════════════════════════════════════════════════
/// Result of the operation: created, updated, deleted, noop.
public const string Result = "redbEs.Result";
// ═══════════════════════════════════════════════════════════════════
// SEARCH (consumer & producer)
// ═══════════════════════════════════════════════════════════════════
/// Relevance score (_score).
public const string Score = "redbEs.Score";
/// Total number of matching documents.
public const string TotalHits = "redbEs.TotalHits";
/// Total hits relation: "eq" or "gte".
public const string TotalHitsRelation = "redbEs.TotalHitsRelation";
/// Scroll context ID for scroll API.
public const string ScrollId = "redbEs.ScrollId";
/// Sort values from the last hit (for search_after pagination).
public const string SortValues = "redbEs.SortValues";
// ═══════════════════════════════════════════════════════════════════
// BULK
// ═══════════════════════════════════════════════════════════════════
/// Number of items in the bulk response.
public const string BulkItemCount = "redbEs.BulkItemCount";
/// Whether the bulk response had errors (bool).
public const string BulkErrors = "redbEs.BulkErrors";
/// Serialized error details from failed bulk items (JSON).
public const string BulkErrorItems = "redbEs.BulkErrorItems";
// ═══════════════════════════════════════════════════════════════════
// MULTISEARCH
// ═══════════════════════════════════════════════════════════════════
/// Number of individual search responses returned.
public const string MultiSearchResponseCount = "redbEs.MultiSearchResponseCount";
/// Whether any sub-query returned an error (bool).
public const string MultiSearchHasErrors = "redbEs.MultiSearchHasErrors";
/// Array of total hits per sub-query (long[]).
public const string MultiSearchTotalHits = "redbEs.MultiSearchTotalHits";
// ═══════════════════════════════════════════════════════════════════
// REQUEST ROUTING
// ═══════════════════════════════════════════════════════════════════
/// Ingest pipeline name override.
public const string Pipeline = "redbEs.Pipeline";
/// Custom routing value override.
public const string Routing = "redbEs.Routing";
/// Refresh policy override: "true", "false", or "wait_for".
public const string Refresh = "redbEs.Refresh";
/// Returns true if the header key starts with the ES prefix.
public static bool IsRedbHeader(string headerKey) =>
headerKey.StartsWith(Prefix, StringComparison.Ordinal);
}
Path: redb-route/redb.Route.Elasticsearch/ElasticsearchOperationType.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Elasticsearch/ElasticsearchOperationType.cs
----
namespace redb.Route.Elasticsearch;
///
/// Elasticsearch operation types — determines what the producer does.
/// Parsed from the first path segment of the URI: elasticsearch:OPERATION:index-name
/// or es:OPERATION:index-name .
/// When no operation is specified, the default is for producer.
///
public enum ElasticsearchOperationType
{
/// Index (upsert) a single document. Default producer operation.
Index,
/// Bulk API — batch index/update/delete operations.
Bulk,
/// Search API — returns hits (InOut pattern).
Search,
/// Get a single document by ID (InOut pattern).
Get,
/// Partial update a document by ID.
Update,
/// Delete a single document by ID.
Delete,
/// Count documents matching a query (InOut pattern).
Count,
/// Check if a document exists by ID (InOut pattern).
Exists,
/// Multi-search API — execute multiple search queries in a single request (InOut pattern).
MultiSearch,
}
Path: redb-route/redb.Route.Elasticsearch/ElasticsearchProducer.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Elasticsearch/ElasticsearchProducer.cs
----
using System.Diagnostics;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using Elastic.Clients.Elasticsearch;
using Elastic.Clients.Elasticsearch.Core.MSearch;
using Elastic.Clients.Elasticsearch.Core.Search;
using Elastic.Clients.Elasticsearch.QueryDsl;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
namespace redb.Route.Elasticsearch;
///
/// Elasticsearch producer — sends messages to Elasticsearch via Index/Bulk/Search/Get/Update/Delete/Count/Exists/MultiSearch.
/// Extends for persistent client lifecycle.
///
internal sealed class ElasticsearchProducer : ConnectableProducer
{
private readonly ElasticsearchEndpoint _endpoint;
private readonly ElasticsearchEndpointOptions _options;
private ElasticsearchClient? _client;
///
protected override IEndpoint ProducerEndpoint => _endpoint;
///
protected override string ProducerName => $"es:{_endpoint.OperationType}:{_endpoint.IndexName}";
internal ElasticsearchProducer(ElasticsearchEndpoint endpoint, ElasticsearchEndpointOptions options)
{
_endpoint = endpoint;
_options = options;
}
///
protected override async Task ConnectAsync(CancellationToken ct)
{
_client = await _endpoint.GetOrCreateClientAsync(ct).ConfigureAwait(false);
// Verify connectivity
var ping = await _client.PingAsync(ct).ConfigureAwait(false);
if (!ping.IsValidResponse)
Logger?.LogWarning("Elasticsearch ping failed during connect: {Info}", ping.DebugInformation);
}
///
public override async Task Process(IExchange exchange, CancellationToken ct = default)
{
EnsureStarted();
ArgumentNullException.ThrowIfNull(exchange);
// Allow runtime operation override via header
var operation = _endpoint.OperationType;
if (exchange.In.Headers.TryGetValue(ElasticsearchHeaders.Operation, out var opHeader) && opHeader is string opStr)
{
if (Enum.TryParse(opStr, ignoreCase: true, out var headerOp))
operation = headerOp;
}
using var activity = RouteTelemetryExtensions.StartTransportSpan(
(_endpoint.Component as ComponentBase)?.Context,
$"es {operation}", ActivityKind.Client,
"db.system", "elasticsearch",
_endpoint.Uri.NormalizedKey,
destination: _endpoint.IndexName,
operation: operation.ToString());
try
{
await DispatchOperationAsync(operation, exchange, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
{
// Only our own token cancelling the call is a stop; a timeout or any other failure marks the span.
activity.RecordFailure(ex);
throw;
}
}
// ═══════════════════════════════════════════════════════════════════
// OPERATION DISPATCH
// ═══════════════════════════════════════════════════════════════════
private async Task DispatchOperationAsync(ElasticsearchOperationType operation, IExchange exchange,
CancellationToken ct)
{
switch (operation)
{
case ElasticsearchOperationType.Index:
await ProcessIndexAsync(exchange, ct).ConfigureAwait(false);
break;
case ElasticsearchOperationType.Bulk:
await ProcessBulkAsync(exchange, ct).ConfigureAwait(false);
break;
case ElasticsearchOperationType.Search:
await ProcessSearchAsync(exchange, ct).ConfigureAwait(false);
break;
case ElasticsearchOperationType.Get:
await ProcessGetAsync(exchange, ct).ConfigureAwait(false);
break;
case ElasticsearchOperationType.Update:
await ProcessUpdateAsync(exchange, ct).ConfigureAwait(false);
break;
case ElasticsearchOperationType.Delete:
await ProcessDeleteAsync(exchange, ct).ConfigureAwait(false);
break;
case ElasticsearchOperationType.Count:
await ProcessCountAsync(exchange, ct).ConfigureAwait(false);
break;
case ElasticsearchOperationType.Exists:
await ProcessExistsAsync(exchange, ct).ConfigureAwait(false);
break;
case ElasticsearchOperationType.MultiSearch:
await ProcessMultiSearchAsync(exchange, ct).ConfigureAwait(false);
break;
default:
throw new InvalidOperationException($"Unsupported Elasticsearch operation: {operation}");
}
}
// ═══════════════════════════════════════════════════════════════════
// INDEX
// ═══════════════════════════════════════════════════════════════════
private async Task ProcessIndexAsync(IExchange exchange, CancellationToken ct)
{
var index = ResolveIndex(exchange);
var documentId = ResolveDocumentId(exchange);
var body = ResolveBodyAsJsonObject(exchange);
var response = await _client!.IndexAsync(body, r =>
{
r.Index(index);
if (documentId is not null) r.Id(documentId);
var pipeline = ResolveStringOption(exchange, ElasticsearchHeaders.Pipeline, _options.Pipeline);
if (!string.IsNullOrEmpty(pipeline)) r.Pipeline(pipeline);
var routing = ResolveStringOption(exchange, ElasticsearchHeaders.Routing, _options.Routing);
if (!string.IsNullOrEmpty(routing)) r.Routing(new Routing(routing));
ApplyRefresh(r, exchange);
}, ct).ConfigureAwait(false);
ValidateResponse(response, "Index");
exchange.In.Headers[ElasticsearchHeaders.DocumentId] = response.Id;
exchange.In.Headers[ElasticsearchHeaders.Version] = response.Version;
exchange.In.Headers[ElasticsearchHeaders.Result] = response.Result.ToString();
exchange.In.Headers[ElasticsearchHeaders.SequenceNumber] = response.SeqNo;
exchange.In.Headers[ElasticsearchHeaders.PrimaryTerm] = response.PrimaryTerm;
// MessagesOut is recorded by the core (ToProcessor / the template) - ownership audit.
}
// ═══════════════════════════════════════════════════════════════════
// BULK
// ═══════════════════════════════════════════════════════════════════
private async Task ProcessBulkAsync(IExchange exchange, CancellationToken ct)
{
var index = ResolveIndex(exchange);
var items = ResolveBodyAsList(exchange);
int totalItems = 0;
bool hasErrors = false;
var errorDetails = new List();
// Batch into chunks of BulkSize
foreach (var batch in items.Chunk(_options.BulkSize))
{
var response = await _client!.BulkAsync(b =>
{
b.Index(index);
foreach (var item in batch)
b.Index(item, idx => { });
var refresh = ResolveRefreshValue(exchange);
if (refresh is not null) b.Refresh(refresh.Value);
}, ct).ConfigureAwait(false);
totalItems += response.Items.Count;
if (response.Errors)
{
hasErrors = true;
foreach (var item in response.Items.Where(i => i.Error is not null))
errorDetails.Add($"{item.Id}: {item.Error?.Reason}");
}
}
exchange.In.Headers[ElasticsearchHeaders.BulkItemCount] = totalItems;
exchange.In.Headers[ElasticsearchHeaders.BulkErrors] = hasErrors;
if (hasErrors)
exchange.In.Headers[ElasticsearchHeaders.BulkErrorItems] = JsonSerializer.Serialize(errorDetails);
// MessagesOut is recorded by the core (ToProcessor / the template) - ownership audit.
}
// ═══════════════════════════════════════════════════════════════════
// SEARCH
// ═══════════════════════════════════════════════════════════════════
private async Task ProcessSearchAsync(IExchange exchange, CancellationToken ct)
{
var index = ResolveIndex(exchange);
var query = exchange.In.Body as string ?? _options.Query;
var response = await _client!.SearchAsync(s =>
{
s.Indices(index);
s.Size(_options.Size);
s.TrackTotalHits(new TrackHits(_options.TrackTotalHits));
ApplyQuery(s, query);
}, ct).ConfigureAwait(false);
ValidateResponse(response, "Search");
var documents = response.Documents.ToList();
exchange.Out = new Message { Body = documents, ContentType = "application/json" };
exchange.Out.Headers[ElasticsearchHeaders.TotalHits] = response.Total;
exchange.Pattern = ExchangePattern.InOut;
// MessagesOut is recorded by the core (ToProcessor / the template) - ownership audit.
}
// ═══════════════════════════════════════════════════════════════════
// GET
// ═══════════════════════════════════════════════════════════════════
private async Task ProcessGetAsync(IExchange exchange, CancellationToken ct)
{
var index = ResolveIndex(exchange);
var documentId = RequireDocumentId(exchange, "GET");
var response = await _client!.GetAsync(index, documentId, ct).ConfigureAwait(false);
if (response.Found)
{
exchange.Out = new Message
{
Body = response.Source?.ToJsonString() ?? "{}",
ContentType = "application/json"
};
exchange.Out.Headers[ElasticsearchHeaders.DocumentId] = response.Id;
exchange.Out.Headers[ElasticsearchHeaders.Version] = response.Version;
exchange.Out.Headers[ElasticsearchHeaders.SequenceNumber] = response.SeqNo;
exchange.Out.Headers[ElasticsearchHeaders.PrimaryTerm] = response.PrimaryTerm;
}
else
{
exchange.Out = new Message { Body = null };
}
exchange.Pattern = ExchangePattern.InOut;
// MessagesOut is recorded by the core (ToProcessor / the template) - ownership audit.
}
// ═══════════════════════════════════════════════════════════════════
// UPDATE
// ═══════════════════════════════════════════════════════════════════
private async Task ProcessUpdateAsync(IExchange exchange, CancellationToken ct)
{
var index = ResolveIndex(exchange);
var documentId = RequireDocumentId(exchange, "UPDATE");
var body = ResolveBodyAsJsonObject(exchange);
var response = await _client!.UpdateAsync(
index, documentId, r =>
{
r.Doc(body);
var refresh = ResolveRefreshValue(exchange);
if (refresh is not null) r.Refresh(refresh.Value);
}, ct).ConfigureAwait(false);
ValidateResponse(response, "Update");
exchange.In.Headers[ElasticsearchHeaders.Result] = response.Result.ToString();
exchange.In.Headers[ElasticsearchHeaders.Version] = response.Version;
// MessagesOut is recorded by the core (ToProcessor / the template) - ownership audit.
}
// ═══════════════════════════════════════════════════════════════════
// DELETE
// ═══════════════════════════════════════════════════════════════════
private async Task ProcessDeleteAsync(IExchange exchange, CancellationToken ct)
{
var index = ResolveIndex(exchange);
var documentId = RequireDocumentId(exchange, "DELETE");
var request = new DeleteRequest(index, documentId);
var refresh = ResolveRefreshValue(exchange);
if (refresh is not null) request.Refresh = refresh.Value;
var response = await _client!.DeleteAsync(request, ct).ConfigureAwait(false);
ValidateResponse(response, "Delete");
exchange.In.Headers[ElasticsearchHeaders.Result] = response.Result.ToString();
// MessagesOut is recorded by the core (ToProcessor / the template) - ownership audit.
}
// ═══════════════════════════════════════════════════════════════════
// COUNT
// ═══════════════════════════════════════════════════════════════════
private async Task ProcessCountAsync(IExchange exchange, CancellationToken ct)
{
var index = ResolveIndex(exchange);
var query = exchange.In.Body as string ?? _options.Query;
var response = await _client!.CountAsync(r =>
{
r.Indices(index);
ApplyQuery(r, query);
}, ct).ConfigureAwait(false);
ValidateResponse(response, "Count");
exchange.Out = new Message { Body = response.Count };
exchange.Pattern = ExchangePattern.InOut;
// MessagesOut is recorded by the core (ToProcessor / the template) - ownership audit.
}
// ═══════════════════════════════════════════════════════════════════
// EXISTS
// ═══════════════════════════════════════════════════════════════════
private async Task ProcessExistsAsync(IExchange exchange, CancellationToken ct)
{
var index = ResolveIndex(exchange);
var documentId = RequireDocumentId(exchange, "EXISTS");
var response = await _client!.ExistsAsync(index, documentId, ct).ConfigureAwait(false);
exchange.Out = new Message { Body = response.Exists };
exchange.Pattern = ExchangePattern.InOut;
// MessagesOut is recorded by the core (ToProcessor / the template) - ownership audit.
}
// ═══════════════════════════════════════════════════════════════════
// MULTISEARCH
// ═══════════════════════════════════════════════════════════════════
private async Task ProcessMultiSearchAsync(IExchange exchange, CancellationToken ct)
{
var defaultIndex = ResolveIndex(exchange);
var queries = ResolveBodyAsQueryArray(exchange);
var items = new SearchRequestItem[queries.Count];
for (int i = 0; i < queries.Count; i++)
{
var q = queries[i];
var header = new MultisearchHeader();
if (q.TryGetPropertyValue("index", out var idxNode) && idxNode is not null)
header.Indices = idxNode.GetValue();
var body = new MultisearchBody();
// Query (required) — raw JSON query passed via WrapperQuery
if (q.TryGetPropertyValue("query", out var queryNode) && queryNode is not null)
{
var raw = queryNode.ToJsonString();
body.Query = new Query
{
Wrapper = new WrapperQuery
{
Query = Convert.ToBase64String(Encoding.UTF8.GetBytes(raw))
}
};
}
if (q.TryGetPropertyValue("size", out var sizeNode) && sizeNode is not null)
body.Size = sizeNode.GetValue();
if (q.TryGetPropertyValue("from", out var fromNode) && fromNode is not null)
body.From = fromNode.GetValue();
// Sort: "field:order,field2:order2" string format (same as consumer)
if (q.TryGetPropertyValue("sort", out var sortNode) && sortNode is not null)
{
var sortStr = sortNode.GetValue();
var sortParts = sortStr.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
var sortOptions = new List();
foreach (var part in sortParts)
{
var fieldOrder = part.Split(':', 2);
var fieldName = fieldOrder[0].Trim();
var order = fieldOrder.Length > 1 &&
fieldOrder[1].Trim().Equals("desc", StringComparison.OrdinalIgnoreCase)
? SortOrder.Desc
: SortOrder.Asc;
sortOptions.Add(new SortOptions { Field = new FieldSort { Field = fieldName, Order = order } });
}
body.Sort = sortOptions;
}
// Source filtering: "_source" can be false (disable) or "field1,field2" (includes only)
if (q.TryGetPropertyValue("_source", out var sourceNode) && sourceNode is not null)
{
if (sourceNode is JsonValue jv && jv.TryGetValue(out var srcBool))
{
body.Source = new SourceConfig(srcBool);
}
else
{
var fields = sourceNode.GetValue()
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(f => (Field)f).ToArray();
body.Source = new SourceConfig(new Elastic.Clients.Elasticsearch.Core.Search.SourceFilter { Includes = fields });
}
}
items[i] = new SearchRequestItem(header, body);
}
var response = await _client!.MultiSearchAsync(ms =>
{
ms.Indices(defaultIndex);
ms.Searches(items);
}, ct).ConfigureAwait(false);
ValidateResponse(response, "MultiSearch");
var allResults = new List>();
var totalHitsList = new List();
bool hasErrors = false;
foreach (var item in response.Responses)
{
if (item.Tag == UnionTag.T1)
{
var searchItem = item.Value1!;
allResults.Add(searchItem.Documents.ToList());
totalHitsList.Add(searchItem.Total);
}
else if (item.Tag == UnionTag.T2)
{
hasErrors = true;
allResults.Add(new List());
totalHitsList.Add(0);
}
}
exchange.Out = new Message { Body = allResults, ContentType = "application/json" };
exchange.Out.Headers[ElasticsearchHeaders.MultiSearchResponseCount] = allResults.Count;
exchange.Out.Headers[ElasticsearchHeaders.MultiSearchTotalHits] = totalHitsList.ToArray();
exchange.Out.Headers[ElasticsearchHeaders.MultiSearchHasErrors] = hasErrors;
exchange.Pattern = ExchangePattern.InOut;
// MessagesOut is recorded by the core (ToProcessor / the template) - ownership audit.
}
// ═══════════════════════════════════════════════════════════════════
// HELPERS
// ═══════════════════════════════════════════════════════════════════
private string ResolveIndex(IExchange exchange)
{
if (exchange.In.Headers.TryGetValue(ElasticsearchHeaders.IndexName, out var hdr) && hdr is string idx &&
!string.IsNullOrEmpty(idx))
return idx;
return _endpoint.IndexName;
}
private string? ResolveDocumentId(IExchange exchange)
{
if (exchange.In.Headers.TryGetValue(ElasticsearchHeaders.DocumentId, out var hdr) && hdr is string id &&
!string.IsNullOrEmpty(id))
return id;
return _options.DocumentId?.Resolve(exchange);
}
private static string RequireDocumentId(IExchange exchange, string operation)
{
if (exchange.In.Headers.TryGetValue(ElasticsearchHeaders.DocumentId, out var hdr) && hdr is string id &&
!string.IsNullOrEmpty(id))
return id;
throw new InvalidOperationException($"ElasticsearchHeaders.DocumentId is required for {operation} operation");
}
private static string ResolveStringOption(IExchange exchange, string headerKey, string defaultValue)
{
if (exchange.In.Headers.TryGetValue(headerKey, out var hdr) && hdr is string val &&
!string.IsNullOrEmpty(val))
return val;
return defaultValue;
}
private static JsonObject ResolveBodyAsJsonObject(IExchange exchange)
{
return exchange.In.Body switch
{
JsonObject jo => jo,
string s => JsonNode.Parse(s)?.AsObject()
?? throw new InvalidOperationException("Body is not valid JSON"),
byte[] bytes => JsonNode.Parse(bytes)?.AsObject()
?? throw new InvalidOperationException("Body is not valid JSON"),
null => throw new InvalidOperationException("Body is null — cannot index empty document"),
_ => JsonNode.Parse(JsonSerializer.Serialize(exchange.In.Body))?.AsObject()
?? throw new InvalidOperationException("Cannot serialize body to JSON"),
};
}
private static List ResolveBodyAsList(IExchange exchange)
{
return exchange.In.Body switch
{
IEnumerable list => list.ToList(),
string s => JsonSerializer.Deserialize>(s)
?? throw new InvalidOperationException("Body is not a valid JSON array"),
byte[] bytes => JsonSerializer.Deserialize>(bytes)
?? throw new InvalidOperationException("Body is not a valid JSON array"),
null => throw new InvalidOperationException("Body is null — cannot bulk index empty list"),
_ => throw new InvalidOperationException(
$"Bulk operation requires body of type IEnumerable, string, or byte[], got {exchange.In.Body.GetType().Name}"),
};
}
private static List ResolveBodyAsQueryArray(IExchange exchange)
{
return exchange.In.Body switch
{
string s => JsonSerializer.Deserialize>(s)
?? throw new InvalidOperationException("MultiSearch body is not a valid JSON array"),
byte[] bytes => JsonSerializer.Deserialize>(bytes)
?? throw new InvalidOperationException("MultiSearch body is not a valid JSON array"),
IEnumerable list => list.ToList(),
null => throw new InvalidOperationException("Body is null — MultiSearch requires a JSON array of queries"),
_ => throw new InvalidOperationException(
$"MultiSearch requires body of type string, byte[], or IEnumerable, got {exchange.In.Body.GetType().Name}"),
};
}
private Refresh? ResolveRefreshValue(IExchange exchange)
{
var refresh = ResolveStringOption(exchange, ElasticsearchHeaders.Refresh, _options.Refresh);
if (string.IsNullOrEmpty(refresh)) return null;
return refresh.ToLowerInvariant() switch
{
"true" => Refresh.True,
"wait_for" => Refresh.WaitFor,
_ => Refresh.False,
};
}
private void ApplyRefresh(IndexRequestDescriptor r, IExchange exchange)
{
var v = ResolveRefreshValue(exchange);
if (v is not null) r.Refresh(v.Value);
}
/// Applies a raw JSON query via WrapperQuery (base64-encoded JSON).
private static void ApplyQuery(SearchRequestDescriptor s, string? query)
{
if (!string.IsNullOrEmpty(query))
s.Query(q => q.Wrapper(w => w.Query(Convert.ToBase64String(Encoding.UTF8.GetBytes(query)))));
}
/// Applies a raw JSON query via WrapperQuery (base64-encoded JSON) for count requests.
private static void ApplyQuery(CountRequestDescriptor r, string? query)
{
if (!string.IsNullOrEmpty(query))
r.Query(q => q.Wrapper(w => w.Query(Convert.ToBase64String(Encoding.UTF8.GetBytes(query)))));
}
private static void ValidateResponse(Elastic.Transport.Products.Elasticsearch.ElasticsearchResponse response, string operation)
{
if (!response.IsValidResponse)
throw new InvalidOperationException(
$"Elasticsearch {operation} failed: {response.DebugInformation}");
}
}
Path: redb-route/redb.Route.Elasticsearch/Extensions/ServiceCollectionExtensions.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Elasticsearch/Extensions/ServiceCollectionExtensions.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Extensions;
namespace redb.Route.Elasticsearch;
///
/// Extension methods for registering the Elasticsearch transport in a DI container.
///
public static class ServiceCollectionExtensions
{
///
/// Registers the in the route context so that
/// elasticsearch:// and es:// URIs are resolved.
///
///
/// services.AddRedbRoute(route =>
/// {
/// route.Services.AddRedbRouteElasticsearch();
/// route.AddRouteBuilder<MyRoutes>();
/// });
///
///
///
public static IServiceCollection AddRedbRouteElasticsearch(this IServiceCollection services)
{
// IRouteContextConfigurator is applied by RouteHostedService at startup --
// the correct registration hook (a lazy marker singleton never fires).
services.AddRouteComponent();
return services;
}
}
Path: redb-route/redb.Route.Elasticsearch/Fluent/ElasticsearchDsl.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Elasticsearch/Fluent/ElasticsearchDsl.cs
----
using System.Text;
using redb.Route.Abstractions;
namespace redb.Route.Elasticsearch;
///
/// Fluent API for Elasticsearch endpoints.
///
/// // Consumer: poll for new documents
/// .From(Es.Index("my-index")
/// .Nodes("http://localhost:9200")
/// .Query("{\"term\":{\"status\":\"active\"}}")
/// .Sort("timestamp:desc")
/// .DeleteAfterRead()
/// .Delay(10_000))
///
/// // Producer: index a document
/// .To(Es.Index("my-index")
/// .Nodes("http://localhost:9200")
/// .Refresh("wait_for"))
///
/// // Producer: search
/// .To(Es.Index("my-index", ElasticsearchOperationType.Search)
/// .Nodes("http://localhost:9200"))
///
///
public static class Es
{
/// Creates an Elasticsearch endpoint builder for the given index name.
public static ElasticsearchBuilder Index(string indexName)
=> new(indexName, null);
/// Creates an Elasticsearch endpoint builder with a specific producer operation.
public static ElasticsearchBuilder Index(string indexName, ElasticsearchOperationType operation)
=> new(indexName, operation);
}
///
/// Fluent builder for Elasticsearch endpoint URIs.
///
public sealed class ElasticsearchBuilder
{
private readonly string _indexName;
private readonly ElasticsearchOperationType? _operation;
// Connection
private string? _nodes;
private string? _apiKey;
private string? _username;
private string? _password;
private string? _certificateFingerprint;
private string? _connectionFactory;
private bool _enableDebugMode;
// Timeouts
private string? _requestTimeout;
private string? _pingTimeout;
private string? _deadTimeout;
private string? _maxDeadTimeout;
private string? _maxRetries;
// Common
private string? _pipeline;
private string? _routing;
private string? _documentId;
private string? _refresh;
private string? _bulkSize;
// Consumer
private string? _delay;
private string? _initialDelay;
private string? _query;
private string? _size;
private string? _scrollTimeout;
private string? _sort;
private bool _deleteAfterRead;
private bool? _trackTotalHits;
private string? _sourceIncludes;
private string? _sourceExcludes;
internal ElasticsearchBuilder(string indexName, ElasticsearchOperationType? operation)
{
ArgumentException.ThrowIfNullOrWhiteSpace(indexName);
_indexName = indexName;
_operation = operation;
}
// ═══════════════════════════════════════════════════════════════════
// CONNECTION
// ═══════════════════════════════════════════════════════════════════
/// Comma-separated node URIs.
public ElasticsearchBuilder Nodes(string nodes) { _nodes = nodes; return this; }
/// Node URIs from an expression.
public ElasticsearchBuilder Nodes(IExpression nodes) { _nodes = nodes.ToTemplateString(); return this; }
/// API key authentication.
public ElasticsearchBuilder ApiKey(string key) { _apiKey = key; return this; }
/// API key from expression.
public ElasticsearchBuilder ApiKey(IExpression key) { _apiKey = key.ToTemplateString(); return this; }
/// Basic auth username.
public ElasticsearchBuilder Username(string user) { _username = user; return this; }
/// Basic auth password.
public ElasticsearchBuilder Password(string pass) { _password = pass; return this; }
/// TLS certificate fingerprint.
public ElasticsearchBuilder CertificateFingerprint(string fp) { _certificateFingerprint = fp; return this; }
/// Named connection factory from registry.
public ElasticsearchBuilder ConnectionFactory(string name) { _connectionFactory = name; return this; }
/// Enable debug mode for request/response logging.
public ElasticsearchBuilder DebugMode() { _enableDebugMode = true; return this; }
// ═══════════════════════════════════════════════════════════════════
// TIMEOUTS
// ═══════════════════════════════════════════════════════════════════
/// Request timeout in milliseconds.
public ElasticsearchBuilder RequestTimeout(int ms) { _requestTimeout = ms.ToString(); return this; }
/// Ping timeout in milliseconds.
public ElasticsearchBuilder PingTimeout(int ms) { _pingTimeout = ms.ToString(); return this; }
/// Dead node backoff in milliseconds.
public ElasticsearchBuilder DeadTimeout(int ms) { _deadTimeout = ms.ToString(); return this; }
/// Max dead node backoff in milliseconds.
public ElasticsearchBuilder MaxDeadTimeout(int ms) { _maxDeadTimeout = ms.ToString(); return this; }
/// Maximum retries per request.
public ElasticsearchBuilder MaxRetries(int n) { _maxRetries = n.ToString(); return this; }
// ═══════════════════════════════════════════════════════════════════
// COMMON
// ═══════════════════════════════════════════════════════════════════
/// Ingest pipeline name.
public ElasticsearchBuilder Pipeline(string name) { _pipeline = name; return this; }
/// Custom routing value.
public ElasticsearchBuilder Routing(string value) { _routing = value; return this; }
/// Routing from expression.
public ElasticsearchBuilder Routing(IExpression value) { _routing = value.ToTemplateString(); return this; }
/// Dynamic document ID expression.
public ElasticsearchBuilder DocumentId(string expr) { _documentId = expr; return this; }
/// Dynamic document ID from expression.
public ElasticsearchBuilder DocumentId(IExpression expr) { _documentId = expr.ToTemplateString(); return this; }
/// Refresh policy: "true", "false", or "wait_for".
public ElasticsearchBuilder Refresh(string policy) { _refresh = policy; return this; }
/// Max documents per bulk request.
public ElasticsearchBuilder BulkSize(int n) { _bulkSize = n.ToString(); return this; }
// ═══════════════════════════════════════════════════════════════════
// CONSUMER
// ═══════════════════════════════════════════════════════════════════
/// Polling delay in milliseconds. Default 5000.
public ElasticsearchBuilder Delay(int ms) { _delay = ms.ToString(); return this; }
/// Polling delay from expression.
public ElasticsearchBuilder Delay(IExpression ms) { _delay = ms.ToTemplateString(); return this; }
/// Initial delay before first poll in milliseconds.
public ElasticsearchBuilder InitialDelay(int ms) { _initialDelay = ms.ToString(); return this; }
/// JSON query DSL string.
public ElasticsearchBuilder Query(string json) { _query = json; return this; }
/// Hits per search page. Default 100.
public ElasticsearchBuilder Size(int n) { _size = n.ToString(); return this; }
/// Scroll timeout (e.g. "1m"). Enables Scroll API.
public ElasticsearchBuilder ScrollTimeout(string timeout) { _scrollTimeout = timeout; return this; }
/// Sort fields: "field:asc,field2:desc".
public ElasticsearchBuilder Sort(string sort) { _sort = sort; return this; }
/// Delete documents after successful consumption.
public ElasticsearchBuilder DeleteAfterRead(bool v = true) { _deleteAfterRead = v; return this; }
/// Track total hit count.
public ElasticsearchBuilder TrackTotalHits(bool v = true) { _trackTotalHits = v; return this; }
/// Source fields to include.
public ElasticsearchBuilder SourceIncludes(string fields) { _sourceIncludes = fields; return this; }
/// Source fields to exclude.
public ElasticsearchBuilder SourceExcludes(string fields) { _sourceExcludes = fields; return this; }
// ═══════════════════════════════════════════════════════════════════
// BUILD
// ═══════════════════════════════════════════════════════════════════
/// Builds the Elasticsearch endpoint URI string using the full scheme.
public string Build() => BuildUri("elasticsearch");
/// Builds the short-form URI using es:// .
public string BuildShort() => BuildUri("es");
private string BuildUri(string scheme)
{
var sb = new StringBuilder();
sb.Append(scheme).Append("://");
if (_operation.HasValue)
{
sb.Append(_operation.Value);
sb.Append(':');
}
sb.Append(_indexName);
var sep = '?';
void Append(string key, string value)
{
sb.Append(sep); sb.Append(key); sb.Append('=');
sb.Append(Uri.EscapeDataString(value)); sep = '&';
}
void AppendIf(string key, string? value) { if (!string.IsNullOrEmpty(value)) Append(key, value); }
void AppendBool(string key, bool value) { if (value) Append(key, "true"); }
void AppendBoolExplicit(string key, bool? value)
{
if (value.HasValue) Append(key, value.Value.ToString().ToLowerInvariant());
}
// Connection
AppendIf("nodes", _nodes);
AppendIf("apiKey", _apiKey);
AppendIf("username", _username);
AppendIf("password", _password);
AppendIf("certificateFingerprint", _certificateFingerprint);
AppendIf("connectionFactory", _connectionFactory);
AppendBool("enableDebugMode", _enableDebugMode);
// Timeouts
AppendIf("requestTimeout", _requestTimeout);
AppendIf("pingTimeout", _pingTimeout);
AppendIf("deadTimeout", _deadTimeout);
AppendIf("maxDeadTimeout", _maxDeadTimeout);
AppendIf("maxRetries", _maxRetries);
// Common
AppendIf("pipeline", _pipeline);
AppendIf("routing", _routing);
AppendIf("documentId", _documentId);
AppendIf("refresh", _refresh);
AppendIf("bulkSize", _bulkSize);
// Consumer
AppendIf("delay", _delay);
AppendIf("initialDelay", _initialDelay);
AppendIf("query", _query);
AppendIf("size", _size);
AppendIf("scrollTimeout", _scrollTimeout);
AppendIf("sort", _sort);
AppendBool("deleteAfterRead", _deleteAfterRead);
AppendBoolExplicit("trackTotalHits", _trackTotalHits);
AppendIf("sourceIncludes", _sourceIncludes);
AppendIf("sourceExcludes", _sourceExcludes);
return sb.ToString();
}
/// Implicit conversion to URI string (full scheme).
public static implicit operator string(ElasticsearchBuilder b) => b.Build();
///
public override string ToString() => Build();
}
Path: redb-route/redb.Route.Elasticsearch/README.md
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Elasticsearch/README.md
----
# redb.Route.Elasticsearch
> Documentation and articles:
Elasticsearch connector for the [redb.Route](../README.md) ESB framework.
Provides a full-featured **producer** (9 operations) and a **polling consumer** with deep pagination, source filtering, and delete-after-read. Compatible with **Elasticsearch 8.x**.
[](https://www.nuget.org/packages/redb.Route.Elasticsearch)
[](../../LICENSE)
## Quick Start
```csharp
// Consumer: poll an index for new documents
.From(Es.Index("orders")
.Nodes("http://localhost:9200")
.Query("""{"term":{"status":"pending"}}""")
.Sort("timestamp:asc")
.Size(100)
.DeleteAfterRead())
// Producer: index a document
.To(Es.Index("orders")
.Nodes("http://localhost:9200")
.Refresh("wait_for"))
```
## URI Format
```
elasticsearch://[OPERATION:]index-name?nodes=http://host:9200¶m=value
es://[OPERATION:]index-name?nodes=http://host:9200 # short alias
```
Operations: `Index` (default), `Bulk`, `Search`, `Get`, `Update`, `Delete`, `Count`, `Exists`, `MultiSearch`.
## Producer Operations
| Operation | Body (In) | Result (Out) | Pattern |
|-----------|-----------|--------------|---------|
| **Index** | JSON document | — | InOnly |
| **Bulk** | JSON array of documents | — | InOnly |
| **Search** | JSON query DSL | `List` hits | InOut |
| **Get** | — (ID via header) | JSON document | InOut |
| **Update** | Partial JSON document | — | InOnly |
| **Delete** | — (ID via header) | — | InOnly |
| **Count** | JSON query DSL (optional) | `long` count | InOut |
| **Exists** | — (ID via header) | `bool` | InOut |
| **MultiSearch** | JSON array of queries | `List>` | InOut |
### Index
```csharp
var exchange = new Exchange(new Message("""{"title":"Hello","author":"Alice"}"""));
exchange.In.Headers[ElasticsearchHeaders.DocumentId] = "doc-1"; // optional, auto-generated if omitted
await producer.Process(exchange);
// Headers set: DocumentId, Version, Result, SequenceNumber, PrimaryTerm
```
### Bulk
```csharp
var docs = new JsonArray { new JsonObject { ["title"] = "A" }, new JsonObject { ["title"] = "B" } };
var exchange = new Exchange(new Message(docs.ToJsonString()));
await producer.Process(exchange);
// Headers set: BulkItemCount, BulkErrors, BulkErrorItems
```
Documents are automatically chunked into batches of `bulkSize` (default: 100).
### Search
```csharp
var exchange = new Exchange(new Message("""{"match_all":{}}"""));
await producer.Process(exchange);
var docs = exchange.Out!.Body as List;
var total = (long)exchange.Out.Headers[ElasticsearchHeaders.TotalHits]!;
```
### MultiSearch
Execute multiple search queries in a single request. Each query supports `index`, `query`, `size`, `from`, `sort`, and `_source`:
```csharp
var queries = """
[
{"index": "logs-2024", "query": {"term": {"level": "error"}}, "size": 5, "sort": "timestamp:desc"},
{"index": "logs-2024", "query": {"match_all": {}}, "_source": "message,timestamp"},
{"query": {"range": {"score": {"gte": 90}}}}
]
""";
var exchange = new Exchange(new Message(queries));
await producer.Process(exchange);
var results = exchange.Out!.Body as List>; // one list per query
var totalHits = exchange.Out.Headers[ElasticsearchHeaders.MultiSearchTotalHits] as long[];
var hasErrors = (bool)exchange.Out.Headers[ElasticsearchHeaders.MultiSearchHasErrors]!;
```
**MultiSearch query fields:**
| Field | Type | Description |
|-------|------|-------------|
| `index` | string | Override index for this sub-query |
| `query` | object | Elasticsearch query DSL |
| `size` | int | Max hits to return |
| `from` | int | Offset for pagination |
| `sort` | string | Sort expression: `field:asc,field2:desc` |
| `_source` | string\|bool | Field filter: `"title,author"` or `false` to disable |
### Operation Override via Header
Any producer can switch operations at runtime:
```csharp
exchange.In.Headers[ElasticsearchHeaders.Operation] = "Count";
await producer.Process(exchange);
```
## Consumer
The consumer polls an Elasticsearch index and delivers each document as an exchange.
```csharp
.From(Es.Index("events")
.Nodes("http://localhost:9200")
.Query("""{"range":{"timestamp":{"gte":"now-1h"}}}""")
.Sort("timestamp:asc,_id:asc")
.Size(200)
.SourceIncludes("title,body,timestamp")
.DeleteAfterRead()
.Delay(5000))
```
### Pagination Strategies
- **`search_after`** (default) — stateful cursor-based pagination using sort values from the last hit. Efficient for deep pagination.
- **Scroll API** — enabled when `scrollTimeout` is set (e.g., `scrollTimeout=1m`). Legacy approach, deprecated in ES 8.x.
### Delete After Read
When `deleteAfterRead=true`, the consumer deletes each document after successful processing. If processing throws an exception, the document is preserved.
### Consumer Headers (per document)
| Header | Type | Description |
|--------|------|-------------|
| `redbEs.IndexName` | string | Source index name |
| `redbEs.DocumentId` | string | Document `_id` |
| `redbEs.Version` | long | Document `_version` |
| `redbEs.SequenceNumber` | long | `_seq_no` for optimistic concurrency |
| `redbEs.PrimaryTerm` | long | `_primary_term` for optimistic concurrency |
| `redbEs.Score` | double | Relevance `_score` |
| `redbEs.SortValues` | string | JSON-serialized sort values |
## Configuration Reference
### Connection
| Parameter | Default | Description |
|-----------|---------|-------------|
| `nodes` | `http://localhost:9200` | Comma-separated node URIs |
| `apiKey` | — | Base64-encoded API key |
| `username` | — | Basic auth username |
| `password` | — | Basic auth password |
| `certificateFingerprint` | — | SHA-256 TLS fingerprint |
| `connectionFactory` | — | Named factory from DI registry |
| `enableDebugMode` | `false` | Log raw request/response |
### Timeouts & Resilience
| Parameter | Default | Min | Description |
|-----------|---------|-----|-------------|
| `requestTimeout` | 30000 | 1000 | Request timeout (ms) |
| `pingTimeout` | 2000 | — | Node ping timeout (ms) |
| `deadTimeout` | 60000 | — | Dead node backoff (ms) |
| `maxDeadTimeout` | 600000 | — | Max dead node timeout (ms) |
| `maxRetries` | 3 | 0 | Retries per request |
### Producer
| Parameter | Default | Description |
|-----------|---------|-------------|
| `operation` | `Index` | Default operation |
| `pipeline` | — | Ingest pipeline name |
| `routing` | — | Custom routing value |
| `refresh` | — | Refresh policy: `true`, `false`, `wait_for` |
| `bulkSize` | 100 | Documents per bulk batch |
### Consumer
| Parameter | Default | Description |
|-----------|---------|-------------|
| `delay` | 5000 | Poll interval (ms), min 100 |
| `initialDelay` | 1000 | Delay before first poll (ms) |
| `query` | match_all | JSON query DSL |
| `size` | 100 | Hits per page (1–10000) |
| `sort` | `_doc:asc` | Sort fields: `field:order,...` |
| `scrollTimeout` | — | Scroll API timeout (e.g. `1m`) |
| `deleteAfterRead` | `false` | Delete docs after processing |
| `trackTotalHits` | `true` | Track exact total hit count |
| `sourceIncludes` | — | Fields to include (CSV) |
| `sourceExcludes` | — | Fields to exclude (CSV) |
## Connection Factory
For complex or shared client configurations, register a named `ElasticsearchConnectionFactory`:
```csharp
var factory = new ElasticsearchConnectionFactory
{
Nodes = "https://node1:9200,https://node2:9200",
ApiKey = "base64encodedkey",
EnableSniffing = true,
MaxRetries = 5,
};
// Reference by name in URI
Es.Index("my-index").ConnectionFactory("myFactory")
```
The factory supports `StaticNodePool` (default) and `SniffingNodePool` (cluster discovery) depending on node count and `EnableSniffing` flag.
## Headers Reference
All headers use the `redbEs.` prefix.
| Constant | Value | Direction | Used By |
|----------|-------|-----------|---------|
| `IndexName` | `redbEs.IndexName` | In | Consumer, Producer |
| `DocumentId` | `redbEs.DocumentId` | In/Out | All |
| `Version` | `redbEs.Version` | Out | Index, Get, Update |
| `SequenceNumber` | `redbEs.SequenceNumber` | Out | Index, Get, Consumer |
| `PrimaryTerm` | `redbEs.PrimaryTerm` | Out | Index, Get, Consumer |
| `Operation` | `redbEs.Operation` | In | Producer (override) |
| `Result` | `redbEs.Result` | Out | Index, Update, Delete |
| `Score` | `redbEs.Score` | Out | Consumer |
| `TotalHits` | `redbEs.TotalHits` | Out | Search |
| `TotalHitsRelation` | `redbEs.TotalHitsRelation` | Out | Search |
| `ScrollId` | `redbEs.ScrollId` | Out | Consumer (scroll) |
| `SortValues` | `redbEs.SortValues` | Out | Consumer |
| `BulkItemCount` | `redbEs.BulkItemCount` | Out | Bulk |
| `BulkErrors` | `redbEs.BulkErrors` | Out | Bulk |
| `BulkErrorItems` | `redbEs.BulkErrorItems` | Out | Bulk |
| `MultiSearchResponseCount` | `redbEs.MultiSearchResponseCount` | Out | MultiSearch |
| `MultiSearchHasErrors` | `redbEs.MultiSearchHasErrors` | Out | MultiSearch |
| `MultiSearchTotalHits` | `redbEs.MultiSearchTotalHits` | Out | MultiSearch |
| `Pipeline` | `redbEs.Pipeline` | In | Producer |
| `Routing` | `redbEs.Routing` | In | Producer |
| `Refresh` | `redbEs.Refresh` | In | Producer |
## Requirements
- **Elasticsearch 8.x** (tested with 8.17.0)
- .NET 10.0 / 11.0. The 4.7 line stays on .NET 8, 9 and 10 for applications that cannot move yet.
- `Elastic.Clients.Elasticsearch` 8.19.18
## Named connection factory
Keep credentials out of the route URI: register a factory in the context registry and
reference it by name. A set-but-unknown name fails loud at startup — a typo can never
silently fall back to inline URI parameters.
```csharp
context.AddToRegistry("prod", new ElasticsearchConnectionFactory
{
Nodes = "https://es1:9200,https://es2:9200",
ApiKey = secrets.EsApiKey,
});
// es://logs?connectionFactory=prod
```
## Tracing
On the `redb.Route` activity source (`AddSource("redb.Route")`), with `db.system` = `elasticsearch`,
`redb.route.endpoint` and the index as `messaging.destination.name`:
- **Consumer.** One `Consumer` span, `es {index} receive`, per routed hit. A document carries no trace context, so the
span is a root, never a child of the activity the poll loop inherited from whoever started the routes. An empty poll
opens none. A failed route marks it an error, whether the failure stays on the exchange or escapes the pipeline; our
own stop does not.
- **Producer.** One `Client` span per call, `es {operation}`; an error when the call fails, unless our own token
cancelled it.
- `RouteEngineOptions.EnableTelemetry = false` opens neither span.
Path: redb-route/redb.Route.Elasticsearch/_SortCheck.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Elasticsearch/_SortCheck.cs
----
using Elastic.Clients.Elasticsearch;
using Elastic.Clients.Elasticsearch.Core.MSearch;
using Elastic.Clients.Elasticsearch.Core.Search;
class SortCheck
{
void Check()
{
var body = new MultisearchBody();
// Sort is ICollection
body.Sort = new List
{
new SortOptions { Field = new FieldSort { Field = "timestamp", Order = SortOrder.Desc } }
};
// Source is SourceConfig
body.Source = new SourceConfig(new SourceFilter
{
Includes = new Field[] { new Field("title"), new Field("author") }
});
// Source with false (disable)
body.Source = new SourceConfig(false);
}
}
Path: redb-route/redb.Route.Elasticsearch/redb.Route.Elasticsearch.csproj
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Elasticsearch/redb.Route.Elasticsearch.csproj
----
redb.Route.Elasticsearch
Elasticsearch connector for redb.Route ESB framework. Polling search/scroll consumer with deep pagination, source filtering, and delete-after-read; multi-operation producer with Index, Bulk, Search, Get, Update, Delete, Count, and Exists. Compatible with Elasticsearch 8.x.
esb;messaging;elasticsearch;search;redb
README.md