Multiple keys for emit

query

#1

Hello.
When the view as:

function (doc, meta) {
  if (meta.type == "json" && doc.type == "fileActivity") {
    // Check if doc is JSON
    emit([doc.createdAt, doc.toUserId], {
      'docId': doc.docId,
      'createdAt': doc.createdAt,
      'updatedAt': doc.updatedAt,
      'file': doc.file
    });
  } else {
    // do something with binary value
  }
}

how to make a query with only one key?

CouchbaseViewQuery::from("fileActivity", 'toUserIdWithCreatedAt')->custom([['startkey' => '0',
    'endkey' => '1401566605'], "a056833fe94a"]);

or

CouchbaseViewQuery::from("fileActivity", 'toUserIdWithCreatedAt')->limit(50)->range(['startkey' => '0');

or

CouchbaseViewQuery::from("fileActivity", 'toUserIdWithCreatedAt')->custom(??????????????);

Thanks!


#2

I will use here sample bucket beer-sample, which also has similar view function:

function(doc, meta) {
  switch(doc.type) {
  case "brewery":
    emit([meta.id]);
    break;
  case "beer":
    if (doc.brewery_id) {
      emit([doc.brewery_id, meta.id]);
    }
    break;
  }
}

I assume you want to select the rows by specifying only first part of compound key, in this case you would need something like this

<?php
$cb = new CouchbaseCluster('localhost');
$db = $cb->openBucket('beer-sample');

$filter_key = "abita_brewing_company";
$query = CouchbaseViewQuery::from('beer', 'brewery_beers')
       ->custom([
           'startkey' => json_encode([$filter_key]),
           'endkey' => json_encode([$filter_key . "\uffff"]),
       ]);
$doc = $db->query($query);
var_dump($doc);

Note here, that we use json_encode because they parameter value have to be JSON encoded. And also to stop right after that key, we append "\uffff" character.

On the other hand, if you need to fetch one document exactly by the key, you have to either specify whole key to key parameter (there is also keys parameter for multiple keys):

<?php
$cb = new CouchbaseCluster('localhost');
$db = $cb->openBucket('beer-sample');

$filter_key = [
    "abita_brewing_company",
    "abita_brewing_company-triple_citra_hopped_satsuma_wit",
];
$query = CouchbaseViewQuery::from('beer', 'brewery_beers')
       ->custom([
           'key' => json_encode($filter_key),
       ]);
$doc = $db->query($query);
var_dump($doc);

More information about query parameters you can find in the docs: http://developer.couchbase.com/documentation/server/4.1/developer-guide/views-querying.html#story-h2-1


#3

Thank you @avsej it useful for me.