Who can help me with creating dynamic multidimensional array using recursion.
I need to create a function with the depth of the array and the number of children
The depth of the array may be of different sizes
class Item {
public int id;
public Map<Integer, Item>[] children;
}
Map<Integer, Item> items = new HashMap<>();
function void build(int depth, int countChildren) {
...
}
function Item createItem() {
Item item = new Item();
item.id = Math.Random(0,10000);
return item;
}
Array looks like this
Image link
[
[
'id' => 1,
'children' => [
[
'id' => 10,
'children' => [
[
'id' => 100,
'children' => [
[
'id' => 1000,
],
[
'id' => 2000,
],
]
],
[
'id' => 200,
'children' => [
[
'id' => 1000,
],
[
'id' => 2000,
],
]
],
]
],
[
'id' => 20,
'children' => [
[
'id' => 100,
'children' => [
[
'id' => 1000,
],
[
'id' => 2000,
],
]
],
[
'id' => 200,
'children' => [
[
'id' => 1000,
],
[
'id' => 2000,
],
]
],
]
],
]
],
[
'id' => 1,
'children' => [
[
'id' => 10,
'children' => [
[
'id' => 100,
'children' => [
[
'id' => 1000,
],
[
'id' => 2000,
],
]
],
[
'id' => 200,
'children' => [
[
'id' => 1000,
],
[
'id' => 2000,
],
]
],
]
],
[
'id' => 20,
'children' => [
[
'id' => 100,
'children' => [
[
'id' => 1000,
],
[
'id' => 2000,
],
]
],
[
'id' => 200,
'children' => [
[
'id' => 1000,
],
[
'id' => 2000,
],
]
],
]
],
]
],
];
Related
Given the following code snippet:
<?php
require "db_conn.php";
$sql = "SELECT category,product_code,product_name,unit,quantity FROM items INNER JOIN categories ON items.category_id=categories.id";
$res = $conn->query($sql)->fetchAll();
$structured = [];
if ($res) {
foreach ($res as $key => $row)
{
$structured[$row['category']]['items'][] = [
'product_code' => $row['product_code'],
'product_name' => $row['product_name'],
'unit' => $row['unit'],
'quantity' => $row['quantity'],
];
}
echo json_encode([$structured]);
}
outputs the following JSON response:
[{
"BABY ITEMS": {
"items": [{
"product_code": "151128",
"product_name": "BOUNCY BABY WIPES 80'S",
"unit": "CARTON",
"quantity": "5.00"
}]
},
"CONFECTIONS\/PASTRIES": {
"items": [{
"product_code": "130570",
"product_name": "NUVITA FAMILY 75G",
"unit": "CARTON",
"quantity": "1.00"
}, {
"product_code": "115165",
"product_name": "NUVITA MAGIK LEMON CRM 60*2'S",
"unit": "CARTON",
"quantity": "2.00"
}]
},
"HOUSEHOLD ITEMS": {
"items": [{
"product_code": "150278",
"product_name": "BOUNCY BABY DIAPER 10'S MINI",
"unit": "CARTON",
"quantity": "1.00"
}]
}
}]
How do I modify this part of code:
$structured[$row['category']]['items'][]
to output:
"category": "BABY ITEMS",
instead of:
"BABY ITEMS":
The expected JSON is (Handwritten):
[{
"category": "BABY ITEMS",
"items": [{
"product_code": "151128",
"product_name": "BOUNCY BABY WIPES 80'S",
"unit": "CARTON",
"quantity": "5.00"
}]
},
{
"category": "CONFECTIONS/PASTRIES",
"items": [{
"product_code": "130570",
"product_name": "NUVITA FAMILY 75G",
"unit": "CARTON",
"quantity": "1.00"
},
{
"product_code": "115165",
"product_name": "NUVITA MAGIK LEMON CRM 60*2'S",
"unit": "CARTON",
"quantity": "3.00"
},
{
"product_code": "115160",
"product_name": "NUVITA MAGIK S.BERRY CRM 60*2'S",
"unit": "CARTON",
"quantity": "2.00"
}
]
},
{
"category": "HOUSEHOLD ITEMS",
"items": [{
"product_code": "150278",
"product_name": "BOUNCY BABY DIAPER 10'S MINI",
"unit": "CARTON",
"quantity": "1.00"
}]
},
{
"category": "PERSONAL CARE",
"items": [{
"product_code": "160200",
"product_name": "ALL TYME ULTRA REGULAR 8'S",
"unit": "CARTON",
"quantity": "2.00"
},
{
"product_code": "160309",
"product_name": "ALL TYME ULTRA MEDIUM 8'S",
"unit": "CARTON",
"quantity": "4.00"
},
{
"product_code": "160235",
"product_name": "GOLDEN SHOE POLSIH 50ML BLACK",
"unit": "CARTON",
"quantity": "1.00"
},
{
"product_code": "190251",
"product_name": "ALL TYME ULTRA MEDIUM 16'S",
"unit": "CARTON",
"quantity": "2.00"
}]
}
]
I really need the JSON formatted as above as am using it to create a nested category and items RecyclerView. This is how am parsing in android java:
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject objCategory = jsonArray.getJSONObject(i);
System.out.println("Category: " + objCategory.getString("category"));
// fetch item details and store it in arraylists
JSONArray itemArray = objCategory.getJSONArray("items");
//System.out.println("Item length: " + itemArray.length());
ParentItem category = new
ParentItem(objCategory.getString("category"),OrderItemsList(itemArray));
orderFetchingList.add(category);
}
Please see the following code (fully functional). I mocked $res with few records and copied your code to fill $structured. Below that, please find my code to restructure the data in order the get the desired JSON output
$res = [
[
'category' => 'BABY',
'product_code' => '123',
'product_name' => 'BABY STUFF',
'unit' => 1,
'quantity' => 999,
],
[
'category' => 'BABY',
'product_code' => '125',
'product_name' => 'BABY EAT',
'unit' => 1,
'quantity' => 999,
],
[
'category' => 'MEN',
'product_code' => '124',
'product_name' => 'MEN STUFF',
'unit' => 2,
'quantity' => 888,
]
];
echo '<pre>';
$structured = [];
foreach($res as $key => $row) {
$structured[$row['category']]['items'][] = [
'product_code' => $row['product_code'],
'product_name' => $row['product_name'],
'unit' => $row['unit'],
'quantity' => $row['quantity'],
];
}
print_r($structured);
// restructure the data to get the desired JSON output
$collection = [];
foreach($structured as $category => $items) {
$collection[] = [
'category' => $category,
'items' => $items['items']
];
}
echo json_encode($collection);
Output (JSON):
[
{
"category": "BABY",
"items": [
{
"product_code": "123",
"product_name": "BABY STUFF",
"unit": 1,
"quantity": 999
},
{
"product_code": "125",
"product_name": "BABY EAT",
"unit": 1,
"quantity": 999
}
]
},
{
"category": "MEN",
"items": [
{
"product_code": "124",
"product_name": "MEN STUFF",
"unit": 2,
"quantity": 888
}
]
}
]
I am trying to send SQL queries to elasticsearch server using the SQL API ( I am using the free version so I can't use the JDBC driver they provide)
and I was wondering how I can map the result of the query since it comes back like this:
{
"columns": [
{
"name": "project_id",
"type": "text"
}
],
"rows": [
[
"item1"
],
[
"item2"
],
[
"item3"
],
[
"item4"
],
[
"item5"
],
[
"item6"
]
]
}'''
I have a product that has a property categoryIds.
"id" : 1,
"title" : "product",
"price" : "1100.00",
"categories" : [ the ids of the product's categories],
"tags" : [ the ids of the product's tags ],
"variants" : [ nested type with properties: name, definition, maybe in the future availability dates]
I want to group the product id according to the category in the query.
In POST _search, I ask about products that belong to specific categories (eg [1, 2, 3]), and I can also limit them with a variant.
How can I group/aggregate my answer to get a list of the productIds of a categories?
What I'm trying to get:
{
"productsForCategories": {
"1": [
"product-1",
"product-2",
"product-3"
],
"2": [
"product-1",
"product-3",
"product-4"
],
"3": [
"product-5",
"product-6"
]
}
}
Thanks in advance for all answers.
What java generated.
curl --location --request POST 'https://localhost:9200/products/_search' \
--header 'Content-Type: application/json' \
--data-raw '{
"size": 0,
"query": {
"bool": {
"must": [
{
"bool": {
"should": [
{
"term": {
"categories": {
"value": 7,
"boost": 1.0
}
}
}
],
"adjust_pure_negative": true,
"minimum_should_match": "1",
"boost": 1.0,
"_name": "fromRawQuery"
}
}
],
"filter": [
{
"bool": {
"adjust_pure_negative": true,
"boost": 1.0,
"_name": "filterPart"
}
}
],
"adjust_pure_negative": true,
"boost": 1.0,
"_name": "queryPart"
}
},
"_source": {
"includes": [
"categories",
"productType",
"relations"
],
"excludes": []
},
"stored_fields": "_id",
"sort": [
{
"_score": {
"order": "desc"
}
}
],
"aggregations": {
"agg": {
"global": {},
"aggregations": {
"categories": {
"terms": {
"field": "categories",
"size": 2147483647,
"min_doc_count": 1,
"shard_min_doc_count": 0,
"show_term_doc_count_error": false,
"order": [
{
"_count": "desc"
},
{
"_key": "asc"
}
]
},
"aggregations": {
"productsForCategories": {
"terms": {
"field": "_id",
"size": 2147483647,
"min_doc_count": 1,
"shard_min_doc_count": 0,
"show_term_doc_count_error": false,
"order": [
{
"_count": "desc"
},
{
"_key": "asc"
}
]
}
}
}
}
}
}
}
}'```
You can use terms aggregation that is a multi-bucket value source based aggregation where buckets are dynamically built - one per unique value.
Adding a working example with index data, mapping, search query, and search result
Index Mapping:
{
"mappings":{
"properties":{
"categories":{
"type":"keyword"
}
}
}
}
Index Data:
{
"id":1,
"product":"p1",
"category":[1,2,7]
}
{
"id":2,
"product":"p2",
"category":[7,4,5]
}
{
"id":3,
"product":"p3",
"category":[4,5,6]
}
Search Query:
{
"size": 0,
"aggs": {
"cats": {
"terms": {
"field": "cat_ids",
"include": [
7
]
},
"aggs": {
"products": {
"terms": {
"field": "product.keyword",
"size": 10
}
}
}
}
}
}
Search Result:
"aggregations": {
"cats": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": 7,
"doc_count": 2,
"products": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": "p1",
"doc_count": 1
},
{
"key": "p2",
"doc_count": 1
}
]
}
}
]
}
I believe what you want is products corresponding to each category. As Bhavya mentioned you can use term aggregation for the same.
GET products/_search
{
"size": 0, //<===== If you need only aggregated results, set this to 0. It represents query result size.
"aggs": {
"categories": {
"terms": {
"field": "cat_ids", // <================= Equivalent of group by Cat_ids
"size": 10
},"aggs": {
"products": {
"terms": {
"field": "name.keyword",//<============= For Each category group by products
"size": 10
}
}
}
}
}
}
Result:
"aggregations" : {
"categories" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : 1, //<========== category id
"doc_count" : 2, //<========== For the given category id 2 products
"products" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "p1", //<========= for cat_id=1, p1 is there
"doc_count" : 1
},
{
"key" : "p2", //<========= for cat_id=1, p2 is there
"doc_count" : 1
}
]
}
},
{
"key" : 2,
"doc_count" : 2,
"products" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "p1",
"doc_count" : 1
},
{
"key" : "p2",
"doc_count" : 1
}
]
}
},
{
"key" : 3,
"doc_count" : 1,
"products" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "p1",
"doc_count" : 1
}
]
}
}
]
}
}
Details are present as comments. Please remove the comments and try running the query.
Filtering aggregation results: See this
I have a json structure like this:
{
"MetricDataResults": [
{
"Id": "m1",
"StatusCode": "Complete",
"Label": "AWS/EC2 NetworkOut Average",
"Timestamps": [
1518868032,
1518867732,
1518867432
],
"Values": [
15000,
14000,
16000
]
},
{
"Id": "m2",
"StatusCode": "Complete",
"Label": "AWS/EC2 NetworkOut SampleCount",
"Timestamps": [
1518868032,
1518867732,
1518867432
],
"Values": [
15,
14,
16
]
},
{
"Id": "m3",
"StatusCode": "Complete",
"Label": "AWS/EC2 HealthyHostCount",
"Timestamps": [
1518868032,
1518867732,
1518867432
],
"Values": [
15,
14,
16
]
}
]
}
For this json structure I need the counts of arrays in it. I'm looking at the structure to look like something like this:
{
"MetricDataResults (3)": [
{
"Id": "m1",
"StatusCode": "Complete",
"Label": "AWS/EC2 NetworkOut Average",
"Timestamps (3)": [
1518868032,
1518867732,
1518867432
],
"Values (3)": [
15000,
14000,
16000
]
},
{
"Id": "m2",
"StatusCode": "Complete",
"Label": "AWS/EC2 NetworkOut SampleCount",
"Timestamps (3)": [
1518868032,
1518867732,
1518867432
],
"Values (3)": [
15,
14,
16
]
},
{
"Id": "m3",
"StatusCode": "Complete",
"Label": "AWS/EC2 HealthyHostCount",
"Timestamps (4)": [
1518868032,
1518867732,
1518867432,
1518867462,
],
"Values (4)": [
15,
14,
16,
18
]
}
]
}
I'm wondering if there's a particular way with which we get the counts when deserializing with jackson? I was looking at this post - How to get count all json nodes using Jackson framework
but that doesn't seem to completely align with the use case I have. Does anybody have an idea on whether this can be done?
i have a problem of transfer JSON to java type, I want to transfer this JSON:
{ "kind": "fusiontables#sqlresponse", "columns": [ "Pre", "Post" ], "rows": [ [ "Si2", "Si2" ], [ "CeSP-A", "CeSP-A" ], [ "Si2", "Si1" ], [ "Si1", "Si2" ], [ "Si2", "Si1" ], [ "Si1", "Si2" ] ]}
to a java list which each one of the list has two private string Pre and Post
Here is my code:
Gson gson = new Gson();
List<Edges> list = gson.fromJson(jsonU,
new TypeToken<List<Edges>>() {
}.getType());
for (int i = 0; i < list.size(); i++) {
Edges p = list.get(i);
System.out.println(p.getPre() + ", " + p.getPost());
System.out.println();
}
and
jsonU is the String of JSON file
{ "kind": "fusiontables#sqlresponse", "columns": [ "Pre", "Post" ], "rows": [ [ "Si2", "Si2" ], [ "CeSP-A", "CeSP-A" ], [ "Si2", "Si1" ], [ "Si1", "Si2" ], [ "Si2", "Si1" ], [ "Si1", "Si2" ] ]}
However, i got the error:
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2
can you please help me resolve this problem? Thank you very much
You are telling GSON to deserialize a List<Edges> yet the JSON you are passing starts with an object, with the { and } tokens.
GSON, based on the type parameters you've passed to it, is expecting something like:
[
{ "kind": .... },
{ "kind: .... },
...
]
In other words, how can GSON construct a List of something when you are passing it JSON corresponding to a single object?