I want to use mongo and ElasticSearch in my projects, and I also like to use Spring Data Mongo and Spring Data ElasticSearch, but both have their own repositories and model specifications, how to use them together?
There are several options:
Use the same model class for Mongo and ElasticSearch?
@Document
@Document
public class Book{
@Id
private String id;
}
But there are some inconsistencies in Spring Data Mongo and Spring Data ElasticSearch, such as the Geo field type.
Define a different model for Mongo and ElasticSearch and copy the state of the data from the Mongo model and create an index when creating a new model.
Any suggestion here?
I would like to use option 2 in projects.
- Save the mongo document as usual.
- JMS/AMQP/Reactor Elasticsearch ElasticSearch.
- ElasticSearch.
5/15/2016
.
Spring ApplicationEvent .
, Mongo .
@Component
public class Publisher implements ApplicationEventPublisherAware {
private static final Logger LOG = LoggerFactory.getLogger(Publisher.class);
@Autowired
PostRepository repository;
private ApplicationEventPublisher publisher;
public Publisher() {
}
public void savePost(Post post) {
Post saved = repository.save(post);
this.publisher.publishEvent(saved);
LOG.debug("saved post data in mongo@" + saved);
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
}
, ElasticSearch.
@Component
public class Receiver {
private static final Logger LOG = LoggerFactory.getLogger(Receiver.class);
@Autowired
ESPostRepository repository;
@EventListener
public void onPostSaved(Post savedPost) {
LOG.debug("=================received post data============== @\r\n"+ savedPost);
ESPost doc=new ESPost();
doc.setId("1");
doc.setTitle(savedPost.getTitle());
doc.setContent(savedPost.getContent());
repository.save(doc);
}
}
JMA/AMQP ApplicationEvent.
, ElasticSearch - / .