Zaleem
Zaleem

Reputation: 11

Perform where condition in couchdb

Here is my database schema:

Database name: user
_id 74acd65e6eeb6d55809a950036000f50
_rev 1-f5ca343d0688d7a01b549e5c29a4a911
Budget dsds
user_Id abc123
Name ssdsd

Now what I want is to retrieve all the records who are having "user_Id":"ssdsd" using GWT.

Like in mysql: select * from user where user_Id=ssdsd

Please guide me in the following code

public String view(String user_id) throws IllegalArgumentException {
        // TODO Auto-generated method stub
        Session s1=new Session("127.0.0.1",5984);
        Database db=s1.getDatabase("users");
        return "";

Upvotes: 1

Views: 470

Answers (1)

Bernhard Gschwantner
Bernhard Gschwantner

Reputation: 1537

Unfortunately I'm not familiar with GWT, but I think your question is more CouchDB-related.

If you plan on having one and exactly one document per user, then you should use the user_Id directly as the _id. This way you get the benefit of using the "primary" index of CouchDb to your advantage and enforce unique user ids at the same time. It is good practice and a convention to also store the type of the document in the type property. The document could look like this:

{
  "_id": "user.abc123",
  "type": "user",
  "name": "ssdsd",
  "budget": "dsds"
}  

If you need to have multiple documents per user_Id, then you need to write a CouchDB view. You can read an introduction in the CouchDB Docs.

This would be some simple JavaScript code for the CouchDB map function:

function (doc) {
  if (doc.user_Id) {
    emit(doc.user_id, {budget: doc.budget});
  }
}

You would then be able to query this view by calling the view with a key of "abc123", e.g. in the browser by calling this URL:

http://localhost:5984/users/_design/users/_view/users?key=[“abc123"]

P.S.: If you need authentication also, it might be worth considering to store the users in the built-in database _users. Just keep in mind that there are some restrictions in this system db: non-admins cannot read other users' documents in this db, and some special schema requirements have to be met when adding documents there.

Upvotes: 1

Related Questions