4

I have a Couchdb that stores documents 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?

1
  • What if there is both AAABBBCCC and AAABBBCCC12 and you query for AAABBBCCC123. Which one is the right answer? Or is that situation impossible?
    – JasonSmith
    Jan 27, 2011 at 11:50

2 Answers 2

2

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.

2
  • Oh wow, I just saw your comment with the same technique. Sorry.
    – JasonSmith
    Jan 27, 2011 at 11:56
  • I will give you the point though - did not know about the _list, thanks!
    – tbikeev
    Jan 27, 2011 at 21:13
0

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)
1
  • Not sure about substring, anyway I'll never know FIXED_KEY_LENGTH in advance ... I got it working through .../_view/QUERY_NAME?startkey="query_key"&descending=true&limit=1 this gives me the last prefix that would have matched, I just need to verify if the prefix is actually contained in the query_key (client-side for the moment).
    – tbikeev
    Jan 26, 2011 at 20:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.