Basic Design: One Database instance per JSON model type?


Hopefully this newbie question is easy to answer: should I have one Database instance per JSON model type?

The Database.getCount() method certainly infers that a Database only stores 1 kind of object, as does the fact that indexes are based only on a property name, which of course would not necessarily be unique across multiple JSON model types.

I could not find anything explicit in the getting started docs… Maybe I didn’t look hard enough?

I’m running Xamarin.Forms with the latest Nuget packages for everything, including Couchbase Lite 2.0.3



No; usually you only need a single database for an application. A database does only store JSON documents, but you can use those to store any number of different types of records. The common convention is to use a type property with a string value, to indicate the different types of documents.


I have a follow-up question. Imagine I have two types of documents in my database. 1 million documents of type A and 10000 documents of type B. Documents of type B have property ‘name’ as well as documents of type A. Now I want to create an index on property ‘name’ but only for documents of type B, since this is what I’m going to query, I don’t need documents of type A to pollute my index. Is there any way to acheive this in Couchbase Lite 2?


No, indexes cannot be predicated. You either get all or nothing. If it has really become a performance problem then you can evaluate either renaming the indexed key or splitting into two databases.



A simple solution/workaround would be to use a different property for B. Say instead of ‘name’ call it name_ or name_b, whatever. This has another (sometimes useful) benefit that for type B ‘name’ is known to be null, and vice versa.


This sounds like a really horrible solution - overcoming platform limitations with changes to domain model names. Looking forward to partial indexes.


You can define an index using the case operator so that the result is the name property in docs of one type, and null in all other docs. This will waste space compared to a true partial index, but it’ll be correct and pretty fast.

(Apologies, I’m not that familiar with the public query API so I’m not sure of the proper syntax for case expressions.)