user962206
user962206

Reputation: 16147

How to save an object using Spring Data ElasticSearchTemplate

How do I save an entity using Spring Data ElasticSearchTemplate? Can't find it in the documentation.

Upvotes: 3

Views: 8927

Answers (2)

Ravi Soni
Ravi Soni

Reputation: 71

Employee employee = new Employee(1,"Mike");

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

elasticsearchTemplate.index(indexQuery);

Upvotes: 3

Andrei Stefan
Andrei Stefan

Reputation: 52366

I believe index() is the method for saving an entity in Elasticsearch using the template.

Take a look at this sample application that uses .index() to prepare a JUnit test:

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

You can, also, use bulkIndex for multiple indexes making use of Elasticsearch's bulk index feature.

Upvotes: 5

Related Questions