Encountered a problem while trying to retrieve JSON data from Cassandra DB using Java and sparkSession

I am currently working on a project that involves reading data from a Cassandra table using Java with sparkSession. The goal is to format the output as JSON.

Here is the structure of my database:

CREATE TABLE user (
  user_id               uuid,
  email                  text, 
  first_name          text,
  last_name          text,
  user_password   text,
  created_date      timestamp, 
  updated_date     timestamp,
  PRIMARY KEY (user_id)
) WITH comment = 'List of all registered and active users';

This is the code snippet designed to return the data in JSON format:

public String getAccountData(UUID userid) throws ClassNotFoundException, SQLException {
        SparkSession sparkSession = config.getSparkSession();
        
        Account account = new Account();
        Encoder<Account> accountEncoder = Encoders.bean(Account.class);

return sparkSession
        .read()
        .format("org.apache.spark.sql.cassandra")
        .options(new HashMap<String, String>() {
            {
                put("keyspace", "chat");
                put("table", "user");
            }
        })
        .load()
        .select("first_name", "last_name", "email")
        .filter("user_id = '" + userid +"'")
        .toJSON()
        .as(accountEncoder)
        .toString();
    }

Below is the Account.java file for reference:

package rest.account;

import java.io.Serializable;


public class Account implements Serializable {

   private String user_id;
   private String first_name;
   private String last_name;   
   private String email;

   public Account(){}

   public Account(String user_id, String first_name, String last_name, String email){
      this.user_id = user_id;
      this.first_name = first_name;
      this.last_name = last_name;
      this.email = email;
   }
   
   public String getId() {
      return user_id;
   }

   public void setId(String user_id) {
      this.user_id = user_id;
   }

   public String getFirstName() {
      return first_name;
   }

   public void setFirstName(String first_name) {
      this.first_name = first_name;
   }

   public String getLastName() {
          return last_name;
       }

   public void setLastName(String lastName) {
   this.last_name = last_name;
   }
       
   public String getEmail() {
      return email;
   }

   public void setEmail(String email) {
      this.email = email;
   }        
}

The error message encountered during execution:

HTTP Status 500 - org.glassfish.jersey.server.ContainerException: org.apache.spark.sql.AnalysisException: cannot resolve 'email' given input columns: [value];

If you have any insights or suggestions on how to resolve this issue, I would greatly appreciate your assistance!

Answer №1

If you're looking for data in your getAccountData function, consider using the following code snippet:

return sparkSession
    .read()
    .format("org.apache.spark.sql.cassandra")
    .options(new HashMap<String, String>() {
        {
            put("keyspace", "chat");
            put("table", "user");
        }
    })
    .load()
    .select("first_name", "last_name", "email")
    .filter("user_id = '" + userid +"'")
    .toJSON()
    .first();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to create a list of JsonArrays within a JSON file using Java?

I am in the process of compiling a list of banned users and storing it using a json file. To achieve this, I create a JsonArray as shown below: JsonObject json = new JsonObject(); json.addProperty("user", user); json.addProperty("reason", reason); json.add ...

Sending JSON data from an iOS app to a Flask backend

Within my Flask Python web application, I store certain parameters in SessionStorage to later send back to Flask and save this data as a text file. Interestingly, the process functions perfectly on PCs and Android devices but encounters issues on iOS devi ...

Encountering a problem in Django when attempting to serialize decimal points, error message reads: 'ValuesListQuerySet' does not contain the attribute '_meta'

I'm trying to serialize a FloatField model instance in django, specifically within a management command. Here's the code I have: def chart_data(request): i = 1 chart = open_flash_chart() chart.title = t for manager in FusionMa ...

Working with JSON parsing in Gson or Jackson when a field can have two distinct types

My JSON data includes a field that contains two different types. "fields":[{"value":"ZIELONE OKO"},{"value":{"@nil":"true"}}] I am struggling with deserializing these values. The model class I am using has the following structure: private String value; ...

Exploring the functionalities of HTTP APIs through Python

As a newcomer to Python programming, I am unfamiliar with all the libraries required for the task at hand. I am interested in using Python to test some HTTP APIs. Specifically, I aim to leverage OAuth and make JSON calls. The relevant APIs can be accessed ...

