3

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

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

what about for updating and searching?
For updates I think you have update() and for searching a lot other methods from the same template (query, count, queryForPage etc). I suggest having a look at the source code of ElasticSearchTemplate.
3
Employee employee = new Employee(1,"Mike");

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

elasticsearchTemplate.index(indexQuery);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.