1

I am looking for a way to pass the limit to the mongo query in ReactiveCrudRepository

I tried adding "First2" to the method name but I'm still getting all the results.

What I'm really looking for is a way to pass the value of the 'limit' to the method, passing it in request as @RequestParam int limit

This is my code for the repository

public interface ReactiveUserRepository
        extends ReactiveCrudRepository<User, String> {


    @Query("{ 'roles': ?0 }")
    Flux<User> findFirst2ByRole(String role);
}

And this is controller method:

@GetMapping(path = "/byrole", produces = "application/stream+json")
    Flux<User> getByRole(@RequestParam String role) {
        return users.findFirst2ByRole(role).doOnNext(next -> {
            System.out.println("Next user=" + next.getAssocId());
        }).switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND, String.format("No users found with role=%s", role))));
    }
cchantep
  • 9,118
  • 3
  • 30
  • 41
Dmitri
  • 34,780
  • 9
  • 39
  • 55

2 Answers2

1

limitRequest(long) on a Flux may also be worth to have a look at: https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html#limitRequest-long-

it can be used as a stricter form of take(long)

As it does cap the request amount that goes to the upstream source. This may prevent the reactive MongoDB driver from requesting/loading a huge batch of data when only a limited number is needed.

When using limitRequest, make sure that the provided long is "> 0" (<0 makes no sense and =0 results in a never completing Flux)

Philipp
  • 96
  • 2
  • 5
  • I think this works; anyone could play with `log()` on in the pipeline, experiment with/without `limitRequest()`. – WesternGun Apr 01 '20 at 13:36
0

try to use reactor method users.findFirst2ByRole(role).take(2) as well you can use skip() if needed

Ricard Kollcaku
  • 1,622
  • 5
  • 9