couchdb-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Paul Davis <>
Subject Re: Simulating SQL 'LIKE %' using Regular Expressions
Date Wed, 02 Jun 2010 01:32:32 GMT
The short answer is that you can do 'like "C%"' but not 'like "%C"'.
You don't really appear to care about the latter so this should be ok.

To accomplish:

//map function
function(doc) {
  for(id in doc.Stores) {
    if(doc.Stores[id].name) {
      emit(doc.Stores[id].name, {
        "product": doc.product_name,
        "qty": doc.Stores[id].item_count

And then to query you use something like:


to get the first 10 matching stores.

To get the first N stores matching a prefix of the name for a given
product, do something like:

//in map function
emit([doc.product_name, doc.Stores[id].name], product_info_obj);

and query the view with the query string:

?startkey=[product_name, "C"]&limit=10

Remember that views are all about sorting. Your prefix dealie is just
asking for "the next N things that sort after this prefix" which is
totally doable.

The inevitable follow up will be "but it shows stores that start with
Dude" when I query for "C" if there aren't any stores starting with

In this case you just use an endkey that limits the results to the
range you're interested in. Kinda sorta abusing unicode bits, you can
do something like:

?startkey="C"&endkey="C\uFFFF"&limit=10 which will limit things
reasonably. I seem to recall a different string sentinel but the
alternate version escapes me at the moment.

Also, this should work with things like:


to get the list of stores starting with "Computer"

On Tue, Jun 1, 2010 at 9:01 PM,  <> wrote:
> Hi, so in my couchDB, what I want to happen is when you query a view in
> the design doc and providing ?key="C" at the end, bring up all shop names
> that start with C.
> to do this I have made the following map function:
> function(doc)
> {
>  for (id in doc.Stores)
>  {
>  var strqry = doc.Stores[id]["name"].match(/^.*/);
>    if (strqry)
>    {
>      emit(strqry, doc.product_name + " qty: " +
> doc.Stores[id].item_count);
>    }
>  }
> }
> When I run this from the temp view in Futon, I get a list of all stores
> and products (which made me think 'yay it worked, all it needs is a
> parameter') but when I use:
> http://host:5984/db/design/name/_view/function?key="C" I get back:
> {"total_rows":30,"offset":0,"rows":[]}
> my ultimate aim is to get it working similar to an SQL Like % so if for
> example I say ?key="C" it will return "Computer Store A" and so on..
> I created my function based on this tutorial:

View raw message