As you are using FHIR, wich has a nice REST search API, there is no need to implement your own query.
{{baseurl}}/Observation?device:Device=123&_sort=-_lastUpdated&_count=1
gets you the latest Observation of the Device with the ID of 123.
FHIR search api
edit: as you are also using the HAPI Client, your query code would look like this:
Bundle results = myFhirCtx.newRestfulGenericClient("yourFHIRbaseURL")
.search()
.forResource(Observation.class)
.where(Observation.DEVICE.hasId("123"))
.sort().descending(Observation.DATE)
.count(1)
.returnBundle(Bundle.class)
.execute();
The GET from above searches for the latest updated Observation of a device, the JAVA code gets the newest Observation based on its date. I think you meant the second.
obsolete as this is returning the newest n Observation over all devices not N for every Device, for multiple Devices:
If you want to query multiple devices at once you could either aggregate the query by querying Observations with Devices of Type X, or the latest Observation for Devices of Manufacturer or Model, see: search parameters for the Device resource
If you want to query the latest n Observations of a Set of known device IDs you can use the OR operator, which is just a colon.
{{baseurl}}/Observation?device:Device=123,345,678&_sort=-_lastUpdated&_count=n
in hapi client code:
Bundle results = myFhirCtx.newRestfulGenericClient("ttt")
.search()
.forResource(Observation.class)
.where(Observation.DEVICE.hasAnyOfIds(new ArrayList<String>(Arrays.asList("123", "345", "678" ))))
.sort().descending(Observation.DATE)
.count(n)
.returnBundle(Bundle.class)
.execute();
Conclusion
If you want to have the n latest Observation of each device of a device subset you can either:
- use the first query of this example multiple times
- or if you prefer a single REST call you can batch these GET calls together in batch bundle like in this example: Batch Bundle search. This will return a batch response bundle with entries for each search.