Sunday, March 26, 2023
Learning Code
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
Learning Code
No Result
View All Result
Home Java

Getting Started with NoSQL and Java

learningcode_x1mckf by learningcode_x1mckf
December 7, 2022
in Java
0
Getting Started with NoSQL and Java
74
SHARES
1.2k
VIEWS
Share on FacebookShare on Twitter


For builders working with Java, connecting to the proper database can present important advantages to their group, whereas additionally making their jobs simpler in the long run. That is very true for databases that mix the flexibleness and agility of NoSQL with the familiarity of SQL.

On this article, I’ll briefly dive into the NoSQL database panorama, in addition to stroll you thru the construction of a easy Java instance that interacts with a NoSQL database.

The Present State of NoSQL Database Applied sciences

Jagadesh Munta

Jagadesh is a principal software engineer at Couchbase. He has more than 20 years of experience in the software development life cycle, QA, DevOps and architecture. Prior to joining Couchbase, Jagadesh held technical roles at Oracle and Sun Microsystems.

NoSQL databases retailer information as JSON paperwork moderately than relational tables with columns and rows. Some NoSQL databases present programming interfaces in each SQL and native doc APIs. Forms of NoSQL databases embody doc databases, key-value shops, wide-column databases and graph databases.

NoSQL databases are recognized to retailer and course of huge quantities of information effectively and have turn into a foundational expertise for a lot of fashionable companies. Many NoSQL databases can be found within the cloud as a totally managed Database as a Service (DBaaS) or for on-premises installations. SDKs in varied programming languages and APIs are utilized by builders to work together with such databases.

Earlier than we get into the code samples, it will be useful to take a look at the pattern information and the way it’s organized inside the database, sometimes called the information mannequin.

Knowledge Mannequin 

On the highest degree of information group, this database comprises a number of buckets. Every bucket can include a number of scopes, and every scope can include a number of collections. Inside collections are JSON paperwork.

This hierarchy is just like the relational database the place databases have schemas, tables and rows, and many others. This hierarchical information container mannequin of this doc database maps very nicely to the relational mannequin: bucket = database, scope = schema, assortment = desk, doc = row.

This mapping permits you to entry information both via the doc information mannequin in collections or the relational mannequin utilizing SQL.

The pattern on this instance is named “Journey Pattern,” a knowledge set for an airline journey data system.

The doc (JSON) information mannequin for the Journey Pattern information set is proven beneath.

The main entities are airline, airport, route, linking airline and airport and lodge as a separate entity.

The diagram beneath reveals the connection between the varied paperwork within the Airline Journey system. It reveals the first key, ID and kind fields that every doc comprises, with extra consultant fields in every sort of doc.

Now we’re prepared to take a look at some fundamental information entry operations on this pattern dataset.

Code Examples 

Now that the essential ideas are lined, allow us to see how to connect with the database, set up a context for a bucket and assortment to work on, carry out easy key-value operations and queries, and at last modify some information within the database.

Connect with the Database Cluster

A connection string sometimes consists of a number URL (IP title/addresses), adopted by a username and password. Utilizing this connection string, you may get a connection object to the database cluster. On this instance, we’re utilizing localhost (127.0.0.1) because the database host. You might need to substitute the DB title, username and password which are acceptable to your database cluster. A connection to the database cluster is represented by a cluster object.

class Program

    public static void essential(String[] args)

    var cluster = Cluster.join(

      “dbName”, “username”, “password”

    );

Set Context to the Applicable Assortment

Allow us to now set up a context for a really particular dataset: a bucket named “travel-sample” that already comprises the Journey Pattern information set assortment. The code beneath units our present context to the default assortment inside the “travel-sample.”

    var bucket = cluster.bucket(“travel-sample”);

    var assortment = bucket.defaultCollection();

Fundamental Key-Worth Operation (Get a Doc)

The important thing worth (KV) or information service affords the only technique to retrieve or mutate information the place the hot button is recognized. The get methodology beneath retrieves particular information (worth) related to a key. On this case, the hot button is “airline_10.”

     strive

        var outcome = assortment.get(“airline_10”);

        System.out.println(outcome.toString());

          

     catch (DocumentNotFoundException ex)

      System.out.println(“Doc not discovered!”);

    

  

}

Question Rows Utilizing SQL

