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();
}