I was browsing the Couchbase forums and I came across a question regarding queries against array data in Couchbase. Coming from a relational database, I too once struggled to grasp the concept of querying complex formatted JSON data with SQL.
How do you query within these embedded NoSQL documents? There are numerous ways, none of which are particularly difficult. We’re going to examine some of the complex query possibilities.
In case you’re curious about the question I stumbled upon, it can be found here. The user wanted to know how to query for objects that were nested in an array for a single document. The proposed document model looked similar to this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
{ "id": "order-1", "type": "order", "items": [ { "id": "pokemon-blue", "type": "gaming", "name": "Pokemon Blue" }, { "id": "ms-surface-book", "type": "computing", "name": "Microsoft Surface Book" } ] } |
The end goal was to be able to get each object in a query based on a WHERE
condition that included the nested type
property.
One way to do this is to write a N1QL query that looks like the following:
1 2 3 4 5 |
SELECT forum.id, forum.type, item FROM forum UNNEST items AS item WHERE item.type != "computing"; |
In the above query we are performing a SELECT
from a Couchbase Bucket called forum
and flattening the array using the UNNEST
keyword. The flattened result set would look like the following before applying the WHERE
condition:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
[ { "id": "order-1", "item": { "id": "pokemon-blue", "name": "Pokemon Blue", "type": "gaming" }, "type": "order" }, { "id": "order-1", "item": { "id": "ms-surface-book", "name": "Microsoft Surface Book", "type": "computing" }, "type": "order" } ] |
The WHERE
condition will return us a single result instead of two, where the single result is of a gaming
type as per our query.
So is this the only way to accomplish what we’ve just done? Absolutely not!
Take the following N1QL query:
1 2 3 4 5 |
SELECT forum.id, forum.type, ARRAY item FOR item IN forum.items WHEN item.type != 'computing' END AS item FROM forum |
In the above query we are not first flattening the array in Couchbase with an UNNEST
operation. Instead we are using one of the collection operators to find array items that meet our criteria.
Are there other ways to get the job done? Of course there are, but these two should be enough to get you started when it comes to querying arrays in Couchbase with N1QL and the UNNEST
keyword.
If you need more help with N1QL, check out the Couchbase Developer Portal for other examples.
[…] a recent article, I wrote about flattening and querying arrays in Couchbase using N1QL. That article was inspired by a popular question in the Couchbase Forums. After publishing the […]
Is there a way for use to NEST these results into an array? For example:
{
"id": "order-1",
"type": "order",
"items": [
{
"id": "pokemon-blue",
"type": "gaming",
"name": "Pokemon Blue"
}
]
}