Here’s a snippet of code performing a SQL question to retrieve lodge names within the metropolis of Malibu from the Journey Pattern information set.

strive

      var question =

        “SELECT h.title, h.metropolis, h.state “ +

        “FROM `travel-sample` h “ +

        “WHERE h.sort=”lodge” “ +

          “AND h.metropolis = ‘Malibu’ LIMIT 5;”;

 

      QueryResult outcome = cluster.question(question);

      for (JsonObject row : outcome.rowsAsObject())

        System.out.println(“Lodge: “ + row);

      

     catch (DocumentNotFoundException ex)

      System.out.println(“Doc not discovered!”);

    

  }

}

Question Utilizing Named or Positional Parameters

Question strategies can have named or positional parameters.

Under is a named parameter instance:

The code proceeds to entry the travel-sample database (particularly the title, metropolis and state buckets). The queryOptions() methodology permits the customization of assorted SQL question choices.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

strive

      var question =

        “SELECT h.title, h.metropolis, h.state “ +

        “FROM `travel-sample` h “ +

        “WHERE h.sort = $sort “ +

          “AND h.metropolis = $metropolis LIMIT 5;”;

 

      QueryResult outcome = cluster.question(question,

        queryOptions().parameters(

          JsonObject.create()

            .put(“sort”, “lodge”)

            .put(“metropolis”, “Malibu”)

        ));

          outcome.rowsAsObject().stream().forEach(

        e–> System.out.println(

          “Lodge: “ + e.getString(“title”) + “, “ + e.getString(“metropolis”))

      );

     catch (CouchbaseException ex)

      System.out.println(“Exception: “ + ex.toString());

    

  }

}

Positional parameters permit the order of the tactic parameters to get replaced with placeholders.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

    strive

      var question =

        “SELECT h.title, h.metropolis, h.state “ +

        “FROM `travel-sample` h “ +

        “WHERE h.sort = $1 “ +

          “AND h.metropolis = $2 LIMIT 5;”;

          

      QueryResult outcome = cluster.question(question,

        queryOptions().parameters(JsonArray.from(“lodge”, “Malibu”))      );

    outcome.rowsAsObject().stream().forEach(

        e–> System.out.println(

          “Lodge: “ + e.getString(“title”) + “, “ + e.getString(“metropolis”))

      );

   catch (CouchbaseException ex)

      System.out.println(“Exception: “ + ex.toString());

    

  }

}

Utilizing Subdocument Lookup Operations

Subdocuments are components of the doc which you can atomically and effectively replace and retrieve.

Within the code beneath, the lookupIn operation queries the “airport_1254” doc for a sure path (right here, it’s the geo.alt path). This code permits us to retrieve the doc path utilizing the subdoc get operation: (get("geo.alt")).

strive

      LookupInResult outcome = assortment.lookupIn(

        “airport_1254”,

        Collections.singletonList(get(“geo.alt”))

      );

 

      var str = outcome.contentAs(0, String.class);

      System.out.println(“Altitude = “ + str);

     catch (DocumentNotFoundException ex)

      System.out.println(“Doc not discovered!”);

    

  }

}

Utilizing Subdocument Mutate Operations

Mutation operations modify a number of paths within the doc. Within the code beneath, the mutateIn operation is used to change the airline_10 by utilizing a full doc-level upsert, which can create the worth of an current path with parameters (nation, Canada).

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

   strive

      LookupInResult outcome = assortment.lookupIn(

        “airline_10”, Collections.singletonList(get(“nation”))

      );

      var str = outcome.contentAs(0, String.class);

      System.out.println(“Sub-doc earlier than: “);

      System.out.println(str);

      

     catch (PathNotFoundException e)

      System.out.println(“Sub-doc path not discovered!”);

    

    strive

      assortment.mutateIn(“airline_10”, Arrays.asList(

        upsert(“nation”, “Canada”)

      ));

     catch (PathExistsException e)

      System.out.println(“Sub-doc path exists!”);

    

    strive

      LookupInResult outcome = assortment.lookupIn(

        “airline_10”, Collections.singletonList(get(“nation”))

      );

      var str = outcome.contentAs(0, String.class);

      System.out.println(“Sub-doc after: “);

      System.out.println(str);

   catch (PathNotFoundException e)

      System.out.println(“Sub-doc path not discovered!”);

    

    

  }

}

