Configuration options

edit

Connecting to Elasticsearch with Elasticsearch.Net and NEST is easy, but it’s entirely possible that you’d like to change the default connection behaviour. There are a number of configuration options available on ConnectionConfiguration for the low level client and ConnectionSettings for the high level client that can be used to control how the clients interact with Elasticsearch.

Options on ConnectionConfiguration

edit

The following is a list of available connection configuration options on ConnectionConfiguration; since ConnectionSettings derives from ConnectionConfiguration, these options are available for both the low level and high level client:

ApiKeyAuthentication
Api Key to send with all requests to Elasticsearch
BasicAuthentication
Basic Authentication credentials to send with all requests to Elasticsearch
CertificateFingerprint
ClientCertificate
Use a X509Certificate to authenticate all HTTP requests. You can also set them on individual request using ClientCertificates
ClientCertificates
Use the following certificates to authenticate all HTTP requests. You can also set them on individual request using ClientCertificates
ConnectionLimit

Limits the number of concurrent connections that can be opened to an endpoint. Defaults to 80 for all IConnection implementations that are not based on System.Net.Http.CurlHandler . For those based on System.Net.Http.CurlHandler, defaults to Environment.ProcessorCount .

For Desktop CLR, this setting applies to the DefaultConnectionLimit property on the ServicePointManager object when creating ServicePoint objects, affecting the default IConnection implementation.

For Core CLR, this setting applies to the MaxConnectionsPerServer property on the HttpClientHandler instances used by the HttpClient inside the default IConnection implementation

DeadTimeout
Sets the default dead timeout factor when a node has been marked dead. Some connection pools may use a flat timeout whilst others take this factor and increase it exponentially
DisableAutomaticProxyDetection
Disables the automatic detection of a proxy
DisableDirectStreaming

Ensures the response bytes are always available on the ElasticsearchResponse<T>

Depending on the registered serializer, this may cause the response to be buffered in memory first, potentially affecting performance.

DisableMetaHeader
Disables the meta header which is included on all requests by default. This header contains lightweight information about the client and runtime.
DisablePing
When a node is used for the very first time or when it’s used for the first time after it has been marked dead a ping with a very low timeout is send to the node to make sure that when it’s still dead it reports it as fast as possible. You can disable these pings globally here if you rather have it fail on the possible slower original request
EnableApiVersioningHeader
EnableDebugMode
Turns on settings that aid in debugging like DisableDirectStreaming() and PrettyJson() so that the original request and response JSON can be inspected. It also always asks the server for the full stack trace on errors
EnableHttpCompression

Enables gzip compressed requests and responses.

You need to configure http compression on Elasticsearch to be able to use this

https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-http.html

EnableHttpPipelining

Allows for requests to be pipelined. http://en.wikipedia.org/wiki/HTTP_pipelining

HTTP pipelining must also be enabled in Elasticsearch for this to work properly.

EnableTcpKeepAlive

Sets the keep-alive option on a TCP connection.

For Desktop CLR, sets ServicePointManager.SetTcpKeepAlive

GlobalHeaders
A collection of headers that will be sent with every request. Useful in situations where you always need to pass a header e.g. a custom auth header
GlobalQueryStringParameters
A collection of query string parameters that will be sent with every request. Useful in situations where you always need to pass a parameter e.g. an API key.
IncludeServerStackTraceOnError
Forces all requests to have ?error_trace=true querystring parameter appended, causing Elasticsearch to return stack traces as part of serialized exceptions Defaults to false
MaxDeadTimeout
Sets the maximum time a node can be marked dead. Different implementations of IConnectionPool may choose a different default.
MaximumRetries
The maximum number of retries for a given request
MaxRetryTimeout

Limits the total runtime, including retries, separately from RequestTimeout

When not specified, defaults to RequestTimeout , which itself defaults to 60 seconds

