Search code examples
c#elasticsearchnestnest2

NEST2: How to specify the db index name once


Our C# WebAPI application uses of an ElasticSearch database. We're using NEST2 to access the db.

All the NEST2 queries in the code specify the database index name, here an example:

public TestQuery[] GetAllDocuments()
{
    var readRecords = ec.Search<TestDocument>(s => s
        .Index("my-index-name")
        .Query(q => q.
            QueryString(qs => qs.Query("*")))).Documents;

    return readRecords.ToArray();
}

Sometimes we forget to specify the index name in the query... the problem doesn't manifest itself immediately as the API works as expected and everything is fine... only when we add another index with some similar documents in it we see the problem

Is it possible to specify the index name once for all after NEST2 initialization? Doing so I'll avoid the burden to remember to insert it on every single query


Solution

  • You are looking for .DefaultIndex method on ConnectionSettings.

    var settings = new ConnectionSettings()
        .DefaultIndex("defaultindex");
    

    Hope it helps.