Elasticsearch Client Provider¶
The Elasticsearch client provider module provides enterprise-grade search and analytics capabilities with enhanced security and configuration management. service for validating remote SSL certificates. It allows you to configure acceptable SSL policy errors and handle certificate validation in a consistent manner across your application.
Installation¶
If you want to install elasticsearch client;
-
Add the GridLab.Abp.Elasticsearch NuGet package to your project:
Install-Package GridLab.Abp.Elasticsearch
-
Add the
AbpGridLabElasticsearchModule
to the dependency list of your module:[DependsOn( //...other dependencies typeof(AbpGridLabElasticsearchModule) // <-- Add module dependency like that )] public class YourModule : AbpModule { }
-
Locate the
appsettings.json
file in your project. -
Create or update your
appsettings.json
with Elasticsearch configuration:{ "Elasticsearch": { "Enabled": true, "Configuration": { "ConnectionString": "https://localhost:9200", "DataStreamType": "logs", "DataStreamDataset": "application", "DataStreamNamespace": "production" }, "Authentication": { "Type": "Basic", "Username": "elastic", "Password": "your_password" }, "Ssl": { "Enabled": true, "CertificateFingerprint": "AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD", "CertPath": "certificates/elasticsearch.pfx", "CertPassphrase": "certificate_password" }, "Connection": { "TimeoutSeconds": 30, "MaxRetries": 3, "EnableDebugMode": false } }
Configuration Options¶
Elasticsearch Section¶
Property | Description | Default |
---|---|---|
Enabled | Enable/disable Elasticsearch integration | false |
Configuration Section¶
Property | Description | Default |
---|---|---|
ConnectionString | Elasticsearch cluster endpoint | https://localhost:9200 |
DataStreamType | Data stream type for logging | logs |
DataStreamDataset | Data stream dataset name | generic |
DataStreamNamespace | Data stream namespace | default |
Authentication Section¶
Property | Description | Values |
---|---|---|
Type | Authentication method | Basic, ApiKey, None |
Username | Username for Basic auth | - |
Password | Password for Basic auth | - |
ApiKey | API key for ApiKey auth | - |
SSL Section¶
Property | Description | Default |
---|---|---|
Enabled | Enable SSL certificate validation | true |
CertificateFingerprint | Expected certificate fingerprint | - |
CertPath | Path to client certificate (PKCS#12) | - |
CertPassphrase | Certificate passphrase | - |
Connection Section¶
Property | Description | Default |
---|---|---|
TimeoutSeconds | Request timeout in seconds | 30 |
MaxRetries | Maximum retry attempts | 3 |
EnableDebugMode | Enable debug logging | false |
Usage Examples¶
Basic Client Injection
public class MyService : ITransientDependency
{
private readonly IElasticsearchClientProvider _clientProvider;
public MyService(IElasticsearchClientProvider clientProvider)
{
_clientProvider = clientProvider;
}
public async Task<SearchResponse<MyDocument>> SearchDocumentsAsync()
{
var client = _clientProvider.GetClient();
var response = await client.SearchAsync<MyDocument>(s => s
.Index("my-index")
.Query(q => q.MatchAll())
);
return response;
}
}
Advance Search Options
public class DocumentSearchService : ITransientDependency
{
private readonly IElasticsearchClientProvider _clientProvider;
private readonly ILogger<DocumentSearchService> _logger;
public DocumentSearchService(
IElasticsearchClientProvider clientProvider,
ILogger<DocumentSearchService> logger)
{
_clientProvider = clientProvider;
_logger = logger;
}
public async Task<List<Document>> SearchAsync(string query, int pageSize = 10)
{
try
{
var client = _clientProvider.GetClient();
var response = await client.SearchAsync<Document>(s => s
.Index("documents")
.Size(pageSize)
.Query(q => q
.MultiMatch(m => m
.Fields(f => f.Field(doc => doc.Title).Field(doc => doc.Content))
.Query(query)
)
)
.Highlight(h => h
.Fields(f => f.Field(doc => doc.Content))
)
);
if (!response.IsValidResponse)
{
_logger.LogError("Elasticsearch search failed: {Error}", response.DebugInformation);
return new List<Document>();
}
return response.Documents.ToList();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error occurred during Elasticsearch search");
throw;
}
}
}
Index Management
public class IndexManagementService : ITransientDependency
{
private readonly IElasticsearchClientProvider _clientProvider;
public IndexManagementService(IElasticsearchClientProvider clientProvider)
{
_clientProvider = clientProvider;
}
public async Task<bool> CreateIndexAsync<T>(string indexName) where T : class
{
var client = _clientProvider.GetClient();
var response = await client.Indices.CreateAsync(indexName, c => c
.Mappings(m => m.AutoMap<T>())
.Settings(s => s
.NumberOfShards(1)
.NumberOfReplicas(1)
)
);
return response.IsValidResponse;
}
public async Task<bool> IndexDocumentAsync<T>(T document, string indexName) where T : class
{
var client = _clientProvider.GetClient();
var response = await client.IndexAsync(document, idx => idx.Index(indexName));
return response.IsValidResponse;
}
}
Serilog Integration¶
To use Elasticsearch as a Serilog sink in your ASP.NET Core application:
Program.cs
Configuration
var builder = WebApplication.CreateBuilder(args);
// Configure Serilog with Elasticsearch
builder.Host.UseSerilog((context, services, loggerConfig) =>
{
loggerConfig
.ReadFrom.Configuration(context.Configuration)
.Enrich.FromLogContext()
.Enrich.WithProperty("Application", "MyApplication")
.WriteTo.UseElasticsearch(context.Configuration);
});
// Add ABP and GridLab services
await builder.AddApplicationAsync<MyApplicationModule>();
var app = builder.Build();