Performing connect, set and get

Performing connect, set and get

After you create a connection to Couchbase Server with a client instance, you can perform reads/writes of data with that client instance. Documents reads and writes require a key as parameter; in the case of a document write, you also provide the document value as JSON or binary. The following example demonstrates connecting, setting, then getting a record in PHP:

<?php $cb = new Couchbase(”host:8091", "user", "password"); $cb->set("hello", "Hello World"); var_dump($cb->get("hello")); ?> 

In this case, we create a Couchbase client instance and connect to the default bucket with the username and password of user and password . The same pattern would be used in any given SDK: connect, then perform a set with key/value, and within the same connection, get and output the new value. Here is another example we will build upon later when we do a basic first query. In this case we connect then store the name and age of students. This is using the Ruby SDK.

require 'couchbase' client = Couchbase.connect("http://localhost:8091/pools/default/buckets/newBucket") names = [{'id' => 'doc1', 'name' => 'Aaron', 'age' => 20}, {'id' => 'doc2', 'name' => 'John', 'age' => 24}, {'id' => 'doc3', 'name' => 'Peter', 'age' => 16}, {'id' => 'doc4', 'name' => 'Ralf', 'age' => 12} ] names.each do |name| client.set(name['id'], name ) end begin name = client.get "doc1" puts name rescue Couchbase::Error::NotFound => e puts "There is no record" end 

To begin this example, we import any libraries we require for our application. Then we create a connection to the Couchbase bucket newBucket that we created earlier in Create your first bucket .

After we create a Couchbase client instance, we create a Ruby array containing individual hashes. Each hash contains information for a user. We look through each element in the array and store an entry with the id field as key and the hash contents as JSON documents.

In a begin rescue end block we try to retrieve the first record from Couchbase Server and output it. If the Couchbase client receives an error, it outputs “There is no record.”