CouchDB中的Like-condition [英] Like-condition in CouchDB
问题描述
我想在CouchDB中执行LIKE条件(SQL语法)。如何才能做到这一点? LIKE条件将用于在浏览器中执行自动完成。
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.
我想在输入字段中写co并获得结果Coffee,Couch,CouchDB等等。
I want to write "co" in the input field and get the results Coffee, Couch, CouchDB ect.
推荐答案
在字符串的开头搜索字母非常容易。您只需要一个视图,将您要搜索的字符串作为键发出。假设用户输入存储在变量 q
中,则使用参数 startkey = q
和 endkey = q +\\\
。
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"
.
这里的技巧是将最高的Unicode字符追加到搜索中串。在排序顺序中,此字符串位于以 q
开头的任何其他内容之后。 (这比@titanoboa建议的解决方案更容易实现,你需要增加用户输入的最后一个字母。)
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.)
如果你还想要为了能够在字符串中间找到单词(例如,在键入co时Colbert Report),您可以使用如下视图:
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);
}
}
}
当然这只是建议短串。要在较长的文本中搜索,您应该查看全文搜索插件,如 couchdb-lucene 。
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.
这篇关于CouchDB中的Like-condition的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!