Class: Couchbase::Collection

Inherits:
Object
  • Object
show all
Defined in:
lib/couchbase/collection.rb,
lib/couchbase/collection_options.rb,
/home/runner/work/couchbase-ruby-client/couchbase-ruby-client/lib/couchbase/collection.rb,
/home/runner/work/couchbase-ruby-client/couchbase-ruby-client/lib/couchbase/collection_options.rb

Overview

Provides access to all collection APIs

Defined Under Namespace

Classes: ExistsResult, GetReplicaResult, GetResult, LookupInReplicaResult, LookupInResult, MutateInResult, MutationResult, ScanResult, ScanResults

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#bucket_name ⇒ Object (readonly)

Returns the value of attribute bucket_name.



26
27
28
# File 'lib/couchbase/collection.rb', line 26

def bucket_name
  @bucket_name
end

#name ⇒ Object (readonly)

Returns the value of attribute name.



28
29
30
# File 'lib/couchbase/collection.rb', line 28

def name
  @name
end

#scope_name ⇒ Object (readonly)

Returns the value of attribute scope_name.



27
28
29
# File 'lib/couchbase/collection.rb', line 27

def scope_name
  @scope_name
end

Instance Method Details

#binary ⇒ BinaryCollection

Provides access to the binary APIs, not used for JSON documents

Returns:



50
51
52
# File 'lib/couchbase/collection.rb', line 50

def binary
  BinaryCollection.new(self)
end

#exists(id, options = Options::Exists::DEFAULT) ⇒ ExistsResult

Checks if the given document ID exists on the active partition.

Examples:

Check if the document exists without fetching its contents

res = collection.exists("customer123")
res.exists? #=> true

Parameters:

  • id (String) —

    the document id which is used to uniquely identify it.

  • options (Options::Exists) (defaults to: Options::Exists::DEFAULT) —

    request customization

Returns:



281
282
283
284
285
286
287
288
289
290
291
292
293
294
# File 'lib/couchbase/collection.rb', line 281

def exists(id, options = Options::Exists::DEFAULT)
  @observability.record_operation(Observability::OP_EXISTS, options.parent_span, self, :kv) do |obs_handler|
    resp = @backend.document_exists(bucket_name, @scope_name, @name, id, options.to_backend, obs_handler)
    ExistsResult.new do |res|
      res.deleted = resp[:deleted]
      res.exists = resp[:exists]
      res.expiry = resp[:expiry]
      res.flags = resp[:flags]
      res.sequence_number = resp[:sequence_number]
      res.datatype = resp[:datatype]
      res.cas = resp[:cas]
    end
  end
end

#get(id, options = Options::Get::DEFAULT) ⇒ GetResult

Fetches the full document from the collection

Examples:

Get document contents

res = collection.get("customer123")
res.content["addresses"]

# {"billing"=>
#   {"line1"=>"123 Any Street", "line2"=>"Anytown", "country"=>"United Kingdom"},
#  "delivery"=>
#   {"line1"=>"123 Any Street", "line2"=>"Anytown", "country"=>"United Kingdom"}}

Get partial document using projections

res = collection.get("customer123", Options::Get(projections: ["name", "addresses.billing"]))
res.content

# {"addresses"=>
#    {"billing"=>
#      {"country"=>"United Kingdom",
#       "line1"=>"123 Any Street",
#       "line2"=>"Anytown"}},
#   "name"=>"Douglas Reynholm"}

Parameters:

  • id (String) —

    the document id which is used to uniquely identify it

  • options (Options::Get) (defaults to: Options::Get::DEFAULT) —

    request customization

Returns:



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/couchbase/collection.rb', line 85

def get(id, options = Options::Get::DEFAULT)
  @observability.record_operation(Observability::OP_GET, options.parent_span, self, :kv) do |obs_handler|
    resp = if options.need_projected_get?
             @backend.document_get_projected(bucket_name, @scope_name, @name, id, options.to_backend, obs_handler)
           else
             @backend.document_get(bucket_name, @scope_name, @name, id, options.to_backend, obs_handler)
           end
    GetResult.new do |res|
      res.transcoder = options.transcoder
      res.cas = resp[:cas]
      res.flags = resp[:flags]
      res.encoded = resp[:content]
      res.expiry = resp[:expiry] if resp.key?(:expiry)
    end
  end
end

#get_all_replicas(id, options = Options::GetAllReplicas::DEFAULT) ⇒ Array<GetReplicaResult>

