Using Datastax Java Driver to query a row as a JSON - java

I am trying to use the datastax java driver and retrieve the row as a JSON.
I do the classic
SELECT JSON * from myTable WHERE id=1 and this returns a Json formatted string on CQL.
e.g { "uuid" : "12324567-...." }
This works.
Now when, I try to do the same use the Java driver, I use (in scala)
val resultSet = session.execute(queryString)
I pick up one row from this result set using: "resultSet.one()".
This has the string I need, but how do I pick this up?
Experiment: resultSet.one().getColumnDefinitions.toString
Prints: Columns[ [json] (varchar) ]
Experiment: resultSet.one().toString()
Prints: Row[{"uuid": "3ce19e07-2280-4b31-9475-992bda608e70"}] <- String I need
How do I pick up a simple string that represents the JSON in my program, without trying to split the strings above ?

As noted in the the Cassandra documentation:
The results for SELECT JSON will only include a single column named [json]. This column will contain the same JSON-encoded map representation of a row that is used for INSERT JSON.
In order to access the JSON value of the returned row, you need to use one of the getString methods defined on the Row class to get the value of this column either by index or by name:
Row row = resultSet.one();
String json1 = row.getString(0);
String json2 = row.getString("[json]");

Related

Is it possible to fetch and compare an element which resides in a nested Json string format column in database? Via SQL Query

I have 'a unique-id'. I want to fetch records from table on basis of that unique-id. I have a column named "request body" that contains a nested json string which is of type text. Is there any way i can compare 'unique-id' with the 'unique-id' inside the json string cloumn i-e request body?
Apologies, I am new to stackoverflow.
For anyone looking for the solution, below are the two approaches:
APPROACH 1
SELECT t.request_body
FROM table t
WHERE cast(request_body as JSON) ->> 'uniqueId' ='123'
APPROACH 2
SELECT t.request_body
FROM table t
WHERE (substr(t.request_body, position ('uniqueId' in request_body)+11,3) ='123'
Note: 11 represents lenght of 'uniqueId":"' and 3 for the following id 123

MongoiDB use a String for _id

I'd like to use a unique string per collection to id a doc. I'm using Scala and Casbah but can also use Java if needed.
I know I should use Casbah collection.createIndex but I don't understand the scaladocs.
If my case class is :
case class GroupParams (
_id: String,
//groupId: String,
testPeriodStart: DateTime, // ISO8601 date
variants: Seq[String], //["17","18"]
testPeriodEnd: Option[DateTime])
and I will always use the _id to reference a particular document (no need for _id: ObjectId).
I don't care about sorting/ordering since these will only be accessed as individual docs, never cursored through. There seems no reason to have the overhead of another index on the default _id: ObjectId.
How to I create the index on the collection with _id: String using Casbah? If I should create a new index and leave the default alone can you show how to do this?
Mongo automatically creates index for _id field for all types (ObjectId, String or whatever you want) - mongo indexes
Mongo automatically generate a _id to your index in the collection,
if you want to insert String to the _id you can convert a String to objectId like this : ObjectId.Parse(myString))
See more in the MongoDB API

Hibernate native query return List Object List

I am using an hibernate NQL query which fetches me two columns :
SELECT object_name,
object_name_location
FROM dbo.object_stacks
WHERE object_id IN (SELECT thumb_nail_obj_id
FROM dbo.uois
WHERE Upper(NAME) LIKE Upper('%testobj%'))
When I select only one column i.e only object name - everything works fine but with two columns I am getting an error
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to
java.lang.String
at run time when I try to display result from the list. I tried using String array in the list as well but it doesn't work. Below are my code snippets which give error :
When I use only List :
List<String> Thumbnailpaths = pathquery.list();
System.out.println(Thumbnailpaths.get(i).replace("\\", "\\\\"));
No error at compile time also nothing if leave it as it is but above line to display gives classcast exception.
When I use List array :
List<String[]> Thumbnailpaths = pathquery.list();
System.out.println(Thumbnailpaths.get(i)[0].replace("\\", "\\\\"));
Here again classcast exception at runtime
Also Criteria.ALIAS_TO_ENTITY_MAP doesn't help at all as it makes logic much more complex. I just need 2 column values from a database table.
Please let me know if there is any solution to fetch multiple column results in NQL and then put in list.
Note : Looks like here generics are not displaying and only List is being written in my code snippet
Yes, hibernate will return the Object arrays (Object[]) for this case - return multiple columns. but you still can using the "Entity queries" to return a entity objects rather then the "raw" value.
Unfortunately, Hibernate doesn't provide a standard way to retrieve the results for columns of table and store directly to Entity Object.You have to manually parse the data fetched by your query.
The hibernate query will return List of Object Array i.e. List<Object[]>.
Object[] will contain data from your columns. List is nothing but rows retrieved by query. In your case you can refer following code :
List<Object[]> Thumbnailpaths = pathquery.list();
for(Object[] objArr : Thumbnailpaths)
{
String objName = (String)objArr[0];
String objNameLocation = (String)objArr[1];
System.out.println(objName + " : " +objNameLocation);
}
Above code will help you parse the object[]

