jackhammer013
jackhammer013

Reputation: 2295

How to query to couchdb by key and string search

I'm new to CouchDB and I have documents like this:

{
    "credit_type" : "ADJ",
    "particular" : "Adjusted hours on 2018-01-01"
}

Then I have a view with this Map function

function(doc) {
   if(doc.credit_type == "ADJ") { emit(doc.particular, doc); }  
}

My view url is like this:

http://mywebsite.com:5984/_utils/database.html?client_docs/_design/adj/_view/adj

What I want to do is be able to query documents that will match my search key. The lookup field is the particular field.

The search key is a date like 2018-01-01 When I put they search url like

http://black-widow.remotestaff.com:5984/client_docs/_design/adj/_view/adj?key=20180-01-01

I should be able to fetch records which contains 2018-01-01 string in the particular field

I don't have any reduce function yet

Upvotes: 1

Views: 1000

Answers (1)

Hypnic Jerk
Hypnic Jerk

Reputation: 1192

In order to search by some key, you must emit that key.

For you to be able to do this, I would suggest potentially moving the date out of the particular field, into its own field, this way you wont have to do any string parsing on the particular field to grab your date.

If you do not or can not do this, the you will have to parse the particular field for the date. This can be achieved by this question and answer.*

Once you have gotten the date, you will need to emit it, so let me give you an example.

function(doc){
    String date = doc.particular.parse.date.here();

    emit([date, doc.credit_type], doc.particular);
}

Here, we parse the date from the doc.particular field, and emit it along with the credit type. Now, you can keep your if statement as it is, but doing it this way means you can search for ANY credit_typevs just the ADJ.

Now your keys should be 2018-01-01 and ADJ.

*You will need to make sure that CouchDB version of JS supports these functions.

Upvotes: 0

Related Questions