Search code examples
javacloudant

Cloudant different document structure in the same db


I am new in cloudant and I have two different document structure in the same db as below for example.

I want to know how to list all documents with specific structure? Another question how can i list all document of type document 2 and related to reference to a specific document of type document 1 using Java?

e.g.:

Document1

{
"_id" : "dec_1",
"name" : "value",
"type" : "Value"
}

Document 2 : which hold reference to Document 1

{
"_id" : "ship_1",
"decRef" : "dec_1",
"size" : "1.0"
}

Solution

  • The canonical way to achieve this in Cloudant/CouchDB is to use a discriminator field which specifies the document type, and then use a view. For example:

    Document 1:

    {
        "_id": "dec_1",
        "name": "value",
        "type": "Value",
        "doctype": "dec"
    }
    

    Document 2:

    {
        "_id" : "ship_1",
        "decRef" : "dec_1",
        "size" : "1.0",
        "doctype": "ship"
    }
    

    Then create a view where the map looks something like:

    function (doc) {
       if (doc && doc.doctype) {
          emit(doc.doctype, null);
       }
    }
    

    Now you can list all documents of a given type by hitting the view

    curl "https://U:P@U.cloudant.com/DB/_design/DDOC/_view/VIEW?key=\"dec\""
    {"total_rows":1,"offset":0,"rows":[ 
        {"id":"dec_1","key":"dec","value":null}
    ]}