order by in sub document in DocumentDB - sql-order-by

I have a json document like following with sub-document
[
{
"id": "73e799df-b7a5-7470-4f25-ee6c1811a5b2",
"tblType": "search",
"memberId": 2,
"results": [
{"prcnt": 89,"distance": 8867775.747141607},
{"prcnt": 30,"distance": 11010216.470879028},
{"prcnt": 96,"distance": 9128590.716183286},
{"prcnt": 41,"distance": 9652043.937920697}
]
}
]
i want to get the 'results' tag data only in the query with order by prcnt
SELECT top 10 m.results FROM m join r in m.results where m.memberId=2
and m.tblType='search' order by r.prcnt
when i am executing the query, getting the error as follows..
Order-by over correlated collections is not supported.
how to get the data per my requirement.
Thanks in advance!!

According to your requirement, I have checked this issue. Here are my understanding about this issue:
If the memberId and tblType could locate the single document, then you could refer to this similar issue:
UDF
function sortByPrcntNumber (results) {
return results.sort(function(a,b){
return a.prcnt-b.prcnt;
});
}
QUERY
SELECT value udf.sortByPrcntNumber(c.results)
from c
where c.memberId=2 and c.tblType='search'
If the memberId and tblType could retrieve multiple documents, I assumed that you could leverage STORED PROCEDURES as follows:
function sample(top,tblType,memberId){
var collection=getContext().getCollection();
var isAccepted=collection.queryDocuments(
collection.getSelfLink(),
"SELECT value {\"prcnt\":r.prcnt,\"distance\":r.distance} from c join r in c.results where c.tblType='"+tblType+"' and c.memberId="+memberId+"",
function(err,feed,options){
if(err) throw err;
if(!feed||!feed.length) getContext().getResponse().setBody("no docs found");
else {
//order by prcnt
var orderedFeed=feed.sort(function(a,b){
return a.prcnt-b.prcnt;
});
//select top
var topFeed=orderedFeed.slice(0,top);
getContext().getResponse().setBody(topFeed);
}
});
if(!isAccepted) throw new Error("The query was not accepted by the server.");
}
Result

Related

How can i search by field of joined table in graphql and nestjs

i create two table tag and tagTranslation.
following is field of each
Tag
id, type, transloations, creaed_at, updated_at
TagTranslation
id, tag_id, name, language
I use graphql, i want to get tag list by type, name and language
{ tags(name:"tag1", language:"en, type:3){
id,
type,
translations{
id,
name,
language,
}
}
}
so I create resolver like following
#Query(returns => [Tag])
tags(#Args() tagArgs: TagArgs): Promise<Tag[]> {
const where = {
...(tagArgs.type) && {type: tagArgs.type}
};
const include_where = {
...(tagArgs.name) && {name: { [Op.like]: `%${tagArgs.name}%` }},
...(tagArgs.language) && {language: tagArgs.language}
};
return this.tagService.findAll({
where: where,
include: {
as: 'translations',
model: TagTranslation,
where: include_where,
required: true,
}
});
}
#Query(returns => Tag)
tag(#Args({name: 'id', type: ()=> Int}) id: number): Promise<Tag>{
return this.tagService.get(id)
}
#ResolveProperty()
async translations(#Parent() tag): Promise<TagTranslation[]>{
const { id } = tag;
return await this.tagTranslationService.findAll({tag_id: id});
}
when i call tags, the query is called twice
first, A query is executed to get the results I want.
but second,
SELECT `id`, `tag_id`, `name`, `language`, `created_at`, `updated_at` FROM `tag_translation` AS `TagTranslation` WHERE `TagTranslation`.`tag_id` = 1;
query is called once more, so i can't get results what i want.
I think second query is called because of ResolveProperty, I remove ResolveProperty. after that, tag query is not include tagtranslation info...
how can i solve that problem ? or is there another idea??
how can i solve that problem ? or is there another idea??
Relations between entities should be resolved on a field resolver (#ResolveProperty()) level because when someone requests only id and type, you will still perform additional, not needed join on TagTranslation in sql query.

SuiteScript 2.0 Filter Operator AnyOf Not Working

I have a SuiteScript 2.0 that load and search transaction saved search with posting period filter. In my filter I am using 'anyof' operator which is not working for 'postingperiod' field
below is sample of my code:
function getTransactionData(datain)
{
try
{
var objSearch = search.load(
{
id: datain.savedsearchid
});
objSearch.filters.push(search.createFilter({ name: "postingperiod", operator: "ANYOF", values: ["42", "43"]}));
//above filter filters only record with internalid 42
result = readAllData(objSearch);
return result;
}
catch (ex)
{
log.error("getTransactionData", ex);
throw ex;
}
}
let me know if I am missing something here.
Please note above issue is occurring only for saved search, if I search other object for example 'account' object with internalid filter using 'anyof' operator, works fine.
Update: Today after more testing, found that its only happening for 'postingperiod' filter.
Try this code in Netsuite Debugger, Create a SavedSearch in Netsuite, don't add any filter in that , save that and get the id of saved search and use in below script against id value.
Also replace the Period Id with yours.
require(['N/runtime','N/search'],
function (runtime,search) {
var invoiceSearchObj = search.load({
type: "invoice",
id: '<your search id>',
columns:
[
search.createColumn({
name: "trandate",
sort: search.Sort.ASC,
label: "Date"
})
]
});
invoiceSearchObj.filters.push(search.createFilter({ name: "postingperiod", operator: "ANYOF", values: ["<your period value>"]}));
invoiceSearchObj.filters.push(search.createFilter({ name: "mainline", operator: "is", values : "T"}));
var searchResultCount = invoiceSearchObj.runPaged().count;
log.debug("invoiceSearchObj result count",searchResultCount);
invoiceSearchObj.run().each(function(result){
// .run().each has a limit of 4,000 results
return true;
});
});
var a=0;

How to get count(id) from table with graphql

I've been playing around with resolvers in graphql and need what's seemingly a simple query, but I can't figure it out.
I want to query a table and get results in something like this:
SELECT hero_id, count(id) FROM "Build"
GROUP BY hero_id
ORDER BY hero_id
How do I write the resolver to return the count of rows by id on a table?
I thought the Table.findAndCountAll() would return results I'm looking for.
const buildCount = {
type: BuildCountType,
resolve(parent, args){
return Build.findAndCountAll().then(result => {
console.log(result)
return {
count: result.rows
}
})
}
}
Thanks,
StuckAndConfused ;)

