Query all items in a bucket with filter by field

#1

Hello experts.
I would like to show sample of the latest documents that came into the bucket.
So I’m creating a view to show all items and fetch it with the descending option.
I would like to add an ability to filter by a field inside of a document.
Do I have an option to do this without creating a view for each field and foreach field value?

Thanks

#2

You can conditionally emit the key/value for a map reduce function based on a single or multiple fields and also do startkey/endkey to perform this time of functionality. A writeup of how to do this can be found on this blog: http://blog.couchbase.com/indexes-and-selectivity

#3

You can structure the index so it’ll have the field value as the primary key and the date added as the secondary key. You do this by emitting keys of the form [fieldvalue, date], i.e. the key is a 2-item array.

Then you can use startkey/endkey in your query to restrict the search to the desired field value. If you specify descending order and set a limit, you’ll get the most recent docs with that field value.

For example, you might use a startkey ["red", {}] and endkey ["red"] to restrict to the keys whose first item (the desired field value) is "red". (Note that the start and end key are reversed because you’re using a descending order.)

#4

Thank you very much.
I will try it.