Search code examples
elasticsearchspring-data-elasticsearchelasticsearch-java-api

ElasticSearch Java API vs ElasticsearchTemplate


With ElasticSearchTemplate I can easily create index out of a simple entity class. Say I want to save the Book.java:

@Document(indexName = "bookshop", type = "book", shards = 2, replicas = 2, refreshInterval = "-1")
public class Book {

    @Id
    private String id;
    @Field(type = FieldType.String, store = true)
    private String title;
}

Its enough just to make:

    elasticsearchTemplate.createIndex(Book.class);
    elasticsearchTemplate.putMapping(Book.class);
    elasticsearchTemplate.refresh(Book.class);

Can this be achieved with pure ES Java API without the spring-data-elasticsearch and operations on Strings(JSON)?


Solution

  • Actually Java API requires the JSON however there are ES helpers so the code can be as follows:

    CreateIndexResponse createIndexRequestBuilder = client().admin().indices()
                    .prepareCreate(INDEX_NAME)
                    .setSource(XContentFactory.jsonBuilder()
                            .startObject()
                            .field("title", "My Title 1")
                            .endObject()
                    )
                    .setSettings(
                            Settings.settingsBuilder()
                                    .put("index.number_of_shards", 2)
                                    .put("index.number_of_replicas", 2)
                    )
                    .execute()
                    .actionGet();