How to get Item count (no of records ) in a bucket

Lets example in “beer-sample” bucket has 7303 Item Count .
what is the code in java to get that Item Count

static Cluster cluster = CouchbaseCluster.create();
static Bucket bucket = cluster.openBucket(“beer-sample”);

pls help me.

To answer this well, we’ll need some more context. If this is a one-time count, you can do it with the N1QL COUNT() function. If, on the other hand, this is something you’ll be doing regularly and have a simple filter, you may want to look at the MapReduce Views.

yes its one time count .Please let me know the what is the N1QL query to find out the count (no of records) in a bucket.

The exact statement is simply:

SELECT COUNT(*) AS size FROM `bucket-name`

So in the java sdk:

//notice we use the Bucket instance corresponding to the bucket we want to count
Bucket countedBucket = cluster.openBucket("bucket-name", "password");
N1qlQuery countQuery = N1qlQuery.simple("SELECT COUNT(*) AS size FROM `bucket-name`");
N1qlQueryResult result = countedBucket.query(countQuery);
if (result.isFinalSuccess()) { //query executed entirely 
    //tip: generally, only call allRows() once    
    List<N1qlQueryRows> rows = result.allRows();

    //only 1 result expected, a JSON object:
    long bucketSize = rows.get(0).value() 
    //that's where the "AS size" comes in handy:
        .getLong("size");
} else {
    //deal with result.errors() here
}

Same thing i want to do using mapreduce. The view with design doc i have created through java. But instead of assigning the _ count after going to the couchbase in view manually, is there a way by any chance the same could be done through java…?

The views engine uses JavaScript, not Java. So you cannot define a view using Java.

Do you mean to be asking how can you count things without either N1QL or Views? There isn’t really a supported way to do that at the moment. The only advantage I’d see is that you’d save the cost of the view execution and would be able to do it even if you don’t have the query/indexing services.