ElasticSearch and SpringData: FindAll and OrderBy

4.1k views Asked by At

I need to get all documents, ordered by a certain fied (parent in my case).

In my ItemRepository I added following signature:

public List<Item> findAllOrderByParent();

But by invoking it, I get a

org.springframework.web.util.NestedServletException: Request processing failed;
nested exception is
  org.springframework.data.repository.query.ParameterOutOfBoundsException: 
    Invalid parameter index! You seem to have declare too little query method parameters!

The same postponing Asc or Desc to the method name.

Somewhere I read the correct syntax should be the following (note the extra By just after findAll):

public List<Item> findAllByOrderByParent();

Here I get a

NullPointerException
Caused by: 
java.lang.NullPointerException
    at org.springframework.data.elasticsearch.core.ElasticsearchTemplate.count(ElasticsearchTemplate.java:333)
    at org.springframework.data.elasticsearch.repository.query.ElasticsearchPartQuery.execute(ElasticsearchPartQuery.java:54)
...

I'm excluding other issues because declaring a method like public List<Item> findByNameOrderByParent(); everithing works fine.

Do you have an idea to proceed?

Thank you

1

There are 1 answers

1
spauny On BEST ANSWER

This might be a bit late but since the problem is still there, to get around it I just used the findAll method using a Sort object as param:

List<Item> findAll(Sort sort);

and you call it:

List<Item> items = this.itemRepository.findAll(new Sort(new Sort.Order(Sort.Direction.DESC, "name")));

The "name" property you can extract it in a constant or make your service's listItems method to support dynamic sort and send the sort field as a parameter.

You can also have a look at this article: http://maciejwalkowiak.pl/blog/2012/05/09/sorting-spring-data-mongodb-collections-using-orderby/