how to get Parent-document only in Couchbase [closed] - couchbase

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
any one can help me about this query
how can get Parent-document result using couchbase N1ql query
{
"created_at": "2020-03-26T15:50:12.318Z",
"created_by": 1,
"deleted_at": "",
"frm21_submit": null,
"id": "6cb51519-7c6b-499d-8a8d-3c85658605fc",
"machine_category_id": [
"7a2eb767-faca-4762-b65b-2db9e1992c82",
"259a4bcc-feb5-4d98-88c5-b331316e19be"
],
"main_parts": [
{
"data": {
"deleted_at": "777",
"frm21_submit": null,
"manufacturing_date": "03/31/2020",
"model": "234234234",
"photo": null,
"serial_number": "324324234",
"updated_at": "2020-03-31T14:11:48.909Z"
},
"id": "66354d7c-4769-4f3b-914e-bb841191e323"
}
]
}
i want to desire to result only parent-document only field are all dynamic i can not selected field.
{
"created_at": "2020-03-26T15:50:12.318Z",
"created_by": 1,
"deleted_at": "",
"frm21_submit": null,
"id": "6cb51519-7c6b-499d-8a8d-3c85658605fc",
"machine_category_id": [
"7a2eb767-faca-4762-b65b-2db9e1992c82",
"259a4bcc-feb5-4d98-88c5-b331316e19be"
]
}

If you want only remove main_parts from the original document.
Option 1: Select the fields you want. You mentioned this is not possible.
Option 2: SELECT all fields in the document
and project MISSING as the field you don't want
SELECT d.*, MISSING AS main_parts
FROM default AS d;
Option 3: Remove from the field from the object, if required do cascade using object functions https://docs.couchbase.com/server/current/n1ql/n1ql-language-reference/objectfun.html#object_remove
SELECT OBJECT_REMOVE(d,"main_parts").*
FROM default AS d;
Option 4: If you need to remove lot of fields use reconstruct object
SELECT OBJECT v.name:v.val FOR v IN OBJECT_PAIRS(d) WHEN v.name NOT IN ["main_parts"] END.*
FROM default AS d;
Option 5: If you need to remove if field is object
SELECT OBJECT v.name:v.val FOR v IN OBJECT_PAIRS(d) WHEN v.val IS NULL OR ISOBJECT(v.val) = false END.*
FROM default AS d;
Option 6: Based on value type
SELECT OBJECT v.name:v.val
FOR v IN OBJECT_PAIRS(d)
WHEN type(v.val) IN ["null", "boolean", "number", "string", "array", "object"]
END.*
FROM default AS d;

Related

JSONata Filter Array by starts-with criteria

I'm pretty new to JSONata, and I need to write a query that will search/filter an array and return only the values that meet the criteria.
Specifically:
{
"data": [
{
"externalIds": [
"005262615581",
"1395464646",
"566955222",
"6696630050055999",
"99506533221233"
],
"firstName": "Brian",
"id": "a91f91af91af91a9f11fakeid",
"lastName": "lastName",
"office": null,
"phone": null,
"role": "Admin",
}
]
}
I've tried $Contains, and $Filter, but I honestly don't know the syntax to accomplish the "starts-with" concept.
I need to filter the "externalIds" array and only return the IDs that begin with 005, NOT contain 005.
So in this body I need it to return "005262615581".
You can use regular expressions and the $match function:
data.externalIds[$match($, /^005/)]
See it live on the playground: https://stedi.link/fa5C2GZ

How to map jooq result to their respective entities

