如何使用Spring Data ElasticSearchTemplate
保存实体?无法在文档中找到它。
答案 0 :(得分:4)
我相信index()
是使用模板的method for saving an entity in Elasticsearch。
看一下使用.index()准备JUnit测试的this sample application:
public void before() {
elasticsearchTemplate.deleteIndex(Article.class);
elasticsearchTemplate.createIndex(Article.class);
elasticsearchTemplate.putMapping(Article.class);
elasticsearchTemplate.refresh(Article.class, true);
IndexQuery article1 = new ArticleBuilder("1").title("article four").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addAuthor(JONATHAN_YAN).score(10).buildIndex();
IndexQuery article2 = new ArticleBuilder("2").title("article three").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addPublishedYear(YEAR_2000).score(20).buildIndex();
IndexQuery article3 = new ArticleBuilder("3").title("article two").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addPublishedYear(YEAR_2001).addPublishedYear(YEAR_2000).score(30).buildIndex();
IndexQuery article4 = new ArticleBuilder("4").title("article one").addAuthor(RIZWAN_IDREES).addPublishedYear(YEAR_2002).addPublishedYear(YEAR_2001).addPublishedYear(YEAR_2000).score(40).buildIndex();
elasticsearchTemplate.index(article1);
elasticsearchTemplate.index(article2);
elasticsearchTemplate.index(article3);
elasticsearchTemplate.index(article4);
elasticsearchTemplate.refresh(Article.class, true);
}
您也可以bulkIndex
for multiple indexes使用Elasticsearch's bulk index feature。
答案 1 :(得分:2)
Employee employee = new Employee(1,"Mike");
IndexQuery indexQuery = new IndexQueryBuilder()
.withId(employee.getId())
.withIndexName(indexName).withObject(employee)
.withType(indexName).build();
elasticsearchTemplate.index(indexQuery);