Class: Couchbase::Cluster

Inherits:
Object
  • Object
show all
Defined in:
lib/couchbase/cluster.rb,
lib/couchbase/query_options.rb,
lib/couchbase/search_options.rb,
lib/couchbase/analytics_options.rb

Overview

The main entry point when connecting to a Couchbase cluster.

Defined Under Namespace

Classes: AnalyticsMetaData, AnalyticsMetrics, AnalyticsResult, AnalyticsWarning, QueryMetaData, QueryMetrics, QueryResult, QueryWarning

Constant Summary collapse

SearchQuery =
Couchbase::SearchQuery
SearchSort =
Couchbase::SearchSort
SearchFacet =
Couchbase::SearchFacet
SearchRowLocation =
Couchbase::SearchRowLocation
SearchRowLocations =
Couchbase::SearchRowLocations
SearchFacetResult =
Couchbase::SearchFacetResult
SearchRow =
Couchbase::SearchRow
SearchResult =
Couchbase::SearchResult
SearchMetaData =
Couchbase::SearchMetaData
SearchMetrics =
Couchbase::SearchMetrics

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.connect(connection_string_or_config, options) ⇒ Cluster .connect(connection_string_or_config, username, password, options) ⇒ Cluster

Note:

The couchbase2:// scheme is currently at stability uncommitted

Connect to the Couchbase cluster

Examples:

Explicitly create options object and initialize PasswordAuthenticator internally

options = Cluster::ClusterOptions.new
options.authenticate("Administrator", "password")
Cluster.connect("couchbase://localhost", options)

Pass authenticator object to Options

Cluster.connect("couchbase://localhost",
  Options::Cluster(authenticator: PasswordAuthenticator.new("Administrator", "password")))

Shorter version, more useful for interactive sessions

Cluster.connect("couchbase://localhost", "Administrator", "password")