How to do Cassandra CQL queries with Astyanax?

I'm using Astyanax version 1.56.26 with Cassandra version 1.2.2
Ok, a little situational overview:
I have created a very simple column family using cqlsh like so:
CREATE TABLE users (
name text PRIMARY KEY,
age int,
weight int
);
I populated the column family (no empty columns)
Querying users via cqlsh yields expected results
Now I want to programmatically query users, so I try something like:
ColumnFamily<String, String> users =
new ColumnFamily<String, String>("users", StringSerializer.get(), StringSerializer.get());
OperationResult<ColumnList<String>> result = ks.prepareQuery(users)
.getRow("bobbydigital") // valid rowkey
.execute();
ColumnList<String> columns = result.getResult();
int weight = columns.getColumnByName("weight").getIntegerValue();
During the assignment of weight a NPE is thrown! :(
My understanding is that the result should have contained all the columns associated with the row containing "bobbydigital" as its row key. I then tried to assign the value in the column named "weight" to the integer variable weight. I know that the variable columns is getting assigned because when I add some debug code right after the assignment, like so:
System.out.println("Column names = " + columns.getColumnNames());
I get the following output:
Column names = [, age, weight]
So why the null pointer? Can someone tell me where I went wrong? Also, why is there blank column name?
UPDATE:
Also if I try querying in a different manner, like so:
Column<String> result = ks.prepareQuery(users)
.getKey("bobbydigital")
.getColumn("weight")
.execute().getResult();
int x = result.getIntegerValue();
I get the following exception:
InvalidRequestException(why:Not enough bytes to read value of component 0)
Thanks in advance for any help you can provide!
I figured out what I was doing incorrectly. The style of querying I was attempting is not valid with CQL tables. To query CQL tables with Astyanax you need to chain the .withCQL method to your prepareQuery method; passing a CQL statement as the argument.
Information specific to using CQL with Astyanax can be found here.
I got this fixed by adding setCqlVersion
this.astyanaxContext = new AstyanaxContext.Builder()
.forCluster("ClusterName")
.forKeyspace(keyspace)
.withAstyanaxConfiguration(
new AstyanaxConfigurationImpl().setCqlVersion(
"3.0.0").setDiscoveryType(
And adding WITH COMPACT STORAGE while creating the table.

how to search a JSONArray inside the JSONObject in JAVA

I have a JSONObject which inturn contains two JSONObjects ( key is rows_map and columns_map)
{
"rows_map":{
"3":["Test","Test","Test","Test","Test",null,null,null,null,null,"2011-10-07 15:47:56.0",null,null],
"2":["test","","","","",null,null,null,"123456789","123456789.user","2011-10-07 12:49:49.0",null,null]
},
"columns_map":{
columns_map":"fld1","fld2","fld3","fld4","fld5","Latitude","Longitude","Altitude","Mobile Number","Name","Time","Message","Advertisment"]
}
}
In rows_map 3 and 2 are record numbers.
Each record is related to columns in columns_map.
I want to get records list based on mobile number column
for eg: recordslist of mobilenumber equal to 123456789
How can i do this.
In the case that you're trying to read a json using java, you should be parsing it as an object rather than via syntax. Take a look at:
https://stackoverflow.com/questions/338586/a-better-java-json-library

Categories

Resources