1

When I use the Cosmos website to execute the query

SELECT VALUE COUNT(1) FROM c WHERE 1623736778 <= c.timestamp AND 1623736779 <= c.timestamp

I get

[
    4
]

in the "Results" window. This makes sense, since executing

SELECT * FROM c WHERE 1623736778 <= c.timestamp AND 1623736779 <= c.timestamp

returns 4 entries from my database.

How do I receive the result "4" (from SELECT VALUE COUNT(1) ...) in my backend code using Java with Spring Boot? In other words, given any Cosmos repository, how does one access the return from a SELECT VALUE COUNT ... query using Java?


For context, I have a repository class that looks like this:

import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.azure.spring.data.cosmos.repository.Query;
import com.azure.spring.data.cosmos.repository.ReactiveCosmosRepository;
import reactor.core.publisher.Flux;
import myownpackage.MyEntity;

@Repository
public interface MyRepository extends ReactiveCosmosRepository<MyEntity, String> {
    ...
    @Query(value = "SELECT * FROM c WHERE @startTime <= c.timestamp AND c.timestamp <= @endTime")
    Flux<MyEntity> findInRange(
        @Param("startTime") Long startTime,
        @Param("endTime") Long endTime
    );

    @Query(value = "SELECT VALUE COUNT(1) FROM c WHERE @startTime <= c.timestamp AND c.timestamp <= @endTime")
    Flux<MyEntity> countInRange(
        @Param("startTime") Long startTime,
        @Param("endTime") Long endTime
    );
}

In my service class I try to do

@Autowired private MyRepository repo;
int totalCount = repo.countInRange(1623736778, 1623736779).collectList().block().get(0);

so that totalCount == 4, but this causes an error saying "incompatible types: myownpackage.MyEntity cannot be converted to int." Changing the return type of countInRange to int gives "int cannot be dereferenced." There's no issue accessing results from findInRange() in this manner. I used a logger (from slf4j) to run

LOGGER.info("\n\nHere is the type we need to know: {}\n\n",
repo.countInRange(1623736778,1623736779).getClass().getCanonicalName());

which logs "Here is the type we need to know: reactor.core.publisher.FluxMap", but Googling reactor.core.publisher.FluxMap doesn't reveal any documentation similar to Flux's documentation.

jskattt797
  • 231
  • 2
  • 10

1 Answers1

1

The result is of primitive type int and not an Object. Dereferencing is the process of accessing the value referred to by a reference . Since, int is already a value (not a reference), it can not be dereferenced. Try changing the return type as Flux<Integer>

devReddit
  • 2,696
  • 1
  • 5
  • 20
  • I found success using the return type Flux (and swapping "int totalCount = ..." out for "Long totalCount = ... "). – jskattt797 Jul 22 '21 at 02:19