Alasql select in arrary of array with uknown index - alasql

suppose I have this structure data
data =[
{
"id":1,
"link":[
{
"id":3
},
{
"id":1
},
{
"id":2
}
]
},
{
"id":2,
"link":[
{
"id":30
},
{
"id":11
},
{
"id":22
}
]
}
]
I want see if my structure have a link with id=11
"SELECT * FROM ? WHERE link->[1]->id=11"
work but because I already know that I must check in index 1. How can I check in all indexes?

The SEARCH function would be good if it was fully implemented
alasql('SEARCH / link / WHERE(id=11) .. / .. FROM ?',[data]);
But the parrent .. selector is not implemented yet.
I suggest doing a (not totally elegant) user defined function:
alasql.fn.deepSearch = function(id, obj){
return alasql("SEARCH / link / WHERE(id=?) FROM ?", [id, [obj]]).length
}
alasql('SELECT * FROM ? WHERE deepSearch(11,_)',[data]);

The correct code is
alasql('SEARCH / AS #a link / WHERE(id=11) #a FROM ?',[data]);
Here AS #a saves current element into the variable #a, and the second #a retrieves it.

Related

ElasticSearch Stored Procedure

Suppose I have documents with structure:
{
name:"some_name",
salary:INT_VAL,
date:YYYY.dd.MMTHH:mm:sssZ,
num_of_months:INT_VAL
}
And now I want to make a query to elastic, that would select top 10 documents that sorted by criteria salary*num_of_months.
How can I do this?
And what if I want to sort by criteria with some logic inside, sth. like
if (num_of_months < 5)
then criteria = salary*100 ;
elseif criteria = salary*200;
endif
sort_by_criteria()
Doing a Sort with a script will enable you to perform calculations on the data and return it in the right order:
GET /myindex/mytype/_search?pretty
{
"sort" :{
"_script" : {
"type" : "number",
"lang": "expression",
"script" : "doc['num_of_months'].value < 5 ? doc['salary']*100 : doc['salary']*200",
"order":"desc"
}
},
"size": 10
}
Note the use of the ternary operator to do the If statement.

How to pass a function to angular ui-grid column total