MemoryStreamFactory
The memory stream factory to use, defaults to Default
NodePredicate
Register a predicate to select which nodes that you want to execute API calls on. Note that sniffing requests omit this predicate and always execute on all nodes. When using an IConnectionPool implementation that supports reseeding of nodes, this will default to omitting master only node from regular API calls. When using static or single node connection pooling it is assumed the list of node you instantiate the client with should be taken verbatim.
OnRequestCompleted
Registers an Action<T> that is called when a response is received from Elasticsearch. This can be useful for implementing custom logging. Multiple callbacks can be registered by calling this multiple times
OnRequestDataCreated
Registers an Action<T> that is called when RequestData is created. Multiple callbacks can be registered by calling this multiple times
PingTimeout
Sets the default ping timeout in milliseconds for ping requests, which are used to determine whether a node is alive. Pings should fail as fast as possible.
PrettyJson
Forces all requests to have ?pretty=true querystring parameter appended, causing Elasticsearch to return formatted JSON. Defaults to false
Proxy
If your connection has to go through proxy, use this method to specify the proxy url
RequestTimeout

Sets the default timeout in milliseconds for each request to Elasticsearch. Defaults to 60 seconds.

You can set this to a high value here, and specify a timeout on Elasticsearch’s side.

ServerCertificateValidationCallback
Register a ServerCertificateValidationCallback, this is called per endpoint until it returns true. After this callback returns true that endpoint is validated for the lifetime of the ServiceEndpoint for that host.
SkipDeserializationForStatusCodes
Configure the client to skip deserialization of certain status codes e.g: you run Elasticsearch behind a proxy that returns a HTML for 401, 500
SniffLifeSpan
Set the duration after which a cluster state is considered stale and a sniff should be performed again. An IConnectionPool has to signal it supports reseeding, otherwise sniffing will never happen. Defaults to 1 hour. Set to null to disable completely. Sniffing will only ever happen on ConnectionPools that return true for SupportsReseeding
SniffOnConnectionFault
Enables resniffing of the cluster when a call fails, if the connection pool supports reseeding. Defaults to true
SniffOnStartup
Enables sniffing on first usage of a connection pool if that pool supports reseeding. Defaults to true
ThrowExceptions

Instead of following a c/go like error checking on response.IsValid do throw an exception (except when SuccessOrKnownError is false) on the client when a call resulted in an exception on either the client or the Elasticsearch server.

Reasons for such exceptions could be search parser errors, index missing exceptions, etc…​

TransferEncodingChunked
Whether the request should be sent with chunked Transfer-Encoding. Default is false
UserAgent
The user agent string to send with requests. Useful for debugging purposes to understand client and framework versions that initiate requests to Elasticsearch

ConnectionConfiguration with ElasticLowLevelClient

edit

Here’s an example to demonstrate setting several configuration options using the low level client

var connectionConfiguration = new ConnectionConfiguration()
    .DisableAutomaticProxyDetection()
    .EnableHttpCompression()
    .DisableDirectStreaming()
    .PrettyJson()
    .RequestTimeout(TimeSpan.FromMinutes(2));

var lowLevelClient = new ElasticLowLevelClient(connectionConfiguration);

Options on ConnectionSettings

edit

The following is a list of available connection configuration options on ConnectionSettings:

DefaultDisableIdInference

Disables automatic Id inference for given CLR types.

NEST by default will use the value of a property named Id on a CLR type as the _id to send to Elasticsearch. Adding a type will disable this behaviour for that CLR type. If Id inference should be disabled for all CLR types, use DefaultDisableIdInference

DefaultFieldNameInferrer

Specifies how field names are inferred from CLR property names.

By default, NEST camel cases property names. For example, CLR property EmailAddress will be inferred as "emailAddress" Elasticsearch document field name

DefaultIndex
The default index to use for a request when no index has been explicitly specified and no default indices are specified for the given CLR type specified for the request.
DefaultMappingFor
Specify how the mapping is inferred for a given CLR type. The mapping can infer the index, id and relation name for a given CLR type, as well as control serialization behaviour for CLR properties.

ConnectionSettings with ElasticClient

edit

Here’s an example to demonstrate setting several configuration options using the high level client

var connectionSettings = new ConnectionSettings()
    .DefaultMappingFor<Project>(i => i
        .IndexName("my-projects")
        .IdProperty(p => p.Name)
    )
    .EnableDebugMode()
    .PrettyJson()
    .RequestTimeout(TimeSpan.FromMinutes(2));

var client = new ElasticClient(connectionSettings);

Basic Authentication credentials can alternatively be specified on the node URI directly

var uri = new Uri("http://username:password@localhost:9200");
var settings = new ConnectionConfiguration(uri);

but this can be awkward when using connection pooling with multiple nodes, especially when the connection pool used is one that is capable of reseeding itself. For this reason, we’d recommend specifying credentials on ConnectionSettings.