CouchDB Search of Multiple Fields

Richard67

I am trying to use CouchDB 3.1 for the first time. I'm trying to do a dynamic query where multiple fields can be searched and is totally optional. Example of my data:

{
  "_id": "464e9db4d9216e1621b354794a0181d4",
  "_rev": "1-fade491c3e255bbbfa60f1d7462fa9a2",
  "app_id": "0000001",
  "username": "[email protected]",
  "transaction": "registration",
  "customer_name": "John Doe",
  "status": "complete",
  "request_datetime": "2020-01-31 12:05:00"
}

So what I'm trying to do is, the documents can be searched by "transaction", "transaction" and "app_id", or combination of the fields "app_id" / "username" / "transaction" / "username" / "status" / "request_datetime" based on the search input from the user. (Some of the field such as "app_id" might be null based on the "transaction")

I have tried to make View to search by "app_id" and "transaction" :

function (doc) {
   if(doc.transaction && doc.app_id) {
    emit([doc.transaction, doc.app_id], doc);
   }
}

But this is not gonna work when the app_id itself is null due to key in CouchDB is the index.

So my question is whether this can be achieved using vanilla CouchDB without using GeoCouch or Lucene? Do I need to make different views based on different combination of search fields?

Any help is greatly appreciated. Thank you very much.

uminder

With /db/_find, you can define a selector that accepts combination operators and condition operators. This lets you create simple and really complex queries. Given your document structure, such a selector could look as follows.

"selector":{
  "$and":[
     {
        "app_id":{
           "$eq":"0000001"
        }
     },
     {
        "username":{
           "$eq":"[email protected]"
        }
     },
     {
        "request_datetime": {
           "$gte": "2020-01-31 12:00:00",
           "$lt": "2020-01-31 13:00:00"
         } 
     }         
  ]
}

The $or operator, combined with $eq and $exists may be used for checking fields that can be null. The $regex operator offers you even much more power.

Here's a simple example using CURL (replace with the name of your database).

curl -H 'Content-Type: application/json' -X POST http://localhost:5984/<db>/_find -d '{"selector":{"username":{"$eq": "[email protected]"}}}'

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related