Pergunta

I am new to CouchDB. How to implement keyword search in CouchDB?

For example, I have users document in CouchDB. The structure is the following:

UsersCouchDB:

id: 1
last_name: jack
first_name: abc
phone_num: 123-456-7890

id: 2
last_name: rose
first_name: gbcde
phone_num: 123-111-2222

...

I want to implement a search function for phone_num, so that if users type in, let's say, "23", then id 1 and id 2 should be shown because their phone number contain "23".

What is the easier or fastest way to do it? Is it possible not to use 3rd party package to do this feature?

I heard some people use couchdb-lucene to do the similar thing. Can anyone show me some codes about how to make this kind of search features?

Foi útil?

Solução

The easiest way is to use list functions. However, this is equivalent to full scan operation:

function(head, req){
  var filter = function(key){ 
    if (!req.query.q){
      return key; // list all
    }
    if (!req.query.q.match('^[\d-]+$'){
      return; // don't allow regex injections
    }
    var match = key.match('.*' + req.query.q + '.*');
    if (match) return match[0];
  }
  start({'headers': {'Content-Type': 'text/plain'}});
  var num = null;
  while(row=getRow()){
    num = filter(row.key);
    if (num){
      send(num + '\n');
    }
  }
}

Also define view that emits phone numbers for contacts:

function(doc){
  if(doc.type == 'contact'){emit(doc.phone_num, null)}
}

And call with view that emits only contacts like: /db/_design/contacts/_list/search/phone?q=23

The fastest way is to use couchdb-lucene.

First, create index ddoc:

{
    "_id":"_design/contacts",
    "fulltext": {
        "by_phone": {
            "index":"function(doc) { var ret=new Document(); ret.add(doc.phone_num); return ret }"
        }
    }
}

And query it like http://localhost:5984/db/_fti/_design/contacts/by_phone?q=23

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top