Question

I prepare to use CouchDB to my project. but cannot find a way to implement a view like an SQL SELECT * FROM Employees WHERE LastName NOT IN (SELECT LastName FROM Managers). In other words, I want to get a set from view A but not in view B. Question: how to implement not-in condition in CouchDB?

Was it helpful?

Solution

Keeping employees and managers lists different sets of documents is using relational structure where you DB is not relational. If, for some reason, you are forced to do that, you need some way to distinguish the scheme of the doc (from which table it is). Lets say you are doing it with field scheme:

{ _id: "EMPL_ID", scheme: "employee", ... }
{ _id: "MNGR_ID", scheme: "manager", employee: "EMPL_ID", ... }

Then you can use map:

function (doc) {
    if (!doc.scheme) return;
    if (doc.scheme != "manager") emit(doc.last_name, doc);
}

If, for some strange reason, you cannot do that, and you only have the reference to employee doc in manager doc, you can emit both documents:

function (doc) {
    if (some_test_for_being_employee_scheme(doc))
        emit([doc._id, 1], doc);
    if (doc.emp_id)
        emit([doc.emp_id, 0], null);
}

You will get the list of employees with keys ["employee_id", 1], and each manager is preceded with the row labeled as manager (key [..., 0]). This will require some space, but with list function you can filter out managers easily and the client will receive from DB only the non-managers.

Keep in mind, that it is only the workaround for not making proper DB design.

OTHER TIPS

If you change the model to make it fit a document-oriented database, this would be easy. I generally keep a "type" key in all of my documents to keep different types of documents straight. If you have a single "person" type and decorate all "person" documents who are also "manager" with a separate key, you could easily emit view keys only for non-managerial personnel. If you opt to have a separate "manager" type, you could similarly restrict emitted view keys to non-managers only.

I think the answer is simply: you can't mix view results. Views are independent. However, there is a strategy called view collation that probably solves your problems. I suggest reading this: http://wiki.apache.org/couchdb/View_collation To summarize it: You need to use different document types and then use a single view to collate the results.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top