RethinkDB javascript to java query - javascript

I am fairly new to RethinkDB, so I was able to create my query in JavaScript the problem now is to translate this query into the Java language.
Can someone with more experience help me please?
r.db('reval').table('measurements').filter({ measurementId: 1478261131038})
.update(function(measurement){
return r.branch(measurement.hasFields('movingObject'),
{ movingObject: measurement('movingObject').append({'x': 10, 'y': 40})},
{ movingObject : [{'x': 0, 'y': 0}]}
)})
UPDATE:
After some help from ... I was able to insert the first object of the array. The problem now is when I want to keep inserting more elements.
I start with this record:
{
"from": null ,
"id": "c94aa215-a47e-4cd0-8f98-1b69d7e93a1d" ,
"measurementId": 1478273740811 ,
"movingObject": null,
"time": null ,
"userObject": null
}
After calling this query:
MapObject myArray = new MapObject().with("x", 20).with("y", 80);
MapObject myArray2 = new MapObject().with("x", 10).with("y", 40);
HashMap run = r.db("reval").table("measurements")
.filter(measurement -> measurement
.g("measurementId")
.eq(1478273740811L))
.update(measurement ->
r.branch(
measurement.hasFields("movingObject"),
r.hashMap("movingObject", measurement.g("movingObject").append(myArray)),
new MapObject().with("movingObject", myArray2)
)).run(connectionFactory.createConnection());
The result was this:
{
"from": null ,
"id": "c94aa215-a47e-4cd0-8f98-1b69d7e93a1d" ,
"measurementId": 1478273740811 ,
"movingObject": {
"x": 10 ,
"y": 40
} ,
"time": null ,
"userObject": null
}
Now when I want to insert another element into my array (in this example {{"x": 20, "y": 80}}) the Java code gives the following error:
{
deleted=0,
inserted=0,
unchanged=0,
replaced=0,
first_error=Expected type ARRAY but found OBJECT.,
errors=1,
skipped=0
}
Can anyone give me some pointer on how to solve this problem, because I think we are very close to the solution.

Something like this:
r.table("measurements")
.filter(measurement -> measurement.g("measurementId").eq(1478261131038L))
.update(measurement -> r.hashMap("movingObject", r.branch(measurement.hasFields("movingObject"),
measurement.g("movingObject").append(r.hashMap("x", 10).with("y", 40)),
r.array(r.hashMap("x", 0).with("y", 0)))));

Related

Nodejs Multiple map arrays to single Json file

I'm new to nodejs and am trying to write a Json parser that will take data from a Json API, allow me to grab the data I want (some of this data I will transform) and then write to a Json file.
I have discovered the map command which is extracting the raw data and this is giving me an array for example
data['home_team'] = json['data'].map(smdata => smdata.localTeam.data.name);
data['awayid'] = json['data'].map(smdata => smdata.visitorTeam.data.id);
data['away_team'] = json['data'].map(smdata => smdata.visitorTeam.data.name);
And this works perfectly, now I'm left with an array which I want to turn into a Json file, I can of course just run a FOR loop and iterate through each of the entries and write to a file but I wondered if there was a more efficent way to do this
Thanks
Take a look at JSON.stringify to turn your data into a string you can write to a file.
In your comments below, you provide an invalid JS structure, an array with keys - maybe a typo with square braces (array) rather than curly braces (object). Or maybe note that Array map returns an array, so you may wish to look at Array.reduce, depending on your data.
let data = {
islive: [90, 90, null, null],
ls: [1, 1, 1, 1],
time: [90, 90, null, null],
status: ['FT', 'FT', 'NS', 'NS'],
starttime: [1616036700, 1616050800, 1616058000, 1616058900],
matchid: [17706353, 17926675, 17869155, 17926676]
};
// Dump it as JSON:
console.log(JSON.stringify(data));
// Pretty print with 2 space indent:
console.log(JSON.stringify(data, {}, 2));
// Write it to file 'my.json':
const fs = require('fs');
fs.writeFileSync(
'my.json',
JSON.stringify(data)
);
Outputs:
{"islive":[90,90,null,null],"ls":[1,1,1,1],"time":[90,90,null,null],"status":["FT","FT","NS","NS"],"starttime":[1616036700,1616050800,1616058000,1616058900],"matchid":[17706353,17926675,17869155,17926676]}
{
"islive": [
90,
90,
null,
null
],
"ls": [
1,
1,
1,
1
],
"time": [
90,
90,
null,
null
],
"status": [
"FT",
"FT",
"NS",
"NS"
],
"starttime": [
1616036700,
1616050800,
1616058000,
1616058900
],
"matchid": [
17706353,
17926675,
17869155,
17926676
]
}

