ElasticSearch Java API与ElasticsearchTemplate

时间:2016-08-27 07:46:07

标签: elasticsearch spring-data-elasticsearch elasticsearch-java-api

使用ElasticSearchTemplate,我可以轻松地从简单的实体类中创建索引。说我想保存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;
}

足以使:

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

这可以通过纯ES Java API实现,而不需要spring-data-elasticsearch和字符串操作(JSON)吗?

1 个答案:

答案 0 :(得分:1)

实际上Java API需要JSON但是有ES helpers所以代码可以如下:

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();