Reads from all available replicas and the active node and returns the results

Parameters:

  • id (String) —

    the document id which is used to uniquely identify it.

  • options (Options::GetAllReplicas) (defaults to: Options::GetAllReplicas::DEFAULT) —

    request customization

Returns:



192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/couchbase/collection.rb', line 192

def get_all_replicas(id, options = Options::GetAllReplicas::DEFAULT)
  @observability.record_operation(Observability::OP_GET_ALL_REPLICAS, options.parent_span, self, :kv) do |obs_handler|
    resp = @backend.document_get_all_replicas(@bucket_name, @scope_name, @name, id, options.to_backend, obs_handler)
    resp.map do |entry|
      GetReplicaResult.new do |res|
        res.transcoder = options.transcoder
        res.cas = entry[:cas]
        res.flags = entry[:flags]
        res.encoded = entry[:content]
        res.is_replica = entry[:is_replica]
      end
    end
  end
end

#get_and_lock(id, lock_time, options = Options::GetAndLock::DEFAULT) ⇒ GetResult

Fetches the full document and write-locks it for the given duration

Examples:

Retrieve document and lock for 10 seconds

collection.get_and_lock("customer123", 10, Options::GetAndLock(timeout: 3_000))

Update document pessimistically

res = collection.get_and_lock("customer123", 10)
user_data = res.content
user_data["admin"] = true
collection.replace("user", user_data, Options::Upsert(cas: res.cas))

