Is there a way to use Specifications in ElasticsearchRepository?
Asked Answered
T

2

12

I've implemented the Specification pattern for filtering some of my JpaRepositories. After I have implemented a Specification, I can use it with a JpaRepository like this: Page<Entity> page = entityJpaRepository.findAll(entitySpecification, pageable)

Is there a feature, or planned feature, for supporting Specifications in ElasticsearchRepository?

Tussock answered 2/12, 2015 at 20:7 Comment(0)
A
1

I understand your pain however the thing is that Specification interface belongs to the JPA API that currently none of the Elastic Search Spring Data repositories implement and I don't think they will.

If you really want to use them you should rather migrate from ElasticsearchRepository coming from spring-data-elasticsearch into JPA-based repositories.

Did not try to use JPA together with ElasticSearch myself but noticed that some people does it, check out this link:

https://programmertoday.com/spring-boot-elastic-search-with-spring-data-jpa/

Adalineadall answered 21/4, 2020 at 8:57 Comment(0)
P
0

I don't know about Specifications, but Spring provides a bean ElasticsearchOperations which has a "search" method which accepts org.springframework.data.elasticsearch.core.query.CriteriaQuery which is similar to standard hibernate Criteria. Try mapping Specification to CriteriaQuery.

@Service
@RequiredArgsConstructor
public class FooService {

  private final ElasticsearchOperations elasticsearchTemplate; // autowired bean

  public void search() {
    Criteria criteria = new Criteria();
    criteria.and(new Criteria("foo").is(foo));
    criteria.and(new Criteria("bar").in(bars));
    CriteriaQuery criteriaQuery = new CriteriaQuery(criteria);
    elasticsearchOperations.search(criteriaQuery, 
        FooElasticEntity.class).stream()
           .map(SearchHit::getContent)
           .collect(Collectors.toList())
  }
}

Also it's worth to note that there is a SearchHitSupport utility class which adds support for Pageable.

Provincial answered 7/11, 2022 at 15:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.