Class: Google::Cloud::Firestore::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/google/cloud/firestore/client.rb

Overview

Client

The Cloud Firestore Client used is to access and manipulate the collections and documents in the Firestore database.

Examples:

require "google/cloud/firestore"

firestore = Google::Cloud::Firestore.new

# Get a document reference
nyc_ref = firestore.doc "cities/NYC"

firestore.batch do |b|
  b.update(nyc_ref, { name: "New York City" })
end

Access collapse

Operations collapse

Instance Method Summary collapse

Instance Method Details

#batch {|batch| ... } ⇒ CommitResponse

Perform multiple changes at the same time.

All changes are accumulated in memory until the block completes. Unlike transactions, batches don't lock on document reads, should only fail if users provide preconditions, and are not automatically retried. See Batch.

Examples:

require "google/cloud/firestore"

firestore = Google::Cloud::Firestore.new

firestore.batch do |b|
  # Set the data for NYC
  b.set("cities/NYC", { name: "New York City" })

  # Update the population for SF
  b.update("cities/SF", { population: 1000000 })

  # Delete LA
  b.delete("cities/LA")
end

Yields:

  • (batch)

    The block for reading data and making changes.

Yield Parameters:

  • batch (Batch)

    The write batch object for making changes.

Returns:

See Also:



391
392
393
394
395
# File 'lib/google/cloud/firestore/client.rb', line 391

def batch
  batch = Batch.from_client self
  yield batch
  batch.commit
end

#col(collection_path) ⇒ CollectionReference Also known as: collection

Retrieves a collection.

Examples:

require "google/cloud/firestore"

firestore = Google::Cloud::Firestore.new

# Get the cities collection
cities_col = firestore.col "cities"

# Get the document for NYC
nyc_ref = cities_col.doc "NYC"

Parameters:

  • collection_path (String)

    A string representing the path of the collection, relative to the document root of the database.

Returns:



131
132
133
134
135
136
137
138
# File 'lib/google/cloud/firestore/client.rb', line 131

def col collection_path
  if collection_path.to_s.split("/").count.even?
    raise ArgumentError, "collection_path must refer to a collection."
  end

  CollectionReference.from_path \
    "#{path}/documents/#{collection_path}", self
end

#cols {|collections| ... } ⇒ Enumerator<CollectionReference> Also known as: collections

Retrieves a list of collections.

Examples:

require "google/cloud/firestore"

firestore = Google::Cloud::Firestore.new

# Get the root collections
firestore.cols.each do |col|
  puts col.collection_id
end

Yields:

  • (collections)

    The block for accessing the collections.

Yield Parameters:

Returns:



102
103
104
105
106
107
108
109
# File 'lib/google/cloud/firestore/client.rb', line 102

def cols
  ensure_service!

  return enum_for(:cols) unless block_given?

  collection_ids = service.list_collections "#{path}/documents"
  collection_ids.each { |collection_id| yield col(collection_id) }
end

#database_idString

The database identifier for the Cloud Firestore database.

Returns:

  • (String)

    database identifier.



70
71
72
# File 'lib/google/cloud/firestore/client.rb', line 70

def database_id
  "(default)"
end

#doc(document_path) ⇒ DocumentReference Also known as: document

Retrieves a document reference.

Examples:

require "google/cloud/firestore"

firestore = Google::Cloud::Firestore.new

# Get a document
nyc_ref = firestore.doc "cities/NYC"

puts nyc_ref.document_id

Parameters:

  • document_path (String)

    A string representing the path of the document, relative to the document root of the database.

Returns:



159
160
161
162
163
164
165
166
167
# File 'lib/google/cloud/firestore/client.rb', line 159

def doc document_path
  if document_path.to_s.split("/").count.odd?
    raise ArgumentError, "document_path must refer to a document."
  end

  doc_path = "#{path}/documents/#{document_path}"

  DocumentReference.from_path doc_path, self
end

#document_idFieldPath

Creates a field path object representing the sentinel ID of a document. It can be used in queries to sort or filter by the document ID. See FieldPath.document_id.

Examples:

require "google/cloud/firestore"

firestore = Google::Cloud::Firestore.new

# Get a collection reference
cities_col = firestore.col "cities"

# Create a query
query = cities_col.order(firestore.document_id)
                  .start_at("NYC")

query.get do |city|
  puts "#{city.document_id} has #{city[:population]} residents."
end

Returns:



235
236
237
# File 'lib/google/cloud/firestore/client.rb', line 235

def document_id
  FieldPath.document_id
end

#field_array_delete(*values) ⇒ FieldValue

Creates a sentinel value to indicate the removal of the given values with an array.

Examples:

require "google/cloud/firestore"

firestore = Google::Cloud::Firestore.new

# Get a document reference
nyc_ref = firestore.doc "cities/NYC"

array_delete = firestore.field_array_delete 7, 8, 9

nyc_ref.update({ name: "New York City",
                 lucky_numbers: array_delete })

Parameters:

  • values (Object)

    The values to remove from the array. Required.

Returns:

  • (FieldValue)

    The array delete field value object.



351
352
353
# File 'lib/google/cloud/firestore/client.rb', line 351

def field_array_delete *values
  FieldValue.array_delete(*values)
end

#field_array_union(*values) ⇒ FieldValue

Creates a sentinel value to indicate the union of the given values with an array.

Examples:

require "google/cloud/firestore"

firestore = Google::Cloud::Firestore.new

# Get a document reference
nyc_ref = firestore.doc "cities/NYC"

