I have a Couchdb that stores do开发者_StackOverflow社区cuments each of each has a prefix field. Prefixes are unique so they can actually be used as IDs
Say:
_id=1 {prefix="AAABBBCCC", ...}
_id=2 {prefix="AAABBBDDD", ...}
_id=3 {prefix="AAABBE", ...}
_id=4 {prefix="AAAFF", ...}
I need to query these documents retrieving an appropriate document (always one full match on the prefix) using a key that is longer but completly matches the prefix. Prefix length varies, key length is constant.
query_key = AAABBBCCC123 => _id1
query_key = AAABBBDDD456 => _id2
query_key = AAABBEEEEEEE => _id3
query_key = AAABxxxxxxxx => Null
Any idea how can this be done in Couch?
Make a view emitting doc.prefix
. Then query descending with startkey
set to your query key with limit=1
. The resulting prefix might be yours but you have to confirm.
You can either confirm the prefix in the client, or with a _list
function. A _list
function probably does not help with performance so I would consider doing it in the client, unless you have many clients in many languages, and you can standardize on a single URL to query with the same output.
The map function should look like this
function(doc) {
emit(doc.prefix, doc);
}
and you should search for documents with the substring function in the key.
Like this:
_design/doc/_view/viewname?key=QUERY_KEY.substring(0, FIXED_KEY_LENGTH)
精彩评论