DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 2: Understanding Neo4j
  • Introducing Graph Concepts in Java With Eclipse JNoSQL
  • Redis-Based Tomcat Session Management
  • Scaling Databases With EclipseLink And Redis

Trending

  • Manual Sharding in PostgreSQL: A Step-by-Step Implementation Guide
  • The Smart Way to Talk to Your Database: Why Hybrid API + NL2SQL Wins
  • Can You Run a MariaDB Cluster on a $150 Kubernetes Lab? I Gave It a Shot
  • AI Speaks for the World... But Whose Humanity Does It Learn From?
  1. DZone
  2. Data Engineering
  3. Databases
  4. Eclipse JNoSQL: A Quick Overview of Redis, Cassandra, Couchbase, and Neo4j

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.

By 
Otavio Santana user avatar
Otavio Santana
DZone Core CORE ·
Updated Mar. 16, 18 · Tutorial
Likes (10)
Comment
Save
Tweet
Share
14.6K Views

Join the DZone community and get the full member experience.

Join For Free

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 id, name, 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);


        }
    }
}
Database Neo4j Eclipse Redis (company) Open source Graph (Unix)

Opinions expressed by DZone contributors are their own.

Related

  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 2: Understanding Neo4j
  • Introducing Graph Concepts in Java With Eclipse JNoSQL
  • Redis-Based Tomcat Session Management
  • Scaling Databases With EclipseLink And Redis

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!