I am trying to query for sub document that can be anywhere inside a tree like document, based on a value within that sub document.
Consider the following document:
{
"documentType": "form",
"name": "Form 1",
"fields": [
{
"label": "group",
"value": null
"fields": [
{
"label": "age",
"value": 27
}
]
},
{
"label": "date",
"value": "24-04-2017"
},
{
"label": "age",
"value": 25
}
]
}
Within “fields”, each field object can have a “fields” key, that can contain more fields (recursively).
For example, i would like to query for all sub documents that have the label
= “age”, resulting into 2 results:
[
{
"label": "age",
"value": 27
},
{
"label": "age",
"value": 25
}
]
not sure if it’s possible, but might as well ask
vsr1
June 11, 2018, 3:58pm
2
Use ARRAY constructor with WITHIN which will do recursive of all nested objects
ARRAY v FOR v WITHIN fields WHEN v.label = “age” END
INSERT INTO default VALUES ("d01", { "documentType": "form", "name": "Form 1", "fields": [ { "label": "group", "value": null, "fields": [ { "label": "age", "value": 27 } ] }, { "label": "date", "value": "24-04-2017" }, { "label": "age", "value": 25 } ] });
SELECT ARRAY v FOR v WITHIN fields WHEN v.label = "age" END FROM default;
1 Like
Awesome, thanks @vsr1 !
Now that I have a working example, it leads me to another question: Is is possible to add a Global Secondary Index for this query?
I have been trying to create one, after reading:
Couchbase 4.5 is released!! Part2 is a continuation of this blog and it includes covering array indexes, support for more operators such as UNNEST, ALL, ANY AND EVERY etc., Do you have documents with embedded arrays and need an efficient...
Est. reading time: 5 minutes
and
https://developer.couchbase.com/documentation/server/current/n1ql/n1ql-language-reference/indexing-arrays.html
However, I haven’t been able to succesfully create an index for it.
Ideally, I want to be able to run your example query without having a primary index running.
vsr1
June 14, 2018, 1:24pm
4
when WITHIN used in side array bindings it is not possible