Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Eclipse JNoSQL: A Quick Overview of Redis, Cassandra, Couchbase, and Neo4j

DZone's Guide to

Eclipse JNoSQL: A Quick Overview of Redis, Cassandra, Couchbase, and Neo4j

In the NoSQL world, there are 4 types of databases: key-value, column, document, and graph. Each one has a particular purpose, level of scalability, and model complexity.

· Database Zone ·
Free Resource

Download "Why Your MySQL Needs Redis" and discover how to extend your current MySQL or relational database to a Redis database.

Eclipse JNoSQL is a framework that helps Java developers use Java EE and NoSQL databases so that they can have scalable applications. In the NoSQL world, there are four types of databases: key-value, column, document, and graph. Each one has a particular purpose, level of scalability, and model complexity. The most straightforward model, key-value, is the most scalable; however, it is limited in the model. In this tutorial, you'll connect with four different databases (Redis as key-value, Cassandra as column, Couchbase as document, and Neo4J as graph) using the same annotation.

Introduction to Databases

  1. Redis: Redis is a software project that implements data structure servers. It is open-source, is networked, is in-memory, and stores keys with optional durability.

  2. Cassandra: Apache Cassandra is a free and open-source distributed database management system designed to handle large amounts of data across many commodity servers, providing high availability with no single point of failure.

  3. Couchbase: Couchbase Server, originally known as Membase, is an open-source, distributed multi-model NoSQL document-oriented database software package that is optimized for interactive applications.

  4. Neo4j is a graph database management system developed by Neo4j, Inc. Described by its developers as an ACID-compliant transactional database with native graph storage and processing, Neo4j is the most popular graph database according to db-engines.com. Neo4j is available in a GPL3-licensed open-source Community Edition, with online backup and high availability extensions licensed under the terms of the Affero General Public License. Neo also licenses Neo4j with these extensions under closed-source commercial terms. Neo4j is implemented in Java and accessible from software written in other languages using the Cypher Query Language through a transactional HTTP endpoint or through the binary "bolt" protocol.

Installation

The first step is to install all the NoSQL databases. To make this process easier, we will install all databases using Docker and their commands below.

Docker

Redis:

docker run --name redis-instance -p 6379:6379 -d redis

Cassandra:

docker run -d --name casandra-instance -p 9042:9042 cassandra

Couchbase:

docker run -d --name couchbase-instance -p 8091-8094:8091-8094 -p 11210:11210 couchbase

Follow the instructions here.

  • Create bucket named gods.

  • Create an index running the query:

CREATE PRIMARY INDEX index_gods on gods;

Model

For this sample, we have the God entity with idname, and power as fields. The annotations use JPA annotation.

@Entity
public class God {

    @Id
    private String id;
    @Column
    private String name;
    @Column
    private String power;
 //... 
}

There is a Repository interface that implements the basic operations in the database. Also, it has the method query, which gives the method that Eclipse JNoSQL will implement to the Java developer:

public interface GodRepository extends Repository<God, String> {

    Optional<God> findByName(String name);
}

Infrastructure Code

In a Maven project, we need to set the dependency project. Eclipse JNoSQL has two layers for mapping. One has the JPA annotation and the other has the JDBC annotation. So, there is one mapping layer to each NoSQL database and one to each driver communication.

  <!-- Mapping dependency -->
        <dependency>
            <groupId>org.jnosql.artemis</groupId>
            <artifactId>artemis-configuration</artifactId>
            <version>${artemis.vesion}</version>
        </dependency>
        <dependency>
            <groupId>org.jnosql.artemis</groupId>
            <artifactId>artemis-column</artifactId>
            <version>${artemis.vesion}</version>
        </dependency>
        <dependency>
            <groupId>org.jnosql.artemis</groupId>
            <artifactId>artemis-document</artifactId>
            <version>${artemis.vesion}</version>
        </dependency>
        <dependency>
            <groupId>org.jnosql.artemis</groupId>
            <artifactId>artemis-key-value</artifactId>
            <version>${artemis.vesion}</version>
        </dependency>
        <dependency>
            <groupId>org.jnosql.artemis</groupId>
            <artifactId>graph-extension</artifactId>
            <version>${artemis.vesion}</version>
        </dependency>


        <!-- Communication driver -->
        <dependency>
            <groupId>org.jnosql.diana</groupId>
            <artifactId>redis-driver</artifactId>
            <version>${artemis.vesion}</version>
        </dependency>
        <dependency>
            <groupId>org.jnosql.diana</groupId>
            <artifactId>cassandra-driver</artifactId>
            <version>${artemis.vesion}</version>
        </dependency>
        <dependency>
            <groupId>org.jnosql.diana</groupId>
            <artifactId>couchbase-driver</artifactId>
            <version>${artemis.vesion}</version>
        </dependency>

        <!-- TinkerPop + Neo4J dependency -->
        <dependency>
            <groupId>org.apache.tinkerpop</groupId>
            <artifactId>gremlin-core</artifactId>
            <version>${tinkerpop.version}</version>
        </dependency>
        <dependency>
            <groupId>com.steelbridgelabs.oss</groupId>
            <artifactId>neo4j-gremlin-bolt</artifactId>
            <version>0.2.27</version>
        </dependency>
        <dependency>
            <groupId>org.neo4j.driver</groupId>
            <artifactId>neo4j-java-driver</artifactId>
            <version>1.5.1</version>
        </dependency>

