How to write a view in CouchDB to represent “not in” or “group by having count(*) = 1”?

爷,独闯天下 提交于 2020-06-29 04:04:20

问题


Using relational db as an example, given two tables like below, where when rows in tableA and tableB have the same values, they represent the same "thing" but in different "state". So for ID=1, this thing has gone through stage1 and 2. But for ID=2, this thing has only gone through stage1.

tableA (Id, columnA, columnB)
         1, "a", "b"
         2, "x", "y"
         3, "z", "a"
tableB (Id, columnA, columnB)
         1, "e", "f"

I want to find all the rows from tableA that don't exist in tableB.

select  a.*
from    tableA a
  left join
        tableB b
  on    a.Id = b.Id
where   b.Id is null

So above SQL will show rows 2 and 3 from tableA.

How can I do similar things in CouchDB? Say I have 4 docs that look like below.

{ "_id":"a-1", "type":"A", "correlation_id": "1" }
{ "_id":"a-2", "type":"A", "correlation_id": "2" }
{ "_id":"a-3", "type":"A", "correlation_id": "3" }
{ "_id":"b-1", "type":"B", "correlation_id": "1" }

How can I create a view that only show docs id = a-2 and a-3? I don't want to filter, just want to show all docs that haven't got type B. I could kinda do a group by and count(*) equivalent with view, but I can't do a group by, having count(*) = 1 equivalent.

I'm using CouchDB 3.0.


回答1:


you could write a view :

function (doc) {
  emit(doc.type, 1);
}

and then query the view using the key "A" and include_docs=true if you wanted the whole content of those documents.

If you not only want "A" but "everything but B" you can query from start to B and then from B to end and get all the documents that way.

Depending on your setup it might be easier to query the view with group_level=1 so you get all the keys and then loop through them excluding B to get the rest of the info you're interested in.



来源:https://stackoverflow.com/questions/61844995/how-to-write-a-view-in-couchdb-to-represent-not-in-or-group-by-having-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!