Couchbase N1QL query to get id of documents connected as a linked list

Viewed 38

I have collection that contain documents with the following structure

{
    id: "doc01",
    property1: "",
    nextCollection: "doc02"
    prevCollection: null
},
{
    id: "doc02",
    property1: "",
    nextCollection: "doc03",
    prevCollection: "doc01"
},

{
    id: "doc03",
    property1: "",
    nextCollection: null,
    prevCollection: "doc02"
},

The above code contains three documents. What I want to do is to write a N1QL query that gets all documents in the list given doc01 id. That is I want the return type to be

[
{
    id: "doc01",
    property1: "",
    nextCollection: "doc02"
    prevCollection: null
},
{
    id: "doc02",
    property1: "",
    nextCollection: "doc03",
    prevCollection: "doc01"
},

{
    id: "doc03",
    property1: "",
    nextCollection: null,
    prevCollection: "doc02"
}
]

How to write such query?

1 Answers

N1QL doesn't support hierarchical queries or recursive CTE. Instead of single N1QL statement you can achieve this with the following options

  1. Using N1QL UDF checkout https://www.couchbase.com/blog/traverse-hierarchy-user-defined-functions-in-7-1/

  2. From application using SDK (As you know document keys you can use collection.get() avoid N1QL all together). You can even stop when recursive list detected circular and if list is huge control how many you want in the list.

    Get the first document and add to the list
    In loop until nextDocument is known value
        get the document of key nextDocument
        add to the list
    
Related