@Test public void shouldReturnObjectForGivenId() { // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); sampleEntity.setId(documentId); sampleEntity.setMessage("some message"); sampleEntity.setVersion(System.currentTimeMillis()); IndexQuery indexQuery = new IndexQuery(); indexQuery.setId(documentId); indexQuery.setObject(sampleEntity); elasticsearchTemplate.index(indexQuery); // when GetQuery getQuery = new GetQuery(); getQuery.setId(documentId); SampleEntity sampleEntity1 = elasticsearchTemplate.queryForObject(getQuery, SampleEntity.class); // then assertNotNull("not null....", sampleEntity1); assertEquals(sampleEntity, sampleEntity1); }
@Test public void shouldDoPartialUpdateForExistingDocument() { // given String documentId = randomNumeric(5); String messageBeforeUpdate = "some test message"; String messageAfterUpdate = "test message"; SampleEntity sampleEntity = new SampleEntity(); sampleEntity.setId(documentId); sampleEntity.setMessage(messageBeforeUpdate); sampleEntity.setVersion(System.currentTimeMillis()); IndexQuery indexQuery = new IndexQuery(); indexQuery.setId(documentId); indexQuery.setObject(sampleEntity); elasticsearchTemplate.index(indexQuery); elasticsearchTemplate.refresh(SampleEntity.class, true); IndexRequest indexRequest = new IndexRequest(); indexRequest.source("message", messageAfterUpdate); UpdateQuery updateQuery = new UpdateQueryBuilder() .withId(documentId) .withClass(SampleEntity.class) .withIndexRequest(indexRequest) .build(); // when elasticsearchTemplate.update(updateQuery); // then GetQuery getQuery = new GetQuery(); getQuery.setId(documentId); SampleEntity indexedEntity = elasticsearchTemplate.queryForObject(getQuery, SampleEntity.class); assertThat(indexedEntity.getMessage(), is(messageAfterUpdate)); }
@Test public void shouldDoUpsertIfDocumentDoesNotExist() { // given String documentId = randomNumeric(5); String message = "test message"; IndexRequest indexRequest = new IndexRequest(); indexRequest.source("message", message); UpdateQuery updateQuery = new UpdateQueryBuilder() .withId(documentId) .withDoUpsert(true) .withClass(SampleEntity.class) .withIndexRequest(indexRequest) .build(); // when elasticsearchTemplate.update(updateQuery); // then GetQuery getQuery = new GetQuery(); getQuery.setId(documentId); SampleEntity indexedEntity = elasticsearchTemplate.queryForObject(getQuery, SampleEntity.class); assertThat(indexedEntity.getMessage(), is(message)); }
@Override public <T> T queryForObject(GetQuery query, Class<T> clazz, GetResultMapper mapper) { ElasticsearchPersistentEntity<T> persistentEntity = getPersistentEntityFor(clazz); GetResponse response = client .prepareGet( persistentEntity.getIndexName(), persistentEntity.getIndexType(), query.getId()) .execute() .actionGet(); T entity = mapper.mapResult(response, clazz); return entity; }