Parameters:

  • id (String) —

    the document id which is used to uniquely identify it.

  • lock_time (Integer, #in_seconds) —

    how long to lock the document (values over 30 seconds will be capped)

  • options (Options::GetAndLock) (defaults to: Options::GetAndLock::DEFAULT) —

    request customization

Returns:



148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/couchbase/collection.rb', line 148

def get_and_lock(id, lock_time, options = Options::GetAndLock::DEFAULT)
  @observability.record_operation(Observability::OP_GET_AND_LOCK, options.parent_span, self, :kv) do |obs_handler|
    resp = @backend.document_get_and_lock(bucket_name, @scope_name, @name, id,
                                          lock_time.respond_to?(:in_seconds) ? lock_time.in_seconds : lock_time,
                                          options.to_backend, obs_handler)
    GetResult.new do |res|
      res.transcoder = options.transcoder
      res.cas = resp[:cas]
      res.flags = resp[:flags]
      res.encoded = resp[:content]
    end
  end
end

#get_and_touch(id, expiry, options = Options::GetAndTouch::DEFAULT) ⇒ GetResult

Fetches a full document and resets its expiration time to the duration provided

Examples:

Retrieve document and prolong its expiration for another 10 seconds

collection.get_and_touch("customer123", 10)

Parameters:

  • id (String) —

    the document id which is used to uniquely identify it.

  • expiry (Integer, #in_seconds, Time) —

    the new expiration time for the document

  • options (Options::GetAndTouch) (defaults to: Options::GetAndTouch::DEFAULT) —

    request customization

Returns:



172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/couchbase/collection.rb', line 172

def get_and_touch(id, expiry, options = Options::GetAndTouch::DEFAULT)
  @observability.record_operation(Observability::OP_GET_AND_TOUCH, options.parent_span, self, :kv) do |obs_handler|
    resp = @backend.document_get_and_touch(bucket_name, @scope_name, @name, id,
                                           Utils::Time.extract_expiry_time(expiry),
                                           options.to_backend, obs_handler)
    GetResult.new do |res|
      res.transcoder = options.transcoder
      res.cas = resp[:cas]
      res.flags = resp[:flags]
      res.encoded = resp[:content]
    end
  end
end

#get_any_replica(id, options = Options::GetAnyReplica::DEFAULT) ⇒ GetReplicaResult

Reads all available replicas and active, and returns the first found.

Examples:

Get document contents

res = collection.get_any_replica("customer123")
res.replica? #=> true when a replica answered first, false for the active copy
res.content["addresses"]

# {"billing"=>
#   {"line1"=>"123 Any Street", "line2"=>"Anytown", "country"=>"United Kingdom"},
#  "delivery"=>
#   {"line1"=>"123 Any Street", "line2"=>"Anytown", "country"=>"United Kingdom"}}

Parameters:

  • id (String) —

    the document id which is used to uniquely identify it.

  • options (Options::GetAnyReplica) (defaults to: Options::GetAnyReplica::DEFAULT) —

    request customization

Returns:



258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/couchbase/collection.rb', line 258

def get_any_replica(id, options = Options::GetAnyReplica::DEFAULT)
  @observability.record_operation(Observability::OP_GET_ANY_REPLICA, options.parent_span, self, :kv) do |obs_handler|
    resp = @backend.document_get_any_replica(@bucket_name, @scope_name, @name, id, options.to_backend, obs_handler)
    GetReplicaResult.new do |res|
      res.transcoder = options.transcoder
      res.cas = resp[:cas]
      res.flags = resp[:flags]
      res.encoded = resp[:content]
      res.is_replica = resp[:is_replica]
    end
  end
end

#get_multi(ids, options = Options::GetMulti::DEFAULT) ⇒ Array<GetResult>

Note:

that it will not generate Error::DocumentNotFound exceptions in this case. The caller should check Couchbase::Collection::GetResult#error property of the result

Fetches multiple documents from the collection.

Examples:

Fetch "foo" and "bar" in a batch

res = collection.get(["foo", "bar"], Options::GetMulti(timeout: 3_000))
res[0].content #=> content of "foo"
res[1].content #=> content of "bar"

Parameters:

  • ids (Array<String>) —

    the array of document identifiers

  • options (Options::GetMulti) (defaults to: Options::GetMulti::DEFAULT) —

    request customization

Returns:



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/couchbase/collection.rb', line 116

def get_multi(ids, options = Options::GetMulti::DEFAULT)
  @observability.record_operation(Observability::OP_GET_MULTI, options.parent_span, self, :kv) do |_obs_handler|
    resp = @backend.document_get_multi(ids.map { |id| [bucket_name, @scope_name, @name, id] }, options.to_backend)
    resp.map do |entry|
      GetResult.new do |res|
        res.transcoder = options.transcoder
        res.id = entry[:id]
        res.cas = entry[:cas]
        res.flags = entry[:flags]
        res.encoded = entry[:content]
        res.error = entry[:error]
      end
    end
  end
end

#get_replica(id, strategy, options = Options::GetReplica::DEFAULT) ⇒ GetReplicaResult

Reads the document from the replica the strategy selects.

Examples:

Read the document from the second replica

res = collection.get_replica("airline_10", GetReplicaStrategy.from_index(:second))
res.replica? #=> true
res.content["name"]

Parameters:

  • id (String) —

    the document id which is used to uniquely identify it.

  • strategy (GetReplicaStrategy) —

    selects the replica to read from

  • options (Options::GetReplica) (defaults to: Options::GetReplica::DEFAULT) —

    request customization

Returns:

Raises:

Since:

  • 3.9.0



227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/couchbase/collection.rb', line 227

def get_replica(id, strategy, options = Options::GetReplica::DEFAULT)
  @observability.record_operation(Observability::OP_GET_REPLICA, options.parent_span, self, :kv) do |obs_handler|
    resp = @backend.document_get_replica(@bucket_name, @scope_name, @name, id, strategy.to_backend,
                                         options.to_backend, obs_handler)
    GetReplicaResult.new do |res|
      res.transcoder = options.transcoder
      res.cas = resp[:cas]
      res.flags = resp[:flags]
      res.encoded = resp[:content]
      res.is_replica = true
    end
  end
end

#insert(id, content, options = Options::Insert::DEFAULT) ⇒ MutationResult

Inserts a full document which does not exist yet

Examples:

Insert new document in collection

res = collection.insert("mydoc", {"foo" => 42}, Options::Insert(expiry: 20))
res.cas #=> 242287264414742

Handle error when the document already exists

collection.exists("mydoc").exists? #=> true
begin
  res = collection.insert("mydoc", {"foo" => 42})
rescue Error::DocumentExists
  puts "Failed to insert the document, it already exists in the collection"
end

Parameters:

  • id (String) —

    the document id which is used to uniquely identify it.

  • content (Object) —

    the document content to insert

  • options (Options::Insert) (defaults to: Options::Insert::DEFAULT) —

    request customization

Returns:



388
389
390
391
392
393
394
395
396
397
398
# File 'lib/couchbase/collection.rb', line 388

def insert(id, content, options = Options::Insert::DEFAULT)
  @observability.record_operation(Observability::OP_INSERT, options.parent_span, self, :kv) do |obs_handler|
    obs_handler.add_durability_level(options.durability_level)
    blob, flags = encode_content(content, options, obs_handler)
    resp = @backend.document_insert(bucket_name, @scope_name, @name, id, blob, flags, options.to_backend, obs_handler)
    MutationResult.new do |res|
      res.cas = resp[:cas]
      res.mutation_token = extract_mutation_token(resp)
    end
  end
end

#lookup_in(id, specs, options = Options::LookupIn::DEFAULT) ⇒ LookupInResult

Performs lookups to document fragments

Examples:

Get list of IDs of completed purchases

lookup_specs = [
  LookupInSpec::get("purchases.complete")
]
collection.lookup_in("customer123", lookup_specs)

Retrieve country name and check if pending purchases array is empty

collection.lookup_in "customer123", [
  LookupInSpec.get("addresses.delivery.country"),
  LookupInSpec.exists("purchases.pending[-1]"),
]

Parameters:

  • id (String) —

    the document id which is used to uniquely identify it.

  • specs (Array<LookupInSpec>) —

    the list of specifications which describe the types of the lookups to perform

  • options (Options::LookupIn) (defaults to: Options::LookupIn::DEFAULT) —

    request customization

Returns:



538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
# File 'lib/couchbase/collection.rb', line 538

def lookup_in(id, specs, options = Options::LookupIn::DEFAULT)
  @observability.record_operation(Observability::OP_LOOKUP_IN, options.parent_span, self, :kv) do |obs_handler|
    resp = @backend.document_lookup_in(
      bucket_name, @scope_name, @name, id,
      specs.map do |s|
        {
          opcode: s.type,
          xattr: s.xattr?,
          path: s.path,
        }
      end, options.to_backend, obs_handler
    )
    LookupInResult.new do |res|
      res.transcoder = options.transcoder
      res.cas = resp[:cas]
      res.deleted = resp[:deleted]
      res.encoded = resp[:fields].map do |field|
        SubDocumentField.new do |f|
          f.exists = field[:exists]
          f.index = field[:index]
          f.path = field[:path]
          f.value = field[:value]
          f.error = field[:error]
        end
      end
    end
  end
end

#lookup_in_all_replicas(id, specs, options = Options::LookupInAllReplicas::DEFAULT) ⇒ Array<LookupInReplicaResult>

Performs lookups to document fragments. Reads from the active node and all available replicas and returns all of the results

Parameters:

  • id (String) —

    the document id which is used to uniquely identify it.

  • specs (Array<LookupInSpec>) —

    the list of specifications which describe the types of the lookups to perform

  • options (Options::LookupInAllReplicas) (defaults to: Options::LookupInAllReplicas::DEFAULT) —

    request customization

Returns:

Raises:



609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
# File 'lib/couchbase/collection.rb', line 609

def lookup_in_all_replicas(id, specs, options = Options::LookupInAllReplicas::DEFAULT)
  @observability.record_operation(Observability::OP_LOOKUP_IN_ALL_REPLICAS, options.parent_span, self, :kv) do |obs_handler|
    resp = @backend.document_lookup_in_all_replicas(
      bucket_name, @scope_name, @name, id,
      specs.map do |s|
        {
          opcode: s.type,
          xattr: s.xattr?,
          path: s.path,
        }
      end, options.to_backend, obs_handler
    )
    resp.map do |entry|
      extract_lookup_in_replica_result(entry, options)
    end
  end
end

#lookup_in_any_replica(id, specs, options = Options::LookupInAnyReplica::DEFAULT) ⇒ LookupInReplicaResult

Performs lookups to document fragments. Reads from the active node and all available replicas and returns the first result found

Parameters:

  • id (String) —

    the document id which is used to uniquely identify it.

  • specs (Array<LookupInSpec>) —

    the list of specifications which describe the types of the lookups to perform

  • options (Options::LookupInAnyReplica) (defaults to: Options::LookupInAnyReplica::DEFAULT) —

    request customization

Returns:

Raises:



580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
# File 'lib/couchbase/collection.rb', line 580

def lookup_in_any_replica(id, specs, options = Options::LookupInAnyReplica::DEFAULT)
  @observability.record_operation(Observability::OP_LOOKUP_IN_ANY_REPLICA, options.parent_span, self, :kv) do |obs_handler|
    resp = @backend.document_lookup_in_any_replica(
      bucket_name, @scope_name, @name, id,
      specs.map do |s|
        {
          opcode: s.type,
          xattr: s.xattr?,
          path: s.path,
        }
      end, options.to_backend, obs_handler
    )
    extract_lookup_in_replica_result(resp, options)
  end
end

#mutate_in(id, specs, options = Options::MutateIn::DEFAULT) ⇒ MutateInResult

Performs mutations to document fragments

Examples:

Append number into subarray of the document

mutation_specs = [
  MutateInSpec::array_append("purchases.complete", [42])
]
collection.mutate_in("customer123", mutation_specs, Options::MutateIn(expiry: 10))

Write meta attribute, remove array entry and replace email field

collection.mutate_in("customer123", [
  MutateInSpec.upsert("_framework.model_type", "Customer").xattr,
  MutateInSpec.remove("addresses.billing[2]"),
  MutateInSpec.replace("email", "dougr96@hotmail.com"),
])

Parameters:

  • id (String) —

    the document id which is used to uniquely identify it.

  • specs (Array<MutateInSpec>) —

    the list of specifications which describe the types of the lookups to perform

  • options (Options::MutateIn) (defaults to: Options::MutateIn::DEFAULT) —

    request customization

Returns:



647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
# File 'lib/couchbase/collection.rb', line 647

def mutate_in(id, specs, options = Options::MutateIn::DEFAULT)
  @observability.record_operation(Observability::OP_MUTATE_IN, options.parent_span, self, :kv) do |obs_handler|
    obs_handler.add_durability_level(options.durability_level)
    resp = @backend.document_mutate_in(
      bucket_name, @scope_name, @name, id,
      specs.map do |s|
        {
          opcode: s.type,
          path: s.path,
          param: s.param,
          xattr: s.xattr?,
          expand_macros: s.expand_macros?,
          create_path: s.create_path?,
        }
      end, options.to_backend, obs_handler
    )
    MutateInResult.new do |res|
      res.transcoder = options.transcoder
      res.cas = resp[:cas]
      res.deleted = resp[:deleted]
      res.mutation_token = extract_mutation_token(resp)
      res.encoded = resp[:fields].map do |field|
        SubDocumentField.new do |f|
          f.index = field[:index]
          f.path = field[:path]
          f.value = field[:value]
        end
      end
    end
  end
end

#query_indexes ⇒ Management::CollectionQueryIndexManager



55
56
57
# File 'lib/couchbase/collection.rb', line 55

def query_indexes
  Management::CollectionQueryIndexManager.new(@backend, @bucket_name, @scope_name, @name, @observability)
end

#remove(id, options = Options::Remove::DEFAULT) ⇒ MutationResult

Removes a document from the collection

Examples:

Remove the document in collection

res = collection.remove("customer123")
res.cas #=> 241994216651798

Remove the document in collection, but apply optimistic lock

res = collection.upsert("mydoc", {"foo" => 42})
res.cas #=> 7751414725654

begin
  res = collection.remove("mydoc", Options::Remove(cas: 3735928559))
rescue Error::CasMismatch
  puts "Failed to remove the document, it might be changed by other application"
end

Parameters:

  • id (String) —

    the document id which is used to uniquely identify it.

  • options (Options::Remove) (defaults to: Options::Remove::DEFAULT) —

    request customization

Returns:



316
317
318
319
320
321
322
323
324
325
# File 'lib/couchbase/collection.rb', line 316

def remove(id, options = Options::Remove::DEFAULT)
  @observability.record_operation(Observability::OP_REMOVE, options.parent_span, self, :kv) do |obs_handler|
    obs_handler.add_durability_level(options.durability_level)
    resp = @backend.document_remove(bucket_name, @scope_name, @name, id, options.to_backend, obs_handler)
    MutationResult.new do |res|
      res.cas = resp[:cas]
      res.mutation_token = extract_mutation_token(resp)
    end
  end
end

#remove_multi(ids, options = Options::RemoveMulti::DEFAULT) ⇒ Array<MutationResult>

Note:

that it will not generate Error::DocumentNotFound or Error::CasMismatch exceptions in this case. The caller should check Couchbase::Collection::MutationResult#error property of the result

Removes a list of the documents from the collection

Examples:

Remove two documents in collection. For "mydoc" apply optimistic lock

res = collection.upsert("mydoc", {"foo" => 42})
res.cas #=> 7751414725654

res = collection.remove_multi(["foo", ["mydoc", res.cas]])
if res[1].error.is_a?(Error::CasMismatch)
  puts "Failed to remove the document, it might be changed by other application"
end

Parameters:

  • ids (Array<String, Array>) —

    the array of document ids, or ID/CAS pairs [String,Integer]

  • options (Options::RemoveMulti) (defaults to: Options::RemoveMulti::DEFAULT) —

    request customization

Returns:



345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# File 'lib/couchbase/collection.rb', line 345

def remove_multi(ids, options = Options::RemoveMulti::DEFAULT)
  @observability.record_operation(Observability::OP_REMOVE_MULTI, options.parent_span, self, :kv) do |obs_handler|
    obs_handler.add_durability_level(options.durability_level)
    resp = @backend.document_remove_multi(bucket_name, @scope_name, @name, ids.map do |id|
      case id
      when String
        [id, nil]
      when Array
        id
      else
        raise ArgumentError, "id argument of remove_multi must be a String or Array<String, Integer>, given: #{id.inspect}"
      end
    end, options.to_backend)
    resp.map do |entry|
      MutationResult.new do |res|
        res.cas = entry[:cas]
        res.mutation_token = extract_mutation_token(entry)
        res.error = entry[:error]
        res.id = entry[:id]
      end
    end
  end
end

#replace(id, content, options = Options::Replace::DEFAULT) ⇒ MutationResult

Replaces a full document which already exists

Examples:

Replace new document in collection with optimistic locking

res = collection.get("mydoc")
res = collection.replace("mydoc", {"foo" => 42}, Options::Replace(cas: res.cas))
res.cas #=> 242287264414742

Parameters:

  • id (String) —

    the document id which is used to uniquely identify it.

  • content (Object) —

    the document content to upsert

  • options (Options::Replace) (defaults to: Options::Replace::DEFAULT) —

    request customization

Returns:



468
469
470
471
472
473
474
475
476
477
478
# File 'lib/couchbase/collection.rb', line 468

def replace(id, content, options = Options::Replace::DEFAULT)
  @observability.record_operation(Observability::OP_REPLACE, options.parent_span, self, :kv) do |obs_handler|
    obs_handler.add_durability_level(options.durability_level)
    blob, flags = encode_content(content, options, obs_handler)
    resp = @backend.document_replace(bucket_name, @scope_name, @name, id, blob, flags, options.to_backend, obs_handler)
    MutationResult.new do |res|
      res.cas = resp[:cas]
      res.mutation_token = extract_mutation_token(resp)
    end
  end
end

#scan(scan_type, options = Options::Scan::DEFAULT) ⇒ ScanResults

Note:

Use this API for low concurrency batch queries where latency is not a critical as the system may have to scan a lot of documents to find the matching documents. For low latency range queries, it is recommended that you use SQL++ with the necessary indexes.

Performs a key-value scan operation on the collection

Examples:

Get a sample of up to 5 documents from the collection and store their IDs in an array

result = collection.scan(SamplingScan.new(5), Options::Scan.new(ids_only: true))
ids = result.map { |item| item.id }

Get all documents whose ID starts with 'customer_1' and output their content

result = collection.scan(PrefixScan.new("customer_1"))
result.each { |item| puts item.content }

Get all documents with ID between 'customer_1' and 'customer_2', excluding 'customer_2' and output their content

result = collection.scan(RangeScan.new(
  from: ScanTerm.new("customer_1"),
  to: ScanTerm.new("customer_2", exclusive: true)
))
result.each { |item| puts item.content }

Parameters:

Returns:



705
706
707
708
709
710
711
712
713
714
# File 'lib/couchbase/collection.rb', line 705

def scan(scan_type, options = Options::Scan::DEFAULT)
  @observability.record_operation(Observability::OP_SCAN, options.parent_span, self, :kv) do |_obs_handler|
    ScanResults.new(
      core_scan_result: @backend.document_scan_create(
        @bucket_name, @scope_name, @name, scan_type.to_backend, options.to_backend
      ),
      transcoder: options.transcoder,
    )
  end
end

#touch(id, expiry, options = Options::Touch::DEFAULT) ⇒ MutationResult

Update the expiration of the document with the given id

Examples:

Reset expiration timer for document to 30 seconds

res = collection.touch("customer123", 30)

Parameters:

  • id (String) —

    the document id which is used to uniquely identify it.

  • expiry (Integer, #in_seconds, Time) —

    new expiration time for the document

  • options (Options::Touch) (defaults to: Options::Touch::DEFAULT) —

    request customization

Returns:



490
491
492
493
494
495
496
497
498
499
# File 'lib/couchbase/collection.rb', line 490

def touch(id, expiry, options = Options::Touch::DEFAULT)
  @observability.record_operation(Observability::OP_TOUCH, options.parent_span, self, :kv) do |obs_handler|
    resp = @backend.document_touch(bucket_name, @scope_name, @name, id,
                                   Utils::Time.extract_expiry_time(expiry),
                                   options.to_backend, obs_handler)
    MutationResult.new do |res|
      res.cas = resp[:cas]
    end
  end
end

#unlock(id, cas, options = Options::Unlock::DEFAULT) ⇒ void

This method returns an undefined value.

Unlocks a document if it has been locked previously

Examples:

Lock (pessimistically) and unlock document

res = collection.get_and_lock("customer123", 10)
collection.unlock("customer123", res.cas)

Parameters:

  • id (String) —

    the document id which is used to uniquely identify it.

  • cas (Integer) —

    CAS value which is needed to unlock the document

  • options (Options::Unlock) (defaults to: Options::Unlock::DEFAULT) —

    request customization

Raises:



514
515
516
517
518
# File 'lib/couchbase/collection.rb', line 514

def unlock(id, cas, options = Options::Unlock::DEFAULT)
  @observability.record_operation(Observability::OP_UNLOCK, options.parent_span, self, :kv) do |obs_handler|
    @backend.document_unlock(bucket_name, @scope_name, @name, id, cas, options.to_backend, obs_handler)
  end
end

#upsert(id, content, options = Options::Upsert::DEFAULT) ⇒ MutationResult

Upserts (inserts or updates) a full document which might or might not exist yet

Examples:

Upsert new document in collection

res = collection.upsert("mydoc", {"foo" => 42}, Options::Upsert(expiry: 20))
res.cas #=> 242287264414742

Parameters:

  • id (String) —

    the document id which is used to uniquely identify it.

  • content (Object) —

    the document content to upsert

  • options (Options::Upsert) (defaults to: Options::Upsert::DEFAULT) —

    request customization

Returns:



411
412
413
414
415
416
417
418
419
420
421
# File 'lib/couchbase/collection.rb', line 411

def upsert(id, content, options = Options::Upsert::DEFAULT)
  @observability.record_operation(Observability::OP_UPSERT, options.parent_span, self, :kv) do |obs_handler|
    obs_handler.add_durability_level(options.durability_level)
    blob, flags = encode_content(content, options, obs_handler)
    resp = @backend.document_upsert(bucket_name, @scope_name, @name, id, blob, flags, options.to_backend, obs_handler)
    MutationResult.new do |res|
      res.cas = resp[:cas]
      res.mutation_token = extract_mutation_token(resp)
    end
  end
end

#upsert_multi(id_content, options = Options::UpsertMulti::DEFAULT) ⇒ Array<MutationResult>

Note:

that it will not generate exceptions in this case. The caller should check Couchbase::Collection::MutationResult#error property of the result

Upserts (inserts or updates) a list of documents which might or might not exist yet

Examples:

Upsert two documents with IDs "foo" and "bar" into a collection

res = collection.upsert_multi([
  "foo", {"foo" => 42},
  "bar", {"bar" => "some value"}
])
res[0].cas #=> 7751414725654
res[1].cas #=> 7751418925851

Parameters:

  • id_content (Array<Array>) —

    array of tuples String,Object, where first entry treated as document key, and the second as value to upsert.

  • options (Options::UpsertMulti) (defaults to: Options::UpsertMulti::DEFAULT) —

    request customization

Returns:



441
442
443
444
445
446
447
448
449
450
451
452
453
454
# File 'lib/couchbase/collection.rb', line 441

def upsert_multi(id_content, options = Options::UpsertMulti::DEFAULT)
  @observability.record_operation(Observability::OP_UPSERT, options.parent_span, self, :kv) do |obs_handler|
    encoded_id_content = encode_content_multi(id_content, options, obs_handler)
    resp = @backend.document_upsert_multi(bucket_name, @scope_name, @name, encoded_id_content, options.to_backend)
    resp.map do |entry|
      MutationResult.new do |res|
        res.cas = entry[:cas]
        res.mutation_token = extract_mutation_token(entry)
        res.error = entry[:error]
        res.id = entry[:id]
      end
    end
  end
end