Search code examples
unit-testingelasticsearchdelay

How to deal with elasticsearch delay when doing unit test?


There're some delay in elasticsearch from requesting to index a document to the document become searchable. I want to know how to deal with this in a unit test, for example, first index a document, then check if it is really indexed. Now I simply use a Thread.sleep() call to delay some time(I'm using a plain junit class), say 2 second. Is this OK? Or there're better solutions?


Solution

  • You can refresh the indeces after writting to elasticsearch.

    By doing,

    $ curl -XPOST 'http://localhost:9200/index1,index2/_refresh'
    

    The refresh API allows to explicitly refresh one or more index, making all operations performed since the last refresh available for search. The (near) real-time capabilities depend on the index engine used. For example, the internal one requires refresh to be called, but by default a refresh is scheduled periodically.

    See @Elasticsearch website

    using java api,

     client.admin().indices().prepareRefresh().execute().actionGet()
    

    using the JavaScript client :

    client.indices.refresh({index : 'myIndex'});