3

如何使用 Spring Data 保存实体ElasticSearchTemplate?在文档中找不到。

4

2 回答 2

5

我相信index()是使用模板在 Elasticsearch 中保存实体的方法。

看看这个使用 .index() 准备 JUnit 测试的示例应用程序:

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

您还可以利用Elasticsearch 的批量索引功能bulkIndex用于多个索引

于 2014-06-25T06:50:00.897 回答
3
Employee employee = new Employee(1,"Mike");

IndexQuery indexQuery = new IndexQueryBuilder()
                .withId(employee.getId())
                .withIndexName(indexName).withObject(employee)
                .withType(indexName).build();

elasticsearchTemplate.index(indexQuery);
于 2016-10-12T06:43:18.420 回答