Skip to content
Advertisement

How to search with optional data and list data in ElasticsearchRepository?

I am using spring-data-elasticsearch and I have a class as follows,

@Document(indexName = "sample")
class Sample {

   @Id
   private String id;
   private String n_id;
   private String b_ref;
   private String r_ref;
   private Status status;
}

Above is persisted to elasticsearch. And I have the following method to find data in it.

List<Sample> getAll(String n_id, Optional<String> b_ref, Optional<String> r_ref, List<Status> statuses);

But the challenge I am facing is I have 2 Optional fields and 1 List field that need to check if contains the status. I tried multiple ways in ElasticsearchRepository but none of them worked.

How can I build the query for the above scenario?

Advertisement

Answer

You can implement this using a CriteriaQuery (operations is an ElasticsearchOperations implementation injected in your class):

    List<Sample> getAll(String n_id, Optional<String> b_ref, Optional<String> r_ref, List<Status> statuses) {

        Criteria criteria = new Criteria("nid").is(n_id).and("status").in(statuses);

        if (b_ref.isPresent()) {
            criteria = criteria.and("b_ref").is(b_ref.get());
        }

        if (r_ref.isPresent()) {
            criteria = criteria.and("r_ref").is(r_ref.get());
        }

        SearchHits<Sample> searchHits = operations.search(new CriteriaQuery(criteria), Sample.class);

        // to only get the objects without hit information
        return searchHits.stream().map(SearchHit::getContent).collect(Collectors.toList());
    }
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement