'how to migrate search query from ElasticsearchRepository to ElasticsearchOperations
My repository class uses the queries by using the standard method name findByxxx. It also has custom query using NativeSearchQueryBuilder.
Since search() methods have been removed from ElasticsearchRepository, I will create corresponding class to use ElasticsearchOperations. My code is like below.
@Repository
public interface BookRepository extends ElasticsearchRepository<Book, String> {
public Optional<Book> findById(String bookId);
//default public Page<Book> fetchBooksForUser(String userId, Pageable pageable) {...}
}
@Service
public class BookOperation{ //new class
@Autowired
private ElasticsearchOperations elasticsearchOperations;
public Page<Book> fetchBooksForUser(String userId, Pageable pageable) {..use elasticsearchOperations...}
}
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookRepository bookRepository;
@Autowired
private BookOperation bookOperation;
//some methods use bookRepository, some methods use formsPackageOperation
}
I have more than 20 Repository classes. I don't want to repeat this 20 times. Is there a better to do this?
Solution 1:[1]
You just need to create a repository fragment, check tyhe documentation at https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#repositories.custom-implementations.
In the interface you define the method you need and in the Impl file you implement the necessary logic - you can just inject an ElasticsearchOperations into the implementations class.
As for the changes in your existing repositories: You just need to add your custom interface to the implements clause.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | P.J.Meisch |