I have this SQL query:
select question.*,
question_option.id
from question
left join question_option on question_option.question_id = question.id;
How do I map the result obtained to the entity. so that the expected result should be like
Can anyone give the sample code for getting the result as above
{
"id": 2655,
"type": "MCQSingleCorrect",
"difficultyLevel": "Advanced",
"question": "Which country are you from?",
"answer": null,
"marks": 1.5,
"negativeMarks": 0.5,
"hint": null,
"explanation": null,
"booleanAnswer": null,
"passage": null,
"isPassageQuestion": null,
"audioFile": null,
"videoFile": null,
"questionFiles": [],
"tags": [],
"updatedAt": "2021-12-21T11:57:03.229136Z",
"createdAt": "2021-12-21T11:57:03.229098Z",
"questionOptions": [
{
"id": 2719,
"option": "India",
"index": 1,
"correct": false,
"blank": null
},
{
"id": 2720,
"option": "Newzealand",
"index": 1,
"correct": false,
"blank": null
},
{
"id": 2721,
"option": "England",
"index": 1,
"correct": true,
"blank": null
},
{
"id": 2722,
"option": "Australia",
"index": 1,
"correct": false,
"blank": null
}
]}
I'm answering from the perspective of our comments discussion, where I suggested you don't need JPA in the middle, because you can do every mapping / projection with jOOQ directly. In this case, if you're targeting a JSON client, why not just use SQL/JSON, for example? Rather than joining, you nest your collection like this:
ctx.select(jsonObject(
key("id", QUESTION.ID),
key("type", QUESTION.TYPE),
..
key("questionOptions", jsonArrayAgg(jsonObject(
key("id", QUESTION_OPTION.ID),
key("option", QUESTION_OPTION.OPTION),
..
)))
))
.from(QUESTION)
.leftJoin(QUESTION_OPTION)
.on(QUESTION_OPTION.QUESTION_ID.eq(QUESTION.ID))
// Assuming you have a primary key here.
// Otherwise, add also the other QUESTION columns to the GROUP BY clause
.groupBy(QUESTION.ID)
.fetch();
This will produce a NULL JSON array if a question doesn't have any options. You can coalesce() it to an empty array, if needed. There are other ways to achieve the same thing, you could also use MULTISET if you don't actually need JSON, but just some hierarchy of Java objects.
As a rule of thumb, you hardly ever need JPA in your code when you're using jOOQ, except if you really rely on JPA's object graph persistence features.
You can write the query with jOOQ and the do this:
Query result = em.createNativeQuery(query.getSQL());
query.getResultList() // or query.getSingleResult() depending what you need.
Read more here:
https://www.jooq.org/doc/3.15/manual/sql-execution/alternative-execution-models/using-jooq-with-jpa/using-jooq-with-jpa-native/
JSON can be fetched directly using SQL (and also jOOQ). Here are some examples:
https://72.services/use-the-power-of-your-database-xml-and-json/

Modify json file using some condition and create new json file in r [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
For the JSON file in this format :
{
"Content": " Some content ",
"Number": "52",
"Sub Content": [
{
"Name": "SC1",
"Value": "100"
},
{
"Name": "SC2",
"Value": "25"
}
]
}
I need to check the value of "Number", it is "52", I have to change value of "SC2" from "25" to "46" using R.
Any help to achieve this.
Start by using a json handling package.
install.packages('rjson',dependencies=TRUE)
Next, read your json into a variable. let's say myjson
Convert your json into a list:
myjsonList = fromJSON(myjson)
Make your changes
if(myjsonList$Number == 52){
myjsonList$'Sub Content'[[2]]$Value=25
}
And make it a json again.
newjson= toJSON(myjsonList)

Access deeper elements of a JSON using postgresql 9.4

I want to be able to access deeper elements stored in a json in the field json, stored in a postgresql database. For example, I would like to be able to access the elements that traverse the path states->events->time from the json provided below. Here is the postgreSQL query I'm using:
SELECT
data#>> '{userId}' as user,
data#>> '{region}' as region,
data#>>'{priorTimeSpentInApp}' as priotTimeSpentInApp,
data#>>'{userAttributes, "Total Friends"}' as totalFriends
from game_json
WHERE game_name LIKE 'myNewGame'
LIMIT 1000
and here is an example record from the json field
{
"region": "oh",
"deviceModel": "inHouseDevice",
"states": [
{
"events": [
{
"time": 1430247045.176,
"name": "Session Start",
"value": 0,
"parameters": {
"Balance": "40"
},
"info": ""
},
{
"time": 1430247293.501,
"name": "Mission1",
"value": 1,
"parameters": {
"Result": "Win ",
"Replay": "no",
"Attempt Number": "1"
},
"info": ""
}
]
}
],
"priorTimeSpentInApp": 28989.41467999999,
"country": "CA",
"city": "vancouver",
"isDeveloper": true,
"time": 1430247044.414,
"duration": 411.53,
"timezone": "America/Cleveland",
"priorSessions": 47,
"experiments": [],
"systemVersion": "3.8.1",
"appVersion": "14312",
"userId": "ef617d7ad4c6982e2cb7f6902801eb8a",
"isSession": true,
"firstRun": 1429572011.15,
"priorEvents": 69,
"userAttributes": {
"Total Friends": "0",
"Device Type": "Tablet",
"Social Connection": "None",
"Item Slots Owned": "12",
"Total Levels Played": "0",
"Retention Cohort": "Day 0",
"Player Progression": "0",
"Characters Owned": "1"
},
"deviceId": "ef617d7ad4c6982e2cb7f6902801eb8a"
}
That SQL query works, except that it doesn't give me any return values for totalFriends (e.g. data#>>'{userAttributes, "Total Friends"}' as totalFriends). I assume that part of the problem is that events falls within a square bracket (I don't know what that indicates in the json format) as opposed to a curly brace, but I'm also unable to extract values from the userAttributes key.
I would appreciate it if anyone could help me.
I'm sorry if this question has been asked elsewhere. I'm so new to postgresql and even json that I'm having trouble coming up with the proper terminology to find the answers to this (and related) questions.
You should definitely familiarize yourself with the basics of json
and json functions and operators in Postgres.
In the second source pay attention to the operators -> and ->>.
General rule: use -> to get a json object, ->> to get a json value as text.
Using these operators you can rewrite your query in the way which returns correct value of 'Total Friends':
select
data->>'userId' as user,
data->>'region' as region,
data->>'priorTimeSpentInApp' as priotTimeSpentInApp,
data->'userAttributes'->>'Total Friends' as totalFriends
from game_json
where game_name like 'myNewGame';
Json objects in square brackets are elements of a json array.
Json arrays may have many elements.
The elements are accessed by an index.
Json arrays are indexed from 0 (the first element of an array has an index 0).
Example:
select
data->'states'->0->'events'->1->>'name'
from game_json
where game_name like 'myNewGame';
-- returns "Mission1"
select
data->'states'->0->'events'->1->>'name'
from game_json
where game_name like 'myNewGame';
This did help me

