When developing with elasticsearch one of the first problems is how to get tests in place that use a fast server instance. It should be easily embeddable in your tests and reliable.
Therefore, you have to take care of two things: disable the http module because you do not want to have network communication in your tests and configure a writable data directory. You could also use elasticsearch with full in-memory mode but this is not as stable as you may think. Just let Lucene write on disk in a temporary directory.
publicclassEmbeddedElasticsearchServer{privatestaticfinalStringDEFAULT_DATA_DIRECTORY="target/elasticsearch-data";privatefinalNodenode;privatefinalStringdataDirectory;publicEmbeddedElasticsearchServer(){this(DEFAULT_DATA_DIRECTORY);}publicEmbeddedElasticsearchServer(StringdataDirectory){this.dataDirectory=dataDirectory;ImmutableSettings.BuilderelasticsearchSettings=ImmutableSettings.settingsBuilder().put("http.enabled","false").put("path.data",dataDirectory);node=nodeBuilder().local(true).settings(elasticsearchSettings.build()).node();}publicClientgetClient(){returnnode.client();}publicvoidshutdown(){node.close();deleteDataDirectory();}privatevoiddeleteDataDirectory(){try{FileUtils.deleteDirectory(newFile(dataDirectory));}catch(IOExceptione){thrownewRuntimeException("Could not delete data directory of embedded elasticsearch server",e);}}}
By using getClient you can get access to the embedded server. And as you can see the data directory is deleted when the embedded elasticsearch server will be stopped. With this class available you can write an abstract test helper class for your test infrastructure.
Test helper class for an embedded elasticsearch server per test