Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start elasticsearch 5.1 embedded in my java application?

With elasticsearch 2.x I used the following code to launch an embedded Node for testing:

@Bean
public Node elasticSearchTestNode() {
    return NodeBuilder.nodeBuilder()
            .settings(Settings.settingsBuilder()
                    .put("http.enabled", "true")
                    .put("path.home", "elasticsearch-data")
                    .build())
            .node();
}

This does not compile any more. How can I start an embedded node in 5.x ?

like image 982
Bastian Voigt Avatar asked Dec 23 '16 09:12

Bastian Voigt


1 Answers

Embedding elasticsearch is no longer officially supported, and it's a bit more complicated than in 2.x, but it works.

You need to add some dependencies:

    <dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch</artifactId>
        <version>5.1.1</version>
        <scope>test</scope>
    </dependency>
    <dependency><!-- required by elasticsearch -->
        <groupId>org.elasticsearch.plugin</groupId>
        <artifactId>transport-netty4-client</artifactId>
        <version>5.1.1</version>
        <scope>test</scope>
    </dependency>
    <dependency><!-- required by elasticsearch -->
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.7</version>
    </dependency>

And then launch a node like this:

@Bean
public Node elasticSearchTestNode() throws NodeValidationException {
    Node node = new MyNode(
            Settings.builder()
                    .put("transport.type", "netty4")
                    .put("http.type", "netty4")
                    .put("http.enabled", "true")
                    .put("path.home", "elasticsearch-data")
                    .build(),
            asList(Netty4Plugin.class));
    node.start();
    return node;
}

private static class MyNode extends Node {
    public MyNode(Settings preparedSettings, Collection<Class<? extends Plugin>> classpathPlugins) {
        super(InternalSettingsPreparer.prepareEnvironment(preparedSettings, null), classpathPlugins);
    }
}
like image 186
Bastian Voigt Avatar answered Nov 03 '22 00:11

Bastian Voigt