How to use orderBy for graphQL - graphql

I am trying to sort reservesUSD of nested object dailyPoolSnapshots In descending order by timestamp and return it's first value (in other words, return the latest entry).
I know almost nothing of GraphQL and it's documentation seems confusing and scarce. Can someone help me to figure out how to sort my objects?
I am using subgraphs on the Ethereum mainnet for Curve.fi to get information about pools
My code:
pools(first: 1000) {
name
address
coins
coinDecimals
dailyPoolSnapshots(first: 1,
orderBy:{field: timestamp, order: DESC}) {
reservesUSD
timestamp
}
}
}
It throws and error:
"errors": [
{
"locations": [
{
"line": 0,
"column": 0
}
],
"message": "Invalid value provided for argument `orderBy`: Object({\"direction\": Enum(\"DESC\"), \"field\": Enum(\"timestamp\")})"
}
]
}```

Here is your solution
{
pools(first: 1000) {
name
address
coins
coinDecimals
dailyPoolSnapshots(first: 1,
orderBy: timestamp, orderDirection:desc) {
reservesUSD
timestamp
}
}
}
In the playground, you have the doc on the right, you can search dailyPoolSnapshots, if you click on it, you will have the documentation of this query
Sample for this query:
Type
[DailyPoolSnapshot!]!
Arguments
skip: Int = 0
first: Int = 100
orderBy: DailyPoolSnapshot_orderBy
orderDirection: OrderDirection
where: DailyPoolSnapshot_filter
block: Block_height
Arguments are all the params you can use

The orderBy and orderDirection are separate query params, and orderDirection needs to be lowercase for their enum syntax.
{
platforms(first: 5) {
id
pools {
id
dailyPoolSnapshots(first: 1, orderBy: timestamp, orderDirection: asc) {
timestamp
}
}
poolAddresses
latestPoolSnapshot
}
registries(first: 5) {
id
}
}

Related

elasticsearch sort by price with currency

I have data
{
"id": 1000,
"price": "99,01USA",
},
{
"id": 1001,
"price": "100USA",
},
{
"id": 1002,
"price": "780USA",
},
{
"id": 1003,
"price": "20USA",
},
How I sort order by price (ASC , DESC)
You can alter it a little to parse price to integer and then sort it
You can create a dynamic sort function that sorts objects by their value that you pass:
function dynamicSort(property) {
var sortOrder = 1;
if(property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function (a,b) {
/* next line works with strings and numbers,
* and you may want to customize it to your needs
*/
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}
}
So you can have an array of objects like this:
var People = [
{Name: "Name", Surname: "Surname"},
{Name:"AAA", Surname:"ZZZ"},
{Name: "Name", Surname: "AAA"}
];
...and it will work when you do:
People.sort(dynamicSort("Name"));
People.sort(dynamicSort("Surname"));
People.sort(dynamicSort("-Surname"));
Actually this already answers the question. Below part is written because many people contacted me, complaining that it doesn't work with multiple parameters.
Multiple Parameters
You can use the function below to generate sort functions with multiple sort parameters.
function dynamicSortMultiple() {
/*
* save the arguments object as it will be overwritten
* note that arguments object is an array-like object
* consisting of the names of the properties to sort by
*/
var props = arguments;
return function (obj1, obj2) {
var i = 0, result = 0, numberOfProperties = props.length;
/* try getting a different result from 0 (equal)
* as long as we have extra properties to compare
*/
while(result === 0 && i < numberOfProperties) {
result = dynamicSort(props[i])(obj1, obj2);
i++;
}
return result;
}
}
Which would enable you to do something like this:
People.sort(dynamicSortMultiple("Name", "-Surname"));
Subclassing Array
For the lucky among us who can use ES6, which allows extending the native objects:
class MyArray extends Array {
sortBy(...args) {
return this.sort(dynamicSortMultiple(...args));
}
}
That would enable this:
MyArray.from(People).sortBy("Name", "-Surname");

Elastic Search - How to return records within time intervals

I have an elastic search db deployed within an AWS VPC. It holds millions of records all with a timestamp added based on the unix datestamp (new Date().getTime()). I am trying to pull (1) record per time slot based on min/max hour and minute values.
Index Mapping:
{ timestamp: "date", ...rest of record }
Elastic Search Query:
let params = {
query: {
bool: {
must: [{
range: {
timestamp: {
gte: (unix date),
lte: (unix date)
}
}
},
{
script: {
script: {
source: "long datestamp = doc['timestamp'].value.getMillis(); " +
"Date dt = new java.util.Date(datestamp*1L); " +
"Calendar instance = Calendar.getInstance(); " +
"instance.setTime(dt); " +
"int hod = instance.get(Calendar.HOUR_OF_DAY); " +
"int tod = instance.get(Calendar.MINUTE); " +
"if (hod >= params.hourMin && hod <= params.hourMax && (hod === params.hourMin && tod >= params.timeMin || hod === params.hourMax && tod <= params.timeMax)) { return true; } else { return false }",
params: {
hourMin: 7,
hourMax: 8,
timeMin: 30,
timeMax: 10
}
}
}
}
]
}
},
from: 0,
size: 500
};
Issue:
I often run into an error while searching indicating that
"dynamic method [java.lang.Long, getMillis/0] not found"
It shows up every 4~5th query generally speaking.
Question:
Is there a better way? I have poured over the elastic search docs regarding intervals, histograms, etc and came up with query above. Not sure if this is the most efficient method nor the most robust.
If this is a community accept approach to find records within an interval then how do I mitigate the errors I am encountering. Do I skip over a specific record or reformat the unix timestamp another way?
Appreciate your support ahead of time.

How to resolve graphene.Union Type?

I want to create a UnionType(graphene.Union) of two existing types (FirstType and SecondType) and be able to resolve the query of this union type.
Schema
class FirstType(DjangoObjectType):
class Meta:
model = FirstModel
class SecondType(DjangoObjectType):
class Meta:
model = SecondModel
class UnionType(graphene.Union):
class Meta:
types = (FirstType, SecondType)
So with this schema I want to query all objects from FirstType and SecondType with pk in some list [pks]
query {
all_items(pks: [1,2,5,7]){
... on FirstType{
pk,
color,
}
... on SecondType{
pk,
size,
}
}
}
PKs from FirstType are normally not in the SecondType.
I tried like one below
def resolve_items(root, info, ids):
queryset1 = FirstModel.objects.filter(id__in=pks)
queryset2 = SecondModel.objects.filter(id__in=pks)
return queryset1 | queryset2
but it gives an error: 'Cannot combine queries on two different base models.'
I expect the following response from query:
{ 'data':
{'all_items':[
{'pk': 1,
'color': blue
},
{'pk': 2,
'size': 50.0
},
...
]}
}
So how the resolver should look like?
The graphene Documentation on union types is very sparse. Here is a working example of how to do it correctly:
from graphene import ObjectType, Field, List, String, Int, Union
mock_data = {
"episode": 3,
"characters": [
{
"type": "Droid",
"name": "R2-D2",
"primaryFunction": "Astromech"
},
{
"type": "Human",
"name": "Luke Skywalker",
"homePlanet": "Tatooine"
},
{
"type": "Starship",
"name": "Millennium Falcon",
"length": 35
}
]
}
class Human(ObjectType):
name = String()
homePlanet = String()
class Droid(ObjectType):
name = String()
primaryFunction = String()
class Starship(ObjectType):
name = String()
length = Int()
class Character(Union):
class Meta:
types = (Human, Droid, Starship)
#classmethod
def resolve_type(cls, instance, info):
if instance["type"] == "Human":
return Human
if instance["type"] == "Droid":
return Droid
if instance["type"] == "Starship":
return Starship
class RootQuery(ObjectType):
result = Field(SearchResult)
def resolve_result(_, info):
return mock_data
Then, for a query like
query Humans {
result {
episode
characters {
... on Droid {
name
}
... on Starship {
name
}
... on Human {
name
}
}
}
}
it returns the correct result.
Okay, so I was too concentrated on merging query sets and I didn't notice that I can simply return a list.
So here is solution which gives me the response I was looking for:
def resolve_items(root, info, ids):
items = []
queryset1 = FirstModel.objects.filter(id__in=pks)
items.extend(queryset1)
queryset2 = SecondModel.objects.filter(id__in=pks)
items.extend(queryset2)
return items

Golang gorm - preload with deeply nested models

I have the following contrived example:
type Top struct {
ID uint `gorm:"primary_key"`
Name string
Middle []*Middle
}
type Middle struct {
ID uint `gorm:"primary_key"`
TopID int
Name string
Low []*Low
}
type Low struct {
ID uint `gorm:"primary_key"`
MiddleID int
Name string
Bottom []*Bottom
}
type Bottom struct {
ID uint `gorm:"primary_key"`
LowID int
Name string
}
top := Top{
Name: "Top",
Middle: []*Middle{
{
Name: "Middle",
Low: []*Low{
{
Name: "Low",
Bottom: []*Bottom{
{
Name: "Bottom",
},
},
},
},
},
},
}
if err := db.Save(&top).Error; err != nil {
log.Fatal("Got errors when saving calc", err.Error())
}
if err := db.Where("id = 1").
Preload("Middle.Low.Bottom").
First(&top).Error; err != nil {
log.Fatal(err)
}
This gives me the following output:
(/host_home/workspace/golang/src/bitbucket.org/cloudgloballog/gormtest/main.go:81)
[2016-03-18 01:53:23] [4.37ms] INSERT INTO "tops" ("name") VALUES ('Top') RETURNING "tops"."id"
(/host_home/workspace/golang/src/bitbucket.org/cloudgloballog/gormtest/main.go:81)
[2016-03-18 01:53:23] [3.49ms] INSERT INTO "middles" ("name","top_id") VALUES ('Middle','1') RETURNING "middles"."id"
(/host_home/workspace/golang/src/bitbucket.org/cloudgloballog/gormtest/main.go:81)
[2016-03-18 01:53:23] [1.07ms] INSERT INTO "lows" ("middle_id","name") VALUES ('1','Low') RETURNING "lows"."id"
()
[2016-03-18 01:53:23] [9.16ms] INSERT INTO "bottoms" ("low_id","name") VALUES ('1','Bottom') RETURNING "bottoms"."id"
(/host_home/workspace/golang/src/bitbucket.org/cloudgloballog/gormtest/main.go:86)
[2016-03-18 01:53:23] [1.54ms] SELECT * FROM "tops" ORDER BY "tops"."id" ASC LIMIT 1
(/host_home/workspace/golang/src/bitbucket.org/cloudgloballog/gormtest/main.go:88)
[2016-03-18 01:53:23] [2.63ms] SELECT * FROM "tops" WHERE ("id" = '1') ORDER BY "tops"."id" ASC LIMIT 1
(/host_home/workspace/golang/src/bitbucket.org/cloudgloballog/gormtest/main.go:88)
[2016-03-18 01:53:23] [1.65ms] SELECT * FROM "middles" WHERE (top_id IN ('1')) ORDER BY "middles"."id" ASC
(/host_home/workspace/golang/src/bitbucket.org/cloudgloballog/gormtest/main.go:88)
[2016-03-18 01:53:23] [4.20ms] SELECT * FROM "lows" WHERE (middle_id IN ('1')) ORDER BY "lows"."id" ASC
(/host_home/workspace/golang/src/bitbucket.org/cloudgloballog/gormtest/main.go:88)
[2016-03-18 01:53:23] can't find field Bottom in []**main.Low
If I were to only nest Top -> Middle -> Low and called Preload("Middle.Low") it works fine. The clue is probably in the double pointer reference []**main.Low but I'm unable to work out how to do this properly.
It's possible that nested preloading is not supported to this level. Anyone know?
This issue seems to have been present in earlier versions of gorm as described in: Issue1, Issue2, Issue3, but the lastest preload issue fix has been in this one.
It appears it has been resolved for quite some time but the exact version it was fixed is not documented unless someone searches git commit dates.
Setting up a current example with the latest version (v1.9.11 as of this writing) held no issues.
package main
import (
"log"
"github.com/davecgh/go-spew/spew"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
type Top struct {
ID uint `gorm:"primary_key"`
Name string
Middle []*Middle
}
type Middle struct {
ID uint `gorm:"primary_key"`
TopID int
Name string
Low []*Low
}
type Low struct {
ID uint `gorm:"primary_key"`
MiddleID int
Name string
Bottom []*Bottom
}
type Bottom struct {
ID uint `gorm:"primary_key"`
LowID int
Name string
}
func main() {
db, err := gorm.Open("sqlite3", "test.db")
if err != nil {
panic("failed to connect database")
}
defer db.Close()
// Enable Logger, show detailed log
db.LogMode(true)
// Migrate the schema
db.AutoMigrate(&Top{})
db.AutoMigrate(&Middle{})
db.AutoMigrate(&Low{})
db.AutoMigrate(&Bottom{})
top := Top{
Name: "Top",
Middle: []*Middle{
{
Name: "Middle",
Low: []*Low{
{
Name: "Low",
Bottom: []*Bottom{
{
Name: "Bottom",
},
},
},
},
},
},
}
if err := db.Save(&top).Error; err != nil {
log.Fatal("Got errors when saving calc", err.Error())
}
var ntop Top
if err := db.Where("id = 1").
Preload("Middle.Low.Bottom").
First(&ntop).Error; err != nil {
log.Fatal(err)
}
spew.Dump(&ntop)
}
$ ./main.exe
(C:/Users/fakename/source/stackoverflow/go/gorm-nested/main.go:70)
[2019-10-31 14:44:23] [2.00ms] INSERT INTO "tops" ("name") VALUES ('Top')
[1 rows affected or returned ]
(C:/Users/fakename/source/stackoverflow/go/gorm-nested/main.go:70)
[2019-10-31 14:44:23] [0.00ms] INSERT INTO "middles" ("top_id","name") VALUES (1,'Middle')
[1 rows affected or returned ]
(C:/Users/fakename/source/stackoverflow/go/gorm-nested/main.go:70)
[2019-10-31 14:44:23] [0.99ms] INSERT INTO "lows" ("middle_id","name") VALUES (1,'Low')
[1 rows affected or returned ]
()
[2019-10-31 14:44:23] [0.00ms] INSERT INTO "bottoms" ("low_id","name") VALUES (1,'Bottom')
[1 rows affected or returned ]
(C:/Users/fakename/source/stackoverflow/go/gorm-nested/main.go:76)
[2019-10-31 14:44:23] [0.00ms] SELECT * FROM "tops" WHERE (id = 1) ORDER BY "tops"."id" ASC LIMIT 1
[1 rows affected or returned ]
(C:/Users/fakename/source/stackoverflow/go/gorm-nested/main.go:76)
[2019-10-31 14:44:23] [0.00ms] SELECT * FROM "middles" WHERE ("top_id" IN (1)) ORDER BY "middles"."id" ASC
[1 rows affected or returned ]
(C:/Users/fakename/source/stackoverflow/go/gorm-nested/main.go:76)
[2019-10-31 14:44:23] [0.00ms] SELECT * FROM "lows" WHERE ("middle_id" IN (1)) ORDER BY "lows"."id" ASC
[1 rows affected or returned ]
(C:/Users/fakename/source/stackoverflow/go/gorm-nested/main.go:76)
[2019-10-31 14:44:23] [0.99ms] SELECT * FROM "bottoms" WHERE ("low_id" IN (1)) ORDER BY "bottoms"."id" ASC
[1 rows affected or returned ]
(*main.Top)(0xc00015f950)({
ID: (uint) 1,
Name: (string) (len=3) "Top",
Middle: ([]*main.Middle) (len=1 cap=1) {
(*main.Middle)(0xc000150fc0)({
ID: (uint) 1,
TopID: (int) 1,
Name: (string) (len=6) "Middle",
Low: ([]*main.Low) (len=1 cap=1) {
(*main.Low)(0xc000151080)({
ID: (uint) 1,
MiddleID: (int) 1,
Name: (string) (len=3) "Low",
Bottom: ([]*main.Bottom) (len=1 cap=1) {
(*main.Bottom)(0xc0001929c0)({
ID: (uint) 1,
LowID: (int) 1,
Name: (string) (len=6) "Bottom"
})
}
})
}
})
}
})

Removing an elements from basicdblist

Hi i have collection which contains around 200 documents looks like
e.g
"_id": 0,
"name": "Demarcus Audette",
"scores": [
{
"type": "exam",
"score": 30.61740640636871
},
{
"type": "quiz",
"score": 14.23233821353732
},
{
"type": "homework",
"score": 31.41421298576332
},
{
"type": "homework",
"score": 30.09304792394713
}
]
now i wrote code like
DBCursor cursor = collection.find().sort(new BasicDBObject("scores.score":1));
while( cursor.hasNext() )
{
DBobject obj=cursor.next();
BasicDBList list=(BasicDBList) Bobj.get("scores");
// Now here i am getting list of documents which consists of an scores array and i need to remove 3rd elements of it and save collection.... but how to do?
if i use for loop like
for(int i=0;i<list.size();i++)
{
list.remove(2);------ it gives an error here
collection.save(obj);
}
}
Are you sure that you can sort it as 'scores.score'. As 'scores' is a list of objects you cant reference objects inside list using dot notation. Error should be on that line.
Edit:
DBCursor cursor = collection.find();
while ( cursor.hasNext()) {
DBObject dbObject = cursor.next();
BasicDBList dbList = (BasicDBList) (dbObject.get("score"));
//then use java Collections.sort() to sort the List (refer to two methods at the bottom)
dbList.remove(3);
collection.save(dbObject);
}
Use one of the following to sort the DBList
1 . Using Lambda expression
Collections.sort(dbList, (o1, o2) -> Double.compare(((BasicDBObject) o1).getDouble("score"), ((BasicDBObject) o2).getDouble("score")));
or java 7 <
Collections.sort(dbList, new Comparator<Object>() {
public int compare(Object o, Object o2) {
if (((BasicDBObject) o).getDouble("score") >= ((BasicDBObject) o2).getDouble("score")) {
return 1;
}
return -1;
}
});
See this link https://gist.github.com/machadolucas/5188447/raw/e3f5c44c2be756c6087809df63f7ea8f4682ace9/Mongo3_1.java
I`m has been
[some symbol for post this message)))]

Resources