Strengthening the security of PHP using JSON

I'm working on a PHP script that receives data from an Android application. What security measures should I implement to ensure the safety of this script? Are functions like isset enough? <?php require ('config.php'); $connection=mysqli ...

Which method is considered more RESTful: creating a resource with a JSON payload or using regular POST parameters?

As I develop an API, I ponder whether to implement a factory endpoint that accepts a JSON payload with the resource attributes to be created, utilize regular application/x-www-form-urlencoded parameters in the request body, or if it's inconsequential ...

Using rowspan to display JSON data in AngularJS

Unique Json data: [{ cityName: Seattle, population: 1000000, rank: 1 }, { cityName: Portland, population: 800000, rank: 2 }, { cityName: San Francisco, population: 900000, rank: 3 }, { cityName: Los Ange ...

Performing an asynchronous Ajax call from a partial view in an Asp.net MVC application

Is it possible to use Ajax to fetch data from a form located in a partial view, send it to a controller, and receive a response message? Utilizing Ajax $("#submitContactInfo").on("click", function () { if ($('#contact-form').valid() === true) { ...

Converting JSON arrays into structured arrays using Spark

Does anyone know how to convert an Array of JSON strings into an Array of structures? Sample data: { "col1": "col1Value", "col2":[ "{\"SubCol1\":\"ABCD\",\"SubCol ...

The process of generating a ticket on osticket using the REST API

I'm in the process of utilizing osticket's REST API to generate a ticket (https://github.com/osTicket/osTicket-1.7/blob/develop/setup/doc/api/tickets.md) The issue arises when I attempt to access /api/tickets.json and receive a 404 error. Even t ...

What is the best way to transform a JSON object from a remote source into an Array using JavaScript?

Attempting to transform the JSON object retrieved from my Icecast server into an array for easy access to current listener statistics to display in HTML. Below is the JavaScript code being used: const endpoint = 'http://stream.8k.nz:8000/status-json ...

Using JSON.load with a one-liner JSON isn't going to give you the desired result

I am dealing with JSON data that comes in two different formats - one is a single line, the other is formatted nicely. JSON A: {"id":1, "name":"BoxH", "readOnly":true, "children":[{ "id":100, "name":"Box1", "readOnly":true, "children":[ { "id":1003, "nam ...

php$json_data = json_decode($response);

I am brand new to PHP coming from a background in Python. I was fairly comfortable with retrieving JSON results from websites in Python, but for some reason, I can't seem to get it working in PHP. Here is the code snippet I'm using: <?php $ ...

Converting a JSON array of strings into a TStringList in Delphi 2007

While Delphi 2009 brought in JSON types, I am currently working with Delphi 2007 that lacks these JSON types. I am looking to parse a JSON string that represents an "array of strings" into a TStringList object. For example: ["Ford", "BMW", "Fiat"] I bel ...

Using Powershell to Transform JSON Data into Property Format

I'm currently facing a challenge that I am struggling to overcome due to my lack of experience. Any assistance from the experts on this platform would be immensely helpful :) My task involves converting JSON input into property format. For example: T ...

Issues with jQuery Ajax functionality in Rails application not achieving successful completion

When a card is moved onto another stack, an Ajax call is triggered twice. This only happens when there are multiple stacks. However, if the cards are rearranged within the same stack, the call is triggered only once. The Ajax call sends an array of IDs fo ...

Tips for saving and retrieving req.user using JsonwebToken

Looking for ways to store and retrieve req.user using JsonwebToken in my booking application built with Node. I need to fetch the user information who booked a product and display it on the admin portal. .then((user) => { const maxAge = 3 * 60 * ...

Decoding deeply nested JSON arrays in Swift

Having trouble figuring out how to parse JSON using Swift. The goal is to extract the RouteKey and routeNAME from this XML content. I've experimented with various tutorials and attempted to utilize quicktype, but nothing seems to be working. { "respo ...

Tips for confirming all the elements on a single page with Data Table

Seeking guidance on how to locate every element within the same page and programmatically confirm their visibility using a Data table in Selenium, Java, or Cucumber. Consider a hypothetical situation like this Scenario: Validate all elements in the xyz p ...