Authentication with TLS client certificate (note couchbases:// schema)

Cluster.connect("couchbases://localhost?trust_certificate=/tmp/ca.pem",
  Options::Cluster(authenticator: CertificateAuthenticator.new("/tmp/certificate.pem", "/tmp/private.key")))

Overloads:

  • .connect(connection_string_or_config, options) ⇒ Cluster

    Parameters:

    • connection_string_or_config (String, Configuration)

      connection string used to locate the Couchbase Cluster

    • options (Options::Cluster)

      custom options when creating the cluster connection

  • .connect(connection_string_or_config, username, password, options) ⇒ Cluster

    Shortcut for PasswordAuthenticator

    Parameters:

    • connection_string_or_config (String)

      connection string used to locate the Couchbase Cluster

    • username (String)

      name of the user

    • password (String)

      password of the user

    • options (Options::Cluster, nil)

      custom options when creating the cluster connection

Returns:

See Also:



69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/couchbase/cluster.rb', line 69

def self.connect(connection_string_or_config, *options)
  connection_string = if connection_string_or_config.is_a?(Configuration)
                        connection_string_or_config.connection_string
                      else
                        connection_string_or_config
                      end
  if connection_string =~ /\Acouchbases?:\/\/.*\z/i || !connection_string.include?("://")
    Cluster.new(connection_string_or_config, *options)
  else
    ClusterRegistry.instance.connect(connection_string_or_config, *options)
  end
end

Instance Method Details

#analytics_indexesManagement::AnalyticsIndexManager



225
226
227
# File 'lib/couchbase/cluster.rb', line 225

def analytics_indexes
  Management::AnalyticsIndexManager.new(@backend)
end

#analytics_query(statement, options = Options::Analytics::DEFAULT) ⇒ AnalyticsResult

Performs an analytics query

Examples:

Select name of the given user

cluster.analytics_query("SELECT u.name AS uname FROM GleambookUsers u WHERE u.id = $user_id ",
                        Options::Analytics(named_parameters: {user_id: 2}))

Parameters:

  • statement (String)

    the N1QL query statement

  • options (Options::Analytics) (defaults to: Options::Analytics::DEFAULT)

    the custom options for this query

Returns:



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/couchbase/cluster.rb', line 147

def analytics_query(statement, options = Options::Analytics::DEFAULT)
  resp = @backend.document_analytics(statement, options.to_backend)

  AnalyticsResult.new do |res|
    res.transcoder = options.transcoder
    res. = AnalyticsMetaData.new do |meta|
      meta.status = resp[:meta][:status]
      meta.request_id = resp[:meta][:request_id]
      meta.client_context_id = resp[:meta][:client_context_id]
      meta.signature = JSON.parse(resp[:meta][:signature]) if resp[:meta][:signature]
      meta.profile = JSON.parse(resp[:meta][:profile]) if resp[:meta][:profile]
      meta.metrics = AnalyticsMetrics.new do |metrics|
        if resp[:meta][:metrics]
          metrics.elapsed_time = resp[:meta][:metrics][:elapsed_time]
          metrics.execution_time = resp[:meta][:metrics][:execution_time]
          metrics.result_count = resp[:meta][:metrics][:result_count]
          metrics.result_size = resp[:meta][:metrics][:result_size]
          metrics.error_count = resp[:meta][:metrics][:error_count]
          metrics.warning_count = resp[:meta][:metrics][:warning_count]
          metrics.processed_objects = resp[:meta][:metrics][:processed_objects]
        end
      end
      res[:warnings] = resp[:warnings].map { |warn| AnalyticsWarning.new(warn[:code], warn[:message]) } if resp[:warnings]
    end
    res.instance_variable_set(:@rows, resp[:rows])
  end
end

#bucket(name) ⇒ Bucket

Returns an instance of the Bucket

Parameters:

  • name (String)

    name of the bucket

Returns:



87
88
89
# File 'lib/couchbase/cluster.rb', line 87

def bucket(name)
  Bucket.new(@backend, name)
end

#bucketsManagement::BucketManager



215
216
217
# File 'lib/couchbase/cluster.rb', line 215

def buckets
  Management::BucketManager.new(@backend)
end

#diagnostics(options = Options::Diagnostics::DEFAULT) ⇒ DiagnosticsResult

Creates diagnostic report that can be used to determine the health of the network connections.

It does not proactively perform any I/O against the network

Parameters:

Returns:



248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'lib/couchbase/cluster.rb', line 248

def diagnostics(options = Options::Diagnostics::DEFAULT)
  resp = @backend.diagnostics(options.report_id)
  DiagnosticsResult.new do |res|
    res.version = resp[:version]
    res.id = resp[:id]
    res.sdk = resp[:sdk]
    resp[:services].each do |type, svcs|
      res.services[type] = svcs.map do |svc|
        DiagnosticsResult::ServiceInfo.new do |info|
          info.id = svc[:id]
          info.state = svc[:state]
          info.last_activity_us = svc[:last_activity_us]
          info.remote = svc[:remote]
          info.local = svc[:local]
          info.details = svc[:details]
        end
      end
    end
  end
end

#disconnectvoid

This method returns an undefined value.

Closes all connections to services and free allocated resources



237
238
239
# File 'lib/couchbase/cluster.rb', line 237

def disconnect
  @backend.close
end

#ping(options = Options::Ping::DEFAULT) ⇒ PingResult

Performs application-level ping requests against services in the couchbase cluster

Parameters:

Returns:



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/couchbase/cluster.rb', line 274

def ping(options = Options::Ping::DEFAULT)
  resp = @backend.ping(nil, options.to_backend)
  PingResult.new do |res|
    res.version = resp[:version]
    res.id = resp[:id]
    res.sdk = resp[:sdk]
    resp[:services].each do |type, svcs|
      res.services[type] = svcs.map do |svc|
        PingResult::ServiceInfo.new do |info|
          info.id = svc[:id]
          info.state = svc[:state]
          info.latency = svc[:latency]
          info.remote = svc[:remote]
          info.local = svc[:local]
          info.error = svc[:error]
        end
      end
    end
  end
end

#query(statement, options = Options::Query::DEFAULT) ⇒ QueryResult

Performs a query against the query (N1QL) services

Examples:

Select first ten hotels from travel sample dataset

cluster.query("SELECT * FROM `travel-sample` WHERE type = $type LIMIT 10",
              Options::Query(named_parameters: {type: "hotel"}, metrics: true))

Execute query with consistency requirement. Make sure that the index is in sync with selected mutation

res = collection.upsert("user:42", {
  "name" => "Brass Doorknob",
  "email" => "[email protected]",
})
cluster.query("SELECT name, email FROM `mybucket`",
              Options::Query(consistent_with: MutationState.new(res.mutation_token)))

Parameters:

  • statement (String)

    the N1QL query statement

  • options (Options::Query) (defaults to: Options::Query::DEFAULT)

    the custom options for this query

Returns:



109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/couchbase/cluster.rb', line 109

def query(statement, options = Options::Query::DEFAULT)
  resp = @backend.document_query(statement, options.to_backend)

  QueryResult.new do |res|
    res. = QueryMetaData.new do |meta|
      meta.status = resp[:meta][:status]
      meta.request_id = resp[:meta][:request_id]
      meta.client_context_id = resp[:meta][:client_context_id]
      meta.signature = JSON.parse(resp[:meta][:signature]) if resp[:meta][:signature]
      meta.profile = JSON.parse(resp[:meta][:profile]) if resp[:meta][:profile]
      meta.metrics = QueryMetrics.new do |metrics|
        if resp[:meta][:metrics]
          metrics.elapsed_time = resp[:meta][:metrics][:elapsed_time]
          metrics.execution_time = resp[:meta][:metrics][:execution_time]
          metrics.sort_count = resp[:meta][:metrics][:sort_count]
          metrics.result_count = resp[:meta][:metrics][:result_count]
          metrics.result_size = resp[:meta][:metrics][:result_size]
          metrics.mutation_count = resp[:meta][:metrics][:mutation_count]
          metrics.error_count = resp[:meta][:metrics][:error_count]
          metrics.warning_count = resp[:meta][:metrics][:warning_count]
        end
      end
      meta.warnings = resp[:warnings].map { |warn| QueryWarning.new(warn[:code], warn[:message]) } if resp[:warnings]
    end
    res.instance_variable_set(:@rows, resp[:rows])
  end
end

#query_indexesManagement::QueryIndexManager



220
221
222
# File 'lib/couchbase/cluster.rb', line 220

def query_indexes
  Management::QueryIndexManager.new(@backend)
end

#search(index_name, search_request, options = Options::Search::DEFAULT) ⇒ SearchResult

Performs a request against the Full Text Search (FTS) service.

Parameters:

  • index_name (String)

    the name of the search index

  • search_request (SearchRequest)

    the request

  • options (Options::Search) (defaults to: Options::Search::DEFAULT)

    the custom options for this search request

Returns:



203
204
205
206
207
# File 'lib/couchbase/cluster.rb', line 203

def search(index_name, search_request, options = Options::Search::DEFAULT)
  encoded_query, encoded_req = search_request.to_backend
  resp = @backend.document_search(nil, nil, index_name, encoded_query, encoded_req, options.to_backend(show_request: false))
  convert_search_result(resp, options)
end

#search_indexesManagement::SearchIndexManager



230
231
232
# File 'lib/couchbase/cluster.rb', line 230

def search_indexes
  Management::SearchIndexManager.new(@backend)
end

#search_query(index_name, query, options = Options::Search::DEFAULT) ⇒ SearchResult

Performs a Full Text Search (FTS) query

Examples:

Return first 10 results of “hop beer” query and request highlighting

cluster.search_query("beer_index", Cluster::SearchQuery.match_phrase("hop beer"),
                     Options::Search(
                       limit: 10,
                       fields: %w[name],
                       highlight_style: :html,
                       highlight_fields: %w[name description]
                     ))

Parameters:

  • index_name (String)

    the name of the search index

  • query (SearchQuery)

    the query tree

  • options (Options::Search) (defaults to: Options::Search::DEFAULT)

    the custom options for this search query

Returns:



191
192
193
194
# File 'lib/couchbase/cluster.rb', line 191

def search_query(index_name, query, options = Options::Search::DEFAULT)
  resp = @backend.document_search(nil, nil, index_name, JSON.generate(query), {}, options.to_backend)
  convert_search_result(resp, options)
end

#usersManagement::UserManager



210
211
212
# File 'lib/couchbase/cluster.rb', line 210

def users
  Management::UserManager.new(@backend)
end