Search code examples
c#elasticsearch.net-corenest

Calling Search immediately after indexing fails intermittently in Elasticsearch NEST


I am using NEST Elasticsearch client and trying to do Unit test. I see that GET starts working immediately but SEARCH takes few milliseconds, causing the Tests to fail intermittently.

await _elasticClient.GetAsync<User>(id)).Source; //Works fine 
elasticClient.Search<User>(s =>
                s.Query(q =>
                    q.MultiMatch(x =>
                        x.Fields(f => f
                            .Field(petType => petType.Name, 3)
                            .Field(petType => petType.Category)
                    )));
             // response.Documents is empty many times.

Adding a delay of 500ms between Index and Search statements works but makes the tests slow.

Is there a way to solve this.

I believe search follows eventual consistency. I am going to attempt to configure number of replicas or shards to 1 to see if that helps.


Solution

  • I was able to solve this issue by calling Refresh API.

    await _client.Indices.RefreshAsync("index-name");
    

    Refresh waits for the Indexing to complete. This answer can be referred.

    How to wait for reindexing in elasticsearch?