Skip to main content

Java Code Example For Aerospike Simple Operations [Read, Write, Delete]

                     In the following post we will see sample java code to perform simple operation (read, write and delete Records) from Aerospike Database System. The code are self explanatory, follow the comments in code for better understanding. You only need a jar for java client which you can download from aerospike official website.


Main Class
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.aerospike.client.AerospikeClient;
import com.aerospike.client.AerospikeException;
import com.aerospike.client.Bin;
import com.aerospike.client.Host;
import com.aerospike.client.Key;
import com.aerospike.client.Record;
import com.aerospike.client.Value;
import com.aerospike.client.policy.ClientPolicy;
import com.aerospike.client.policy.WritePolicy;

public class Aerospike {
    public static void main(String... args){
 //Get host
 Host host = new Host("127.0.0.1",3000);
 
 //create client and write policy
 ClientPolicy clientPolicy = new ClientPolicy();
 WritePolicy writePolicy = new WritePolicy();
 
 /*Get client object by creating connections | throw exception if server credential is not correct or
 server has not been started yet */
 AerospikeClient client = new AerospikeClient(clientPolicy, host);
 
 try {
  //get key
  Key key = new Key("test", "aero_yatra", "product");
  
  //Create Bins for various data types
  Bin b1 = new Bin("Orgnization", "MATRIX"); //String
  
  Bin b2 = new Bin("total-members", 201); //int
  
  Bin b3 = new Bin("total-budget", 5850283.00); //flaot
  
  List ls = new ArrayList();
  ls.add("yatra");
  ls.add("mmt");
  Bin b4 = new Bin("list", Value.getAsList(ls)); //List
  
  Map map = new HashMap();
  map.put("Hey", "Hello");
  map.put("Hoo", "Haa");
  Bin b5 = new Bin("map", Value.getAsMap(map)); //Map
  
  Person p = new Person("Rohit", 23, "Cyber Park");
  Bin b6 = new Bin("pojo", Value.getAsBlob(p)); //Simple POJO for a Person Object
  
  
  //Write the records
  client.put(writePolicy, key, b1, b2, b3, b4, b5, b6);
  
  //Read the records
  Record record = client.get(null, key);
  
  //Print all the record 
  for(String binKey : record.bins.keySet()){
   System.out.println(binKey+" <-----> "+record.bins.get(binKey));
  }
  
  //To access the POJO object from records we need to cast the Reference
  Person person = (Person)record.bins.get("pojo"); //Cast the reference to Person
  System.out.println("\nAccessing the POJO object");
  person.display();
  
  //Now remove all the record based on the key
  //client.delete(writePolicy, key);
  
  System.out.println("\nAll the operations {Write, Read, Delete} has been performed successfull");
 } catch (AerospikeException e) {
  e.printStackTrace();
 }finally{
  client.close();
 }
 
    }
}

Person Class
public class Person implements java.io.Serializable{
 private final static long serialVersionUID = 546263L;
 private String name;
 private int age;
 private String address;
 
 public Person(String name, int age, String addr){
  this.name = name;
  this.age = age;
  this.address = addr;
 }
 
 public void display(){
  System.out.println("The field details for the Person Object");
  System.out.println("name : "+this.name);
  System.out.println("age : "+this.age);
  System.out.println("address : "+this.address);
 }
 
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public String getAddress() {
  return address;
 }
 public void setAddress(String address) {
  this.address = address;
 }
}


Comments

Popular posts from this blog

How to Create a Namespace in Aerospike Database

                      T his post is about creating a namespace in Aerospike. I could not find any concrete method to create a namespace like create database in MySQL and MongoDB. So I am suggesting a way to create a namespace in Aerospike Database. Step-1: Locate config file aerospike.conf and open it in your favorite editor and make sure you have permission to modify the file. In my system the path of file /etc/aerospike/aerospike.conf (Default in Ubuntu). Here the content of the file. # Aerospike database configuration file. service { user root group root paxos-single-replica-limit 1 # Number of nodes where the replica pidfile /var/run/aerospike/asd.pid service-threads 4 transaction-queues 4 transaction-threads-per-queue 4 proto-fd-max 15000 } logging { # Log file must be an absolute path. file /var/log/aerospike/aerospike.log { context any info } } network { service { address any port 3000 } heartbeat { mode multicast address 239.1.99.222 p

java.lang.IllegalArgumentException: Could not instantiate implementation: org.janusgraph.diskstorage.cassandra.thrift.CassandraThriftStoreManager

If you are trying to get started with Janus Graph with Apache Cassandra. You may get the following error. Caused by: org.janusgraph.diskstorage.TemporaryBackendException: Temporary failure in storage backend at org.janusgraph.diskstorage.cassandra.thrift.CassandraThriftStoreManager.getCassandraPartitioner(CassandraThriftStoreManager.java:219) ~[janusgraph-cassandra-0.2.0.jar:na] at org.janusgraph.diskstorage.cassandra.thrift.CassandraThriftStoreManager.<init>(CassandraThriftStoreManager.java:198) ~[janusgraph-cassandra-0.2.0.jar:na] ... 48 common frames omitted Caused by: org.apache.thrift.transport.TTransportException: java.net.ConnectException: Connection refused (Connection refused) at org.apache.thrift.transport.TSocket.open(TSocket.java:187) ~[libthrift-0.9.2.jar:0.9.2] at org.apache.thrift.transport.TFramedTransport.open(TFramedTransport.java:81) ~[libthrift-0.9.2.jar:0.9.2] at org.janusgraph.diskstorage.cassandra.thrift.thriftpool.CTConnectionFactory.makeR

com.mongodb.MongoCommandException: Command failed with error 18: 'Authentication failed.' on server

If you are trying to connect Mongo DB Server and it insanely throwing following error. com.mongodb.MongoTimeoutException : Timed out after 1000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=192.168.1.10:27010, type=UNKNOWN, state=CONNECTING, exception={ com.mongodb.MongoSecurityException: Exception authenticating MongoCredential {mechanism=null, userName='user123', source='admin', password=<hidden>, mechanismProperties={}}}, caused by {com.mongodb.MongoCommandException: Command failed with error 18 : 'Authentication failed.' on server 192.168.1.10:27010 . The full response is { "ok" : 0.0, "code" : 18, "errmsg" : "Authentication failed." }}}] If you start looking the error content First you encounter with Timeout Exception which may mislead you. It is basically an authentication error. I