array_union = firestore.field_array_union 1, 2, 3

nyc_ref.update({ name: "New York City",
                 lucky_numbers: array_union })

Parameters:

  • values (Object)

    The values to add to the array. Required.

Returns:

  • (FieldValue)

    The array union field value object.



326
327
328
# File 'lib/google/cloud/firestore/client.rb', line 326

def field_array_union *values
  FieldValue.array_union(*values)
end

#field_deleteFieldValue

Creates a field value object representing the deletion of a field in document data.

Examples:

require "google/cloud/firestore"

firestore = Google::Cloud::Firestore.new

# Get a document reference
nyc_ref = firestore.doc "cities/NYC"

nyc_ref.update({ name: "New York City",
                 trash: firestore.field_delete })

Returns:



280
281
282
# File 'lib/google/cloud/firestore/client.rb', line 280

def field_delete
  FieldValue.delete
end

#field_path(*fields) ⇒ FieldPath

Creates a field path object representing a nested field for document data.

Examples:

require "google/cloud/firestore"

firestore = Google::Cloud::Firestore.new

user_snap = firestore.doc("users/frank").get

nested_field_path = firestore.field_path :favorites, :food
user_snap.get(nested_field_path) #=> "Pizza"

Parameters:

  • fields (String, Symbol, Array<String|Symbol>)

    One or more strings representing the path of the data to select. Each field must be provided separately.

Returns:



259
260
261
# File 'lib/google/cloud/firestore/client.rb', line 259

def field_path *fields
  FieldPath.new(*fields)
end

#field_server_timeFieldValue

Creates a field value object representing set a field's value to the server timestamp when accessing the document data.

Examples:

require "google/cloud/firestore"

firestore = Google::Cloud::Firestore.new

# Get a document reference
nyc_ref = firestore.doc "cities/NYC"

nyc_ref.update({ name: "New York City",
                 updated_at: firestore.field_server_time })

Returns:

  • (FieldValue)

    The server time field value object.



301
302
303
# File 'lib/google/cloud/firestore/client.rb', line 301

def field_server_time
  FieldValue.server_time
end

#get_all(*docs) {|documents| ... } ⇒ Enumerator<DocumentSnapshot> Also known as: get_docs, get_documents, find

Retrieves a list of document snapshots.

Examples:

require "google/cloud/firestore"

firestore = Google::Cloud::Firestore.new

# Get and print city documents
cities = ["cities/NYC", "cities/SF", "cities/LA"]
firestore.get_all(cities).each do |city|
  puts "#{city.document_id} has #{city[:population]} residents."
end

Parameters:

Yields:

  • (documents)

    The block for accessing the document snapshots.

Yield Parameters:

Returns:



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/google/cloud/firestore/client.rb', line 193

def get_all *docs
  ensure_service!

  return enum_for(:get_all, docs) unless block_given?

  doc_paths = Array(docs).flatten.map do |doc_path|
    coalesce_doc_path_argument doc_path
  end

  results = service.get_documents doc_paths
  results.each do |result|
    next if result.result.nil?
    yield DocumentSnapshot.from_batch_result(result, self)
  end
end

#project_idString

The project identifier for the Cloud Firestore database.

Returns:

  • (String)

    project identifier.



62
63
64
# File 'lib/google/cloud/firestore/client.rb', line 62

def project_id
  service.project
end

#transaction(max_retries: nil) {|transaction| ... } ⇒ CommitResponse

Create a transaction to perform multiple reads and writes that are executed atomically at a single logical point in time in a database.

All changes are accumulated in memory until the block completes. Transactions will be automatically retried when documents change before the transaction is committed. See Transaction.

Examples:

require "google/cloud/firestore"

firestore = Google::Cloud::Firestore.new

firestore.transaction do |tx|
  # Set the data for NYC
  tx.set("cities/NYC", { name: "New York City" })

  # Update the population for SF
  tx.update("cities/SF", { population: 1000000 })

  # Delete LA
  tx.delete("cities/LA")
end

Parameters:

  • max_retries (Integer) (defaults to: nil)

    The maximum number of retries for transactions failed due to errors. Default is 5. Optional.

Yields:

  • (transaction)

    The block for reading data and making changes.

Yield Parameters:

  • transaction (Transaction)

    The transaction object for making changes.

Returns:

See Also:



433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
# File 'lib/google/cloud/firestore/client.rb', line 433

def transaction max_retries: nil
  max_retries = 5 unless max_retries.is_a? Integer
  backoff = { current: 0, delay: 1.0, max: max_retries, mod: 1.3 }

  transaction = Transaction.from_client self
  begin
    yield transaction
    transaction.commit
  rescue Google::Cloud::UnavailableError => err
    # Re-raise if retried more than the max
    raise err if backoff[:current] > backoff[:max]

    # Sleep with incremental backoff before restarting
    sleep backoff[:delay]

    # Update increment backoff delay and retry counter
    backoff[:delay] *= backoff[:mod]
    backoff[:current] += 1

    # Create new transaction and retry
    transaction = Transaction.from_client \
      self, previous_transaction: transaction.transaction_id
    retry
  rescue Google::Cloud::InvalidArgumentError => err
    # Return if a previous call was retried but ultimately succeeded
    return nil if backoff[:current] > 0

    # Re-raise error.
    raise err
  rescue StandardError => err
    # Rollback transaction when handling unexpected error
    transaction.rollback rescue nil

    # Re-raise error.
    raise err
  end
end