Also, there is a configuration that has the password, user, and other setting configurations to each NoSQL database.

[
  {
    "description": "The redis key-value configuration",
    "name": "key-value",
    "provider": "org.jnosql.diana.redis.key.RedisConfiguration",
    "settings": {
      "redis-master-host": "localhost",
      "redis-master-port": "6379"
    }
  },
  {
    "description": "The Cassandra column configuration",
    "name": "column",
    "provider": "org.jnosql.diana.cassandra.column.CassandraConfiguration",
    "settings": {
      "cassandra-host-1": "localhost",
      "cassandra-query-1": "CREATE KEYSPACE IF NOT EXISTS gods WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3};",
      "cassandra-query-2": "CREATE COLUMNFAMILY IF NOT EXISTS gods.god (\"_id\" text PRIMARY KEY, name text, power text);",
      "couchbase-password": "123456"
    }
  },
  {
    "description": "The couchbase document configuration",
    "name": "document",
    "provider": "org.jnosql.diana.couchbase.document.CouchbaseDocumentConfiguration",
    "settings": {
      "couchbase-host-1": "localhost",
      "couchbase-user": "root",
      "couchbase-password": "123456"
    }
  },
  {
    "description": "The Neo4J configuration",
    "name": "graph",
    "settings": {
      "url": "bolt://localhost:7687",
      "admin": "neo4j",
      "password": "admin"
    }
  }
]

With the configuration done, the next step is to make the entity manager available to CDI so that it's easier. Eclipse JNoSQL has the ConfigurationUnit annotation that will read from the jnosql.json file. Take the key-value as an example:

@ApplicationScoped
public class BucketManagerProducer {

    private static final String HEROES = "gods";

    @Inject
    @ConfigurationUnit(name = "key-value")
    private BucketManagerFactory<BucketManager> bucketManager;

    @Produces
    @ApplicationScoped
    public BucketManager getBucketManager() {
        return bucketManager.getBucketManager(HEROES);
    }


    public void close(@Disposes BucketManager bucketManager) {
        bucketManager.close();
    }
}

Key-Value

The smoothest model in the NoSQL database, the key-value is key-based. In this example, we're using the Redis implementation. The KeyValueTemplate has a template method pattern, so it has a skeleton to key-value operations.

public class KeyValueTemplateApp {
    public static void main(String[] args) throws InterruptedException {
        try (SeContainer container = SeContainerInitializer.newInstance().initialize()) {
            KeyValueTemplate template = container.select(KeyValueTemplate.class).get();
            God diana = builder().withId("diana").withName("Diana").withPower("hunt").builder();
            template.put(diana);

            Optional<God> result = template.get("diana", God.class);
            result.ifPresent(System.out::println);

            template.put(diana, Duration.ofSeconds(1));
            Thread.sleep(2_000L);
            System.out.println(template.get("diana", God.class));

        }
    }
}

Also, it has support for the Repository interface, nonetheless, with support to the method query once the query is key-based.

public class KeyValueRepositoryApp {
    public static void main(String[] args) throws InterruptedException {
        try (SeContainer container = SeContainerInitializer.newInstance().initialize()) {

            GodRepository repository = container.select(GodRepository.class, DatabaseQualifier.ofKeyValue()).get();
            God diana = builder().withId("diana").withName("Diana").withPower("hunt").builder();
            repository.save(diana);

            Optional<God> result = repository.findById("diana");
            result.ifPresent(System.out::println);


        }
    }
}

