5

I want to perform a LIKE-condition (SQL syntax) in CouchDB. How can this be done? The LIKE-condition will be used to perform auto complete in the browser.

I want to write "co" in the input field and get the results Coffee, Couch, CouchDB ect.

3 Answers 3

9

It is very easy to search for letters at the beginning of a string. You just need a view that emits the string you want to search for as the key. Assuming the user input is stored in a variable q, you then call that view with the parameters startkey=q and endkey=q+"\ufff0".

The trick here is to append the highest possible Unicode character to the search string. In the sort order, this string comes after anything else starting with q. (This is much easier to implement than the solution suggested by @titanoboa, where you need to "increment" the last letter of the user input.)

If you also want to be able to find words in the middle of a string (e.g. "The Colbert Report" when typing "co"), you could use a view like this:

function(doc) {
  if (doc.title) {
    var words = {};
    doc.title.replace(/\w+/g, function(word) {
      words[word.toLowerCase()] = true;
    });
    for (w in words) {
      emit(w, doc);
    }
  }
}

Of course this is only advisable for short strings. For searching in longer texts you should look into a full-text search add-on like couchdb-lucene.

2
  • Why is the highest possible Unicode character fff0 and not ffff?
    – Jez
    Sep 20, 2016 at 13:37
  • @Jez That's a good question, I have no idea why I wrote \ufff0 back then. I suppose the correct code point would \u{10FFFF}, but I haven't tested this. (en.wikipedia.org/wiki/UTF-8#Description) Feb 20, 2017 at 9:26
0

That won't work with CouchDB alone. The best thing to try is the Lucene search engine which works well with CouchDB. Lucene is designed for full-text searching which is basically what you are looking for. Here are some instructions on the combination.

0

To implement your example, you could create a view which has your field as a key and the same field, the whole document or whatever you want as a value. If you query the view with the parameters startkey="co", endkey="cp", inclusive_end=false, you'll get all entries with a key that starts with "co".

Of course, this is less powerful than 'LIKE'.

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.