Create
Jump to the Code block for a combined complete example.
Create a document record
The following example demonstrates creating a document record with a JSON helper library. In Aerospike, JSON documents are handled as a Collection Data Type (CDT). A JSON object is equivalent to a map, and a JSON array is equivalent to a list.
In this example, we create the following JSON document:
employee = { "id": "09", "name": "Nitin", "department":"Finance" }
The JSON document is added to a bin called employee
which is of data
type map. There are some advantages
to holding an entire document in a single bin, rather than spreading out the document’s
fields over multiple bins. There is less metadata overhead when namespaces
contain fewer, larger bins.
Setup
Import the necessary helpers, create a client connection, and create a key.
package main
import ( "encoding/json" as "github.com/aerospike/aerospike-client-go/v6" "log" "os" "runtime" "time")
// Policy Global policy definitionsvar Policy = as.NewPolicy()var WritePolicy = as.NewWritePolicy(0, 0)
func main() { host := "localhost" port := 3000
// use all cpus in the system for concurrency runtime.GOMAXPROCS(runtime.NumCPU())
log.SetOutput(os.Stdout)
cp := as.NewClientPolicy() cp.Timeout = 3 * time.Second
Client, err := as.NewClientWithPolicy(cp, host, port) if err != nil { panic(err) }
namespace := "test" set := "table1"
// clean out old record key, _ := as.NewKey(namespace, set, "key5") deleted, err := Client.Delete(WritePolicy, key) if deleted { log.Println("Deleted key:", key.Value()) } else { log.Println("Did not delete key", key.Value()) } if err != nil { log.Println("Warning - delete failed with error:", err) }
documentExampleInsert(Client, key) log.Println("Example finished successfully.")}
Create a JSON document
Prepare the JSON document to be sent to Aerospike.
func documentExampleInsert(client *as.Client, key *as.Key) {
// create a slice of maps employees := []map[string]string{ {"id": "09", "name": "Nitin", "department": "Finance"}, {"id": "10", "name": "Jonathan", "department": "HumanResources"}, {"id": "11", "name": "Caitlin", "department": "Engineering"}, }
// create a JSON doc of the employees doc, _ := json.Marshal(employees) log.Println("Generated JSON doc: ", string(doc))
// unmarshal the JSON emps := make([]map[string]string, 3, 3) //if err := json.Unmarshal([]byte(doc), &emps); err != nil { if err := json.Unmarshal(doc, &emps); err != nil { panic(err) } log.Println("Restored data structure for JSON doc: ", emps)
Write
Write the document to Aerospike.
// store the restored structure in an Aerospike bin, then write the bin to the record bin := as.NewBin("Employees", emps) log.Println("Attempting to insert record with key'", key.Value(), "'...") if err := client.PutBins(WritePolicy, key, bin); err != nil { panic(err) } log.Println("Insert Successful.")
// read back the record from the database record, err := client.Get(Policy, key, bin.Name) if err != nil { panic(err) } received := record.Bins[bin.Name].([]interface{}) log.Println("Record read back from database: ", received) for index, employeeRecord := range received { employeeMap := employeeRecord.(map[interface{}]interface{}) log.Println("Employee ", index) log.Println("\\tID: ", employeeMap["id"]) log.Println("\\tName: ", employeeMap["name"]) log.Println("\\tDepartment: ", employeeMap["department"]) }
log.Println("Read/Write JSON Doc successful")}
Code block
Expand this section for a single code block to create a document record.
package main
import ( "encoding/json" as "github.com/aerospike/aerospike-client-go/v6" "log" "os" "runtime" "time")
// Policy Global policy definitionsvar Policy = as.NewPolicy()var WritePolicy = as.NewWritePolicy(0, 0)
func main() { host := "localhost" port := 3000
// use all cpus in the system for concurrency runtime.GOMAXPROCS(runtime.NumCPU())
log.SetOutput(os.Stdout)
cp := as.NewClientPolicy() cp.Timeout = 3 * time.Second
Client, err := as.NewClientWithPolicy(cp, host, port) if err != nil { panic(err) } defer Client.Close()
namespace := "test" set := "table1"
// clean out old record key, _ := as.NewKey(namespace, set, "key5") deleted, err := Client.Delete(WritePolicy, key) if deleted { log.Println("Deleted key:", key.Value()) } else { log.Println("Did not delete key", key.Value()) } if err != nil { log.Println("Warning - delete failed with error:", err) }
documentExampleInsert(Client, key) log.Println("Example finished successfully.")}
func documentExampleInsert(client *as.Client, key *as.Key) {
// create a slice of maps employees := []map[string]string{ {"id": "09", "name": "Nitin", "department": "Finance"}, {"id": "10", "name": "Jonathan", "department": "HumanResources"}, {"id": "11", "name": "Caitlin", "department": "Engineering"}, }
// create a JSON doc of the employees doc, _ := json.Marshal(employees) log.Println("Generated JSON doc: ", string(doc))
// unmarshal the JSON emps := make([]map[string]string, 3, 3) //if err := json.Unmarshal([]byte(doc), &emps); err != nil { if err := json.Unmarshal(doc, &emps); err != nil { panic(err) } log.Println("Restored data structure for JSON doc: ", emps)
// store the restored structure in an Aerospike bin, then write the bin to the record bin := as.NewBin("Employees", emps) log.Println("Attempting to insert record with key'", key.Value(), "'...") if err := client.PutBins(WritePolicy, key, bin); err != nil { panic(err) } log.Println("Insert Successful.")
// read back the record from the database record, err := client.Get(Policy, key, bin.Name) if err != nil { panic(err) } received := record.Bins[bin.Name].([]interface{}) log.Println("Record read back from database: ", received) for index, employeeRecord := range received { employeeMap := employeeRecord.(map[interface{}]interface{}) log.Println("Employee ", index) log.Println("\\tID: ", employeeMap["id"]) log.Println("\\tName: ", employeeMap["name"]) log.Println("\\tDepartment: ", employeeMap["department"]) }
log.Println("Read/Write JSON Doc successful")}