Get list of dishes and detail per dish page in Freebase?

I tried this query to get the list of all dish instances
[{
"id": null,
"name": null,
"type": "/food/dish"
}]
But it only gives me first page:
http://www.freebase.com/query?autorun=1&q=%5B%7B%22id%22:null,%22name%22:null,%22type%22:%22/food/dish%22%7D%5D
Question 1: How to add paging to get all 2.5K or so dish instances? I tried to add "cursor: 2" and didn't work.
Let say I have a name "pizza", I tried this query to get detail of "pizza":
{
"*": null,
"name": "pizza",
"type": "/food/dish"
}
But that didn't give me description and images like this page http://www.freebase.com/m/0663v
Question 2: How to get all information, or at least description and image URLs like in the freebase page above?
Bonus: I tried to do everything via Freebase Node.js here https://github.com/spencermountain/Freebase.js
I suggest you separate this into 2 questions, so each has their own topic, and it is easier for future visitors to search.
That said:
Question 1
You can increase the number of results you get per page by adding limit: to your query. Regardless, you will have to use paging. To use paging, you need to add the cursor parameter to your mqlread HTTP request. Again: cursor is not part of the MQL query itself, but rather of the HTTP envelope that submits it.
For the first query, issue an empty cursor, and for subsequent queries use the cursor value returned to you by mqlread.
Note that all this will need to be done with the API, not with freebase directly, and as such the URL will need to be:
https://www.googleapis.com/freebase/v1/mqlread?cursor=&query=[{"id":null,"name":null,"type":"/food/dish","limit":5}]
Also note that if you plan on doing this for anything other than testing you will need to obtain a key from Google.
Finally, note that some strings in Freebase are "freebase-encoded", read up on that regarding how to decode them in the result.
Question 2
If you just want the ingredient names then simply add "/dining/cuisine/ingredients": [] to your query. Note that many dishes do not have ingredients, but Pizza does:
{
"id": "/m/0663v",
"name": null,
"type": "/food/dish",
"/dining/cuisine/ingredients": []
}
Getting the images means adding "/common/topic/image": [{}] to your query, and using the returned id for each image.
Getting an image URL from a given image id is done by prepending https://usercontent.googleapis.com/freebase/v1/image/ to the id.
Edit
Tom correctly noted that I forgot about image descriptions. The description for each image will be available under name: in the returned /common/topic/image array. For example, for the query
[{
"id": "/en/minestrone",
"/common/topic/image": [{
"id": null,
"name": null
}]
}]
you get the following images and their descriptions:
{
"result": [{
"id": "/en/minestrone",
"/common/topic/image": [
{
"id": "/wikipedia/images/commons_id/1492185",
"name": "MinestroneSoup"
},
{
"id": "/wikipedia/images/commons_id/12565901",
"name": "Homemade minestrone"
}
]
}]
}
Your final MQL, then, is:
[{
"id": null,
"name": null,
"type": "/food/dish",
"/common/topic/image": [{
"id": null,
"name": null
}],
"/dining/cuisine/ingredients": []
}]
... and the HTTP envelope will contain a key and a value for cursor.
See Nitzan's answer for the answer to question 1.
For your second question, the easiest way to get descriptions and images is by using the Topic API e.g. https://www.googleapis.com/freebase/v1/topic/m/0663v