node.js: iterate through nested firebase JSON tree

I am trying to access a nested firebase tree from node.js as follows.
ref.forEach( function(snapshot0) {
snapshot0.child("Meals").forEach( function(snapshot1) {
console.log(snapshot1.val);
});
});
And it will just always tell me that ref.forEach is not a function.
TypeError: refPrices.forEach is not a function
I have defined these as follows.
var db = admin.database();
var ref = db.ref("users");
I have checked these answers
How do I iterate through a large dataset with Firebase / Node.js?
Iterating through nested firebase objects - Javascript
Iterate through nested JSON tree and change values
But I believe according to those my above code should be working, so I am really confused. Also, I have tried to replace forEach by a loop, but I get
TypeError: ref.length is not a function
so I cannot calculate the maximum value of the loop. I have also tried
ref.once("value", function(snapshot0) {
snapshot0.child("Meals").forEach( function(snapshot1) {
console.log(snapshot1.val);
});
});
but in that case it throws the error
TypeError: snapshot0.forEach is not a function
so I pretty much still have the same problem. I cannot work out where my example is different from the links to the solutions above?
Edit: here is what my JSON tree looks like (as per Frank's request). I have only shortened the userID's a little bit.
"users" : {
"ugkvjTuXW2" : {
"Meals" : {
"Meal_2" : {
"priceHist" : [ null, 1, 1, 1, 1, 1, 1 ]
},
"Meal_3" : {
"priceHist" : [ null, 1, 1, 1, 1, 10, 1 ]
},
"Meal_4" : {
"priceHist" : [ null, 1, 1, 1, 1, 1, 1 ]
},
"Meal_5" : {
"priceHist" : [ null, 1, 1, 1, 1, 1, 1 ]
}
}
},
"oJJ1Cojia2" : {
"Meals" : {
"Meal_2" : {
"priceHist" : [ null, 1, 4, 4, 1, 1, 1 ]
},
"Meal_3" : {
"priceHist" : [ null, 1, 1, 1, 1, 10, 1 ]
},
"Meal_4" : {
"priceHist" : [ null, 1, 5, 1, 1, 7, 1 ]
},
"Meal_5" : {
"priceHist" : [ null, 3, 1, 1, 1, 12, 1 ]
}
}
}
}
On your first snippet: a DatabaseReference is nothing more than the path of some data in your Firebase Database. The data itself is not in the ref, so you can't loop over the data.
It's hard to say what's going wrong in your second snippet, because we have no idea what the data under /users looks like. Please edit your question to include a minimal snippet of the JSON (as text, no screenshots please) that is necessary to reproduce the problem. You can get this by clicking the "Export JSON" link in your Firebase Database console.
Update
If you retrieve the value of /users, you get a snapshot with all users. So the first level of children are a node for each user. Then under there you have the meals for each user. Your code is missing a loop for the first level, so:
var ref = admin.database().ref("users");
ref.once("value", function(userSnapshot) {
userSnapshot.forEach(function(userSnapshot) {
userSnapshot.child("Meals").forEach(function(mealSnapshot) {
console.log(mealSnapshot.val());
});
});
});
Also note that you're using numeric indexes, which Firebase recommends against. See this blog post on arrays and the Firebase documentation on handling collections.

JSON/Javascript: return INDEX of array object containing a certain property

Given a JSON object such as this:
{
"something": {
"terms": [
{
"span": [
15,
16
],
"value": ":",
"label": "separator"
},
{
"span": [
16,
20
],
"value": "12.5",
"label": "number"
}
],
"span": [
15,
20
],
"weight": 0.005,
"value": ":12.5"
}
}
I asked a question about parsing the object out where label: number here:
JSON/Javascript: return which array object contains a certain property
I got a sufficient answer there (use filter()), but now need to know the original index of the object.
This issue seems to have the answer, but I simply don't know enough about javascript to translate it into something useful for my particular problem.
The following code successfully returns the object. Now I need to modify this to return the original index of the object:
var numberValue, list = parsed.something.terms.filter(function(a){
return a.label==='number';
});
numberValue = list.length ? list[0].value : -1;
This needs to be a pure javascript solution, no external libraries, etc.
I don't think you can modify the filter solution as within the filter you've lost the indexes.
The solution you've linked to uses the angular external library.
So here is a pure JS solution:
var numberValue = parsed.something.terms
.map(function(d){ return d['label']; })
.indexOf('number');
Array.prototype.indexOf()
Array.prototype.map()
Use forEach and collect the indices of objects that satisfy the a.label==='number' predicate :
var target = parsed.something.terms;
var list = [];
target.forEach(function(element, index){
if (element.label==='number') {
list.push(index)
};
});
var numberValue = list.length ? target[list[0]].value : -1;
console.log(list); // [1]
console.log(numberValue); // 12.5

Please explain .each loop in Jquery

I am new to Jquery. I am calling a Struts 2 action which return a Json object.
I dont understand how actually .each function works in Jquery.
Can you please explain how can I use the variable data, in a complex json using jquery.
{
"od": {
"cwd": [
{
"batchCount": 140,
"batchId": "2121",
"countryName": "Mexico",
"processId": "210002",
"status": "F",
"timeRequired": 140
},
{
"batchCount": 140,
"batchId": "8259",
"countryName": "Japan",
"processId": "220002",
"status": "F",
"timeRequired": 140
}
],
"percentageCompleted": 100,
"remainingTime": "-104Hours -4Mins",
"successBatchCount": 0,
"totalBatchCount": 920
},
"processDateInput": "19/11/2014" }
So here is what I wanted to know that
if json data is parsed into var obj,
Can cwd be accessed by :
var cwd = result.od.cwd;
$.each(cwd, fuction(index, value)){
var batchcount = value.batchcount;
});
and likewise can we parse any json string in jquery.
Thanks and regards,
Tushar
For basic understanding , explain you with your example,
First parent object has two object , "od" and "processDateInput" you can get the values of object directly like od.percentageCompleted , od.remainingTime, processDateInput etc..
So if there is an array inside an object then you need to go for $.each or for loop ,example
$.each(od.cwd,function(index,element){
/*index will be 0 and element will have first cwd[0] value {
"batchCount": 140,
"batchId": "2121",
"countryName": "Mexico",
"processId": "210002",
"status": "F",
"timeRequired": 140
}*/
//similar to this you can get the value
var batchCount=element.batchCount;
});

