Retrieving separate documents as one object

42 Views Asked by At

I have two basic document types:

  • Patient with fields name and number;
  • Analysis with fields that consist of 3 arrays, date of analysis, a bunch of floats and a patientId, linking it to the Patient, so there's a 1:M relationship between Patient and Analysis.

I'm using Ektorp as a driver. Right now there are two POJOs, reflecting the documents, and Patient POJO also has a Set<Analysis>, marked by @DocumentReferences annotation (which I don't actually need yet, but might use later to show all analyses for one patient, for example).

However, what I want to do is use pagination to populate TableView with rows, containing info about both Patient AND Analysis, sorted by date of analysis in descending order. Right now, my only idea is to

  1. Query CouchDB for all Analysis documents sorted by date (using pagination via PageRequest in Ektorp)
  2. Then for each analysis query db for patients with patientId
  3. Make a separate class representing a row in table with fields for both patient and analysis, then create an object of that class using retrieved Analysis and Patient objects.

In code it would look somewhat like this:

PageRequest pageRequest = PageRequest.firstPage(5);

ViewQuery query = new ViewQuery()
    .designDocId("_design/analysis")
    .viewName("by_date")
    .descending(true)
    .includeDocs(true);

Page<Analysis> result = db.queryForPage(query, pageRequest, Analysis.class);
for(Analysis analysis : result) {
    Patient patient = db.find(Patient.class, analysis.getPatientId());
    Row row = new Row(patient, analysis);
    //TODO: ...Populate TableView...
}

This all sounds very cumbersome. Is there a better way to do this? Can I deserialize data I need in one go (or at least in one query)? I know there's a way to use {_id: doc.patientId} as a value in emit() function to return Patient for each Analysis when querying with parameter include_docs=true, but I'm not sure how to use that to my advantage.

I could just embed Patient in Analysis, but then I would have to change every Analysis document if there's a change in Patient, so that's not a good solution. I've read these two paragraphs of documentation several times over, but I can't for the life of me figure out how to implement them with Ektorp. Any help would be appreciated.

0

There are 0 best solutions below