ReQL Updating object inside an embedded array emits "create" and "delete" events when listening to changes

I am hitting the following problem: Suppose that I have the following structure:
{
"id": 1,
"data": {
"arr": [{"text":"item1"}]
}
}
And the following query:
r.db('test').table('test').get(1).update(function (item) {
return {
data: {
arr: item('data')('arr').map(function (row) {
return r.branch(
row('text').eq('item1'),
row.merge({updated:true}),
row
)
})
}
}
})
I am listening for changes in this specific array only, and when the item is updated both create and delete events are emitted. I really need to receive an update event, e.g. old_val is not null and new_val is not null.
Thanks in advance guys
After all, I decided to drop the embedded array and use table joins, this avoids all possible hacks.
You can use something like this
r.db('test').table('test')('data')('arr').changes()
.filter(function(doc) {
return doc('new_val').ne(null).and(doc('old_val').ne(null))
})
I'll only show update to array. If you need to get access to other document field, try this:
r.db('test').table('test').changes()
.filter(function(doc) {
return doc('new_val')('data')('arr').ne(null).and(doc('old_val')('data')('arr').ne(null))
})

Chaining queries in rethinkdb

Lets say I have a "category" table, each category has associated data in the "data" table and it has associated data in other tables "associated" and I want to remove a category with all it's associated data.
What I'm currently doing is something like this:
getAllDataIdsFromCategory()
.then(removeAllAssociated)
.then(handleChanges)
.then(removeDatas)
.then(handleChanges)
.then(removeCategory)
.then(handleChanges);
Is there a way to chain these queries on the db-side?
my functions currently look like this:
var getAllDataIdsFromCategory = () => {
return r
.table('data')
.getAll(categoryId, { index: 'categoryId' })
.pluck('id').map(r.row('id')).run();
}
var removeAllAssociated = (_dataIds: string[]) => {
dataIds = _dataIds;
return r
.table('associated')
.getAll(dataIds, { index: 'dataId' })
.delete()
.run()
}
var removeDatas = () => {
return r
.table('data')
.getAll(dataIds)
.delete()
.run()
}
notice that I cannot use r.expr() or r.do() since I want to do queries based on the result of the previous query.
The problem with my approach is that it won't work for large amounts of "data" since I have to bring all of the ids to the client side, and doing paging for it in the client side in a loop seems like a workaround.
You can use forEach for this:
r.table('data').getAll(categoryID, {index: 'categoryId'})('id').forEach(function(id) {
return r.table('associated').getAll(id, {index: 'dataId'}).delete().merge(
r.table('data').get(id).delete())
});

Resources