Column

The column type also is key-based, despite the fact that there are implementations that enable searching from a different column, as Cassandra does when adding an index. For example, the key-value column has a template to operations, the ColumnTemplate.

public class ColumnTemplateApp {
    public static void main(String[] args) throws InterruptedException {
        try (SeContainer container = SeContainerInitializer.newInstance().initialize()) {
            ColumnTemplate template = container.select(ColumnTemplate.class).get();
            God diana = builder().withId("diana").withName("Diana").withPower("hunt").builder();
            template.insert(diana);

            ColumnQuery query = select().from("god").where("_id").eq("diana").build();

            List<God> result = template.select(query);
            result.forEach(System.out::println);

            template.insert(diana, Duration.ofSeconds(1));
            Thread.sleep(2_000L);
            System.out.println(template.select(query));

        }
    }
}

Also, the repository:

public class ColumnRepositoryApp {
    public static void main(String[] args)  {
        try (SeContainer container = SeContainerInitializer.newInstance().initialize()) {

            GodRepository repository = container.select(GodRepository.class, DatabaseQualifier.ofColumn()).get();
            God diana = builder().withId("diana").withName("Diana").withPower("hunt").builder();
            repository.save(diana);

            Optional<God> result = repository.findById("diana");
            result.ifPresent(System.out::println);


        }
    }
}

Document

The document, in general, has a better approach to reading entities. It has better assistance to find fields than the key/ID. It has DocumentTemplate to do document operations, as the column API and the document query have a fluent API.

public class DocumentTemplateApp {
    public static void main(String[] args) throws InterruptedException {
        try (SeContainer container = SeContainerInitializer.newInstance().initialize()) {
            DocumentTemplate template = container.select(DocumentTemplate.class).get();
            God diana = builder().withId("diana").withName("Diana").withPower("hunt").builder();
            template.insert(diana);

            DocumentQuery query = select().from("god").where("name").eq("Diana").build();

            List<God> result = template.select(query);
            result.forEach(System.out::println);

            template.insert(diana, Duration.ofSeconds(1));
            Thread.sleep(2_000L);
            System.out.println(template.select(query));

        }
    }
}

Another good point in the document is that it might find by ID without any secondary index.

public class DocumentRepositoryApp {
    public static void main(String[] args) throws InterruptedException {
        try (SeContainer container = SeContainerInitializer.newInstance().initialize()) {

            GodRepository repository = container.select(GodRepository.class, DatabaseQualifier.ofDocument()).get();
            God diana = builder().withId("diana").withName("Diana").withPower("hunt").builder();
            repository.save(diana);

            Optional<God> result = repository.findById("diana");
            result.ifPresent(System.out::println);


        }
    }
}

Graph

The graph is the type that allows more complex entities and includes the deepest relationships, like properties or directions. To represent this, it has a particular object, the edge, to make it happen. Against the other's communications layer, Eclipse JNoSQL doesn't create the graph communication API because that already exists in Apache TinkerPop. So, it provides a mapping API with a tight integration with this Apache framework:

public class GraphTemplateApp {
    public static void main(String[] args)  {
        try (SeContainer container = SeContainerInitializer.newInstance().initialize()) {
            GraphTemplate template = container.select(GraphTemplate.class).get();
            Graph graph = container.select(Graph.class).get();

            God diana = builder().withId("diana").withName("Diana").withPower("hunt").builder();
            template.insert(diana);
            graph.tx().commit();
            Optional<God> result = template.getTraversalVertex().hasLabel(God.class).has("name", "Diana").next();

            result.ifPresent(System.out::println);

        }
    }
}

The Graph API offers a repository to query using Gremlin.

public class GraphRepositoryApp {
    public static void main(String[] args) {
        try (SeContainer container = SeContainerInitializer.newInstance().initialize()) {

            GodRepository repository = container.select(GodRepository.class, DatabaseQualifier.ofGraph()).get();
            Graph graph = container.select(Graph.class).get();

            God diana = builder().withName("Diana").withPower("hunt").builder();
            repository.save(diana);
            graph.tx().commit();
            Optional<God> result = repository.findByName("Diana");
            result.ifPresent(System.out::println);


        }
    }
}

Read "Developing Apps Using Active-Active Redis Enterprise" and discover the advantages over other active-actve databases.

Topics:
jnosql ,cassandra ,redis ,couchbase ,neo4j ,database ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}