JSON validation

I'm trying to work with json-framework on iPhone to parse a json string.
When I'm calling this method:
NSDictionary *dictionary = [jsonString JSONValue];
I'm getting the error:
"Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Object value expected for key:
Options\" UserInfo=0x4b5f390 {NSUnderlyingError=0x4b5f320 \"Expected value while
parsing array\", NSLocalizedDescription=Object value expected for key: Options}"
According to this json validator [1]: http://www.jsonlint.com// my json is not valid. But is that so??
My json string looks like this:
{
"Options": [
{
"ID": "7",
"A": "1",
"EAt": new Date(2011,
0,
7,
12,
30,
0),
"Type": "Binary",
}
}
* Edited Json: (still brings up an error)
{
"Options": [
{
"ID": "7",
"A": "1",
"EAt": new Date(2011,
0,
7,
12,
30,
0),
"Type": "Binary"
}
]
}
Your JSON is not valid.
It's because you can't create object instances within JSON. It's not a valid value.
new Date(2011, 0, 7, 12, 30, 0)
And you missed the closing array bracket. Everything else is ok.
remove the comma after ...Binary"
add a ] between the two } }.
Date cant be used like this, see How do I format a Microsoft JSON date? and http://msdn.microsoft.com/en-us/library/bb299886.aspx#intro_to_json_sidebarb
This is valid:
{
"Options": [
{
"ID": "7",
"A": "1",
"EAt": "new Date(2011,0,7,12,30,0)",
"Type": "Binary"
}
]
}
You can't instantiate Date objects (or any objects) in a JSON string.
You need to have whoever's responsible for the code that emits this JSON change it to emit valid JSON. They're putting out something now that can't work with any JSON parser. Maybe they have a customized JSON consumer that can handle such things, but this isn't standard JSON.
If I were you, I'd have them put the string of the current date into that field (so: "2011-07-01 12:30:00") and then parse that in your obj-cusing NSDateFormatter.
If whatever puts out that JSON isn't something you can change, you can always modify it locally before feeding it to the JSON library. It's just a string, nothing magical.

Categories