I'm using angular ui-grid (no ng-grid) and want to pass a function to calculate a column's total value. In the documentation they explicitly say it is possible; it is just that I canĀ“t find how to do it.
This is how I'm showing a total (sum) for another columns:
aggregationType: uiGridConstants.aggregationTypes.sum,
aggregationHideLabel: true,
footerCellFilter: 'currencyFilter',
footerCellClass: 'ui-grid-centerCell'
Now, instead of using uiGridConstants.aggregationTypes.sum, I want to pass a function to calculate the value.
Many thanks and bye ...
My Idea is to Create a method in your Controller like
$scope.sum = function(row){
var sum1 = row.entity.sum1 + row.entity.sum2;
console.log('Sum of Value is = ',sum1);
}
Note : sum1 and sum2 is columnDefs of Field value like
$scope.gridsOptions = {
columnDefs : [
{
field : 'sum1',
name :'xx'
},
{
field : 'sum2',
name : 'xxx'
}
]}
You can also solve this by adding custom tree aggregation.
treeCustomAggregations: {
sum: {
aggregationFn: stats.aggregator.sumSquareErr, finalizerFn: function (aggregation) {
//Do rest of your calculations here
var total = $scope.gridApi.grid.columns[column_number].getAggregationValue() ;
aggregation.value = total ;
aggregation.rendered = (aggregation.value).toFixed(1);
}
Or you can refer this question for custom aggregate template and calling your custom function from it.

Groovy/Grails : How to groupBy multiple keys combined?

I have a list and i want to group by all three keys, i refer to How to group a list of list.
def given = [
[Country:'Japan',Flag:'Yes',Event:'New Year'],
[Country:'china',Flag:'No',Event:'Spring Festival'],
[Country:'uk',Flag:'No',Event:'National Holiday'],
[Country:'us',Flag:'Yes',Event:'Labour Day'],
[Country:'us',Flag:'Yes',Event:'New Year'],
[Country:'uk',Flag:'Yes',Event:'Memorial Day']
]
We can group by:
def mapped = given.groupBy {
[(it["Country"]) : it["Flag"] ] }
How can I group by [(it["Country"]) : it["Flag"] : it["Event"] ] ?
expected results : [['Japan':['Yes':[NewYear]]]:[['Country':'Japan', 'Flag':'Yes', 'Event':'New Year']] , ..
What this is good for, I don't understand. #dmahapatro 's solution gives a much more handlable result. In your example you just want to have a recursive map as key for the group by. I have my strongest doubts, that this will handle the actual grouping case well.
def given = [
[Country:'Japan',Flag:'Yes',Event:'New Year'],
[Country:'china',Flag:'No',Event:'Spring Festival'],
[Country:'uk',Flag:'No',Event:'National Holiday'],
[Country:'us',Flag:'Yes',Event:'Labour Day'],
[Country:'us',Flag:'Yes',Event:'New Year'],
[Country:'uk',Flag:'Yes',Event:'Memorial Day']
]
println given.groupBy{ [(it.Country): [(it.Flag): [it.Event]]] }.inspect()
//=> [['Japan':['Yes':['New Year']]]:[['Country':'Japan', 'Flag':'Yes', 'Event':'New Year']], ...
given.groupBy( { it.Country }, { it.Flag }, { it.Event } )
A method taking 3 closures as arguments.

MongoDB/Mongoid: search for documents matching first item in array

I have a document that has an array:
{
_id: ObjectId("515e10784903724d72000003"),
association_chain: [
{
name: "Product",
id: ObjectId("4e1e2cdd9a86652647000003")
}
],
//...
}
I'm trying to search the collection for documents where the name of the first item in the association_chain array matches a given value.
How can I do this using Mongoid? Or if you only know how this can be done using MongoDB, if you post an example, then I could probably figure out how to do it with Mongoid.
Use the positional operator. You can query the first element of an array with .0 (and the second with .1, etc).
> db.items.insert({association_chain: [{name: 'foo'}, {name: 'bar'}]})
> db.items.find({"association_chain.0.name": "foo"})
{ "_id" : ObjectId("516348865862b60b7b85d962"), "association_chain" : [ { "name" : "foo" }, { "name" : "bar" } ] }
You can see that the positional operator is in effect since searching for foo in the second element doesn't return a hit...
> db.items.find({"association_chain.1.name": "foo"})
>
...but searching for bar does.
> db.items.find({"association_chain.1.name": "bar"})
{ "_id" : ObjectId("516348865862b60b7b85d962"), "association_chain" : [ { "name" : "foo" }, { "name" : "bar" } ] }
You can even index this specific field without indexing all the names of all the association chain documents:
> db.items.ensureIndex({"association_chain.0.name": 1})
> db.items.find({"association_chain.0.name": "foo"}).explain()
{
"cursor" : "BtreeCursor association_chain.0.name_1",
"nscanned" : 1,
...
}
> db.items.find({"association_chain.1.name": "foo"}).explain()
{
"cursor" : "BasicCursor",
"nscanned" : 3,
...
}
Two ways to do this:
1) if you already know that you're only interested in the first product name appearing in "association_chain", then this is better:
db.items.find("association_chain.0.name":"something")
Please note that this does not return all items, which mention the desired product, but only those which mention it in the first position of the 'association_chain' array.
If you want to do this, then you'll need an index:
db.items.ensureIndex({"association_chain.0.name":1},{background:1})
2) if you are looking for a specific product, but you are not sure in which position of the association_chain it appears, then do this:
With the MongoDB shell you can access any hash key inside a nested structure with the '.' dot operator! Please note that this is independent of how deeply that key is nested in the record (isn't that cool?)
You can do a find on an embedded array of hashes like this:
db.items.find("association_chain.name":"something")
This returns all records in the collection which contain the desired product mentioned anywhere in the association_array.
If you want to do this, you should make sure that you have an index:
db.items.ensureIndex({"association_chain.name":1},{background: 1})
See "Dot Notation" on this page: http://docs.mongodb.org/manual/core/document/
You can do this with the aggregation framework. In the mongo shell run a query that unwinds the documents so you have a document per array element (with duplicated data in the other fields), then group by id and any other field you want to include, plus the array with the operator $first. Then just include the $match operator to filter by name or mongoid.
Here's the query to match by the first product name:
db.foo.aggregate([
{ $unwind:"$association_chain"
},
{
$group : {
"_id" : {
"_id" : "$_id",
"other" : "$other"
},
"association_chain" : {
$first : "$association_chain"
}
}
},
{ $match:{ "association_chain.name":"Product"}
}
])
Here's how to query for the first product by mongoid:
db.foo.aggregate([
{ $unwind:"$association_chain"
},
{
$group : {
"_id" : {
"_id" : "$_id",
"other" : "$other"
},
"association_chain" : {
$first : "$association_chain"
}
}
},
{ $match:{ "association_chain.id":ObjectId("4e1e2cdd9a86652647000007")}
}
])

Accessing specific values in array of JSON-Objects

I am using rails 3 with backbone.js 0.53 and currently receive a GET with the following array:
[{"credit_card":
{"id":2,"cc_number":"12345678912345","cc_type":"stack","owner":"overflow"}},
....next objects....]
I have read a lot of the other threads but can't figure out how to access the values.
Is there any way to do this with the backbone-given methods like .get()?
I tried
myArray = eval(arrayJSON)
alert myArray.length #works
but any other way of accessing the single values in an array or iterating over it fails.
Probably I am just missing something here.
Quick example of how to iterate through all your results via underscore:
/* received results mocking */
model.attributes = [
{ "credit_card" : { "id":2, "cc_number":"12345678912345" },
{ "credit_card" : { "id":3, "cc_number":"44444444455555" },
{ "credit_card" : { "id":4, "cc_number":"66666655554332" }
]
/* lets get all results */
results = model.toJSON()
/* loop through all results */
_(results).each(item) {
console.log(item.credit_card.id);
}
/* get result by array pos */
console.log(results[1]); // get 2nd item
Cheers
It might be useful to see more details, but in general you should be able to access elements just fine with the following syntax: alert(myArray[0].credit_card.cc_number);
I even pasted your sample array into jsFiddle and had no issues: http://jsfiddle.net/P4w7T/1/

Resources