Utilizing the Upsert Operate

Upsert is used to insert a brand new report or replace an current one. If the doc doesn’t exist, it is going to be created. Upsert is a mixture of insert and replace.

The .put methodology permits the consumer to insert a mapping right into a map. If an current key’s handed, the brand new worth replaces the earlier worth.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

    JsonObject content material = JsonObject.create()

      .put(“nation”, “Iceland”)

      .put(“callsign”, “ICEAIR”)

      .put(“iata”, “FI”)

      .put(“icao”, “ICE”)

      .put(“id”, 123)

      .put(“title”, “Icelandair”)

      .put(“sort”, “airline”);

 

    assortment.upsert(“airline_123”, content material);

      

    strive

      LookupInResult lookupResult = assortment.lookupIn(

        “airline_123”, Collections.singletonList(get(“title”))

      );

 

      var str = lookupResult.contentAs(0, String.class);

      System.out.println(“New Doc title = “ + str);

     catch (PathNotFoundException ex)

      System.out.println(“Doc not discovered!”);

    

    

  }

}

The pattern information set and code examples used above are from the distributed NoSQL cloud database Couchbase. Talking of Databases as a Service, try Couchbase Capella to see how fashionable enterprises are in a position to ship flexibility throughout varied use instances with built-in multimodel and cellular synchronization capabilities, and drive millisecond information response at scale.

These and lots of extra examples could be discovered and run from Couchbase Playground. To attach with different like-minded builders in the neighborhood for extra inspiration, try the Couchbase Forums. For these simply getting began with Java, one other nice useful resource to contemplate is the free on-line Java developer certification course supplied by Couchbase Academy.

GroupCreated with Sketch.

Jagadesh is a principal software engineer at Couchbase. He has more than 20 years of experience in the software development life cycle, QA, DevOps and architecture. Prior to joining Couchbase, Jagadesh held technical roles at Oracle and Sun Microsystems.

Read more from Jagadesh Munta



Source link

You might also like

YS Jagan launches Ragi Java in Jagananna Gorumudda, says focused on intellectual development of students – The Hans India

Disadvantages of Java – TheServerSide.com

Advantages of Java – TheServerSide.com

Share30Tweet19
learningcode_x1mckf

learningcode_x1mckf

Recommended For You

YS Jagan launches Ragi Java in Jagananna Gorumudda, says focused on intellectual development of students – The Hans India

by learningcode_x1mckf
March 26, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

YS Jagan launches Ragi Java in Jagananna Gorumudda, says focused on intellectual development of students  The Hans India Source link

Read more

Disadvantages of Java – TheServerSide.com

by learningcode_x1mckf
March 26, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

Disadvantages of Java  TheServerSide.com Source link

Read more

Advantages of Java – TheServerSide.com

by learningcode_x1mckf
March 26, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

Advantages of Java  TheServerSide.com Source link

Read more

Java Developer Survey Reveals Increased Need for Java … – Benzinga

by learningcode_x1mckf
March 25, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

Java Developer Survey Reveals Increased Need for Java ...  Benzinga Source link

Read more

Technology News | ⚡Oracle Releases Its New Java 20 Programming Language & Development Platform – LatestLY

by learningcode_x1mckf
March 25, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

Technology News | ⚡Oracle Releases Its New Java 20 Programming Language & Development Platform  LatestLY Source link

Read more
Next Post
Google documents how to inject canonical tags using JavaScript

Google documents how to inject canonical tags using JavaScript

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Related News

How to download Minecraft snapshot 22w45a for Java Edition

How to download Minecraft snapshot 22w45a for Java Edition

November 10, 2022
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

A Quick Guide to Lambda Expressions in C++ – MUO – MakeUseOf

February 22, 2023
ClockKit complications cheatsheet – The.Swift.Dev.

ClockKit complications cheatsheet – The.Swift.Dev.

October 12, 2022

Browse by Category

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

RECENT POSTS

  • YS Jagan launches Ragi Java in Jagananna Gorumudda, says focused on intellectual development of students – The Hans India
  • Disadvantages of Java – TheServerSide.com
  • Advantages of Java – TheServerSide.com

CATEGORIES

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

© 2022 Copyright Learning Code

No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#

© 2022 Copyright Learning Code

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?