We’re trying to write our first indexed join, and attempted to following the beer-sample example as close as possible:
https://developer.couchbase.com/documentation/server/current/n1ql/n1ql-language-reference/from.html
Here’s the query we came up with, but it’s not working properly. The end-goal is being able to use the index on the RHS to quickly filter the rows on the LHS. However it’s returning zero results:
SELECT visit.visitNumber, chg.amount
FROM cloud_med visit
LEFT JOIN cloud_med charge ON KEY "visit-client_name-" || charge.visitNumber FOR visit
UNNEST charge.visitCharges chg
WHERE charge.`type` = "charges"
AND SUBSTR(visit.dischargeDate >= "2016-12-01",0,7) AND SUBSTR(visit.dischargeDate <= "2016-12-02",0,7)
AND meta(visit).id LIKE "visit-%" AND visit.patientClass LIKE "I%" AND visit.drgCode != ""
AND visit.tenantName = "client_name"
Here are the applicable indexes:
CREATE INDEX idx_dischargeDate ON cloud_med(tenantName,dischargeDate) WHERE meta().id) like "visit-%" and patientClass like "I%" and drgCode != ""
CREATE INDEX idx_charge_visitNumber ON cloud_med(visitNumber) WHERE `type` = "charges"
And finally, here’s a snapshot of the documents in play for this query. This is the “charges” document with the nested array of charges. In addition to their being MANY nested charges, there will also be MANY charge documents. Meaning, page 0 has a document key as listed below. Page 1 would be charges-client_name-123456789-1, Page 2 would be charges-client_name-123456789-2, etc.
{
"docID": "charges-client_name-123456789",
"type": "charges",
"pageNumber": 0,
"visitNumber": "345000880023",
"visitCharges": [
{
"amount": 117.41,
"chargeCode": "138169",
"visitNumber": "345000880023"
},
{
"amount": 1296,
"chargeCode": "114787",
"visitNumber": "345000880023"
}
]
}
Here’s the “visit” document. This will be the SINGLE side of the join (meaning 1 visit per many charge documents).
{
"docID": "visit-client_name-123456789",
"type": "visit",
"accountBalance": 39387.45,
"admitDate": "2016-09-20T15:57:00-07:00",
"visitNumber: "123456789"
}