My document
{
itemName: 'name1',
itemType: 'book',
createTime: '2014-09-24 10:10:10'
}
Then I want to query the last n days created item group by createTime and itemType
In other words, I expected my result something like this
[{
group: '2014-09-24',
reduction {
{
group: 'book',
reduction: {count: 100}
},
{
group: 'computer',
reduction: {count: 100}
},
},
{
group: '2014-09-22',
reduction {
{
group: 'book',
reduction: {count: 100}
},
{
group: 'computer',
reduction: {count: 100}
}
}
}]
The rql may looks like
r.db(xx).table(yy)
.order({index: r.desc(createTime)})
.group(r.row('createTime').date())
.map(function() {
????
}).ungroup()
You can also directly order everything (but you don't get nested fields:
r.db(xx).table(yy)
.group([r.row("createTime"), r.row("itemType")])
.count()
You somehow cannot use group inside group for now.
See https://github.com/rethinkdb/rethinkdb/issues/3097 to track progress on this limitation.
Related
After having implemented dataloader in the respective resolvers to solve the N+1 problem, I also need to be able to solve the N+N problem.
I need a decently efficient data loading mechanism to get a relation like this:
{
persons (active: true) {
id,
given_name,
projects (active: true) {
id,
title,
}
}
}
I've created a naive implementation for this, returning
{
persons: [
{
id: 1,
given_name: 'Mike'
projects: [
{
id: 1,
title: 'API'
},
{
id: 2,
title: 'Frontend'
}
]
}
{
id: 2,
given_name: 'Eddie'
projects: [
{
id: 2,
title: 'Frontend'
},
{
id: 3,
title: 'Testing'
}
]
}
]
}
In SQL the underlying structure would be represented by a many many to many relationship.
Is there a similiar tool like dataloader for solving this or can this maybe even be solved with dataloader itself?
The expectation with GraphQL is that the trip to the database is generally the fastest thing you can do, so you just add a resolver to Person.projects that makes a call to the database. You can still use dataLoaders for that.
const resolvers = {
Query: {
persons(parent, args, context) {
// 1st call to database
return someUsersService.list()
},
},
Person: {
projects(parent, args, context) {
// this should be a dataLoader behind the scenes.
// Makes second call to database
return projectsService.loadByUserId(parent.id)
}
}
}
Just remember that now your dataLoader is expecting to return an Array of objects in each slot instead of a single object.
So I'm trying to construct a mutation for inserting/updating a record for a "Person" along with it's address, email, telephones information into multiple tables, using variables.
mutation insertPerson ($address: [adr_insert_input!]!, $emails: [emails_insert_input!]!) {
insert_info(objects: [{
f_name: "User1",
l_name: "Test"
address: {
data: $address,
on_conflict: {
constraint: person_id_pk,
update_column: [add_text_line1, zip_code]
}
},
emails: {
data: $emails,
on_conflict: {
constraint: person_id_pk,
update_column: [email_text]
}
}
}], on_conflict: {
constraints: person_pk,
update_columns: [f_name, l_name]
}) {
affected_rows
}
}
and my variables are set-up as follows...
{
"address": [{
"add_text_line1": "123 Main Street",
"zip_code": 50501
}],
"emails": [{
"email_text": "FirstLastName#email.com"
}]
}
This works as expected for me (with multiple values in emails array too), but I need to move the f_name & l_name values (whole Person object) into a variable as well. How do I achieve that?
I tried the below mutation this way, but this resulted into two separate inserts & empty values being passed...
mutation insertPerson ($person: person_insert_input!, $address: [adr_insert_input!]!){
insertData(objects: [
$person,
{
address: { data: $address }
}
]) { affected_rows }
}
This resulted to a two separate insertions... First person with empty address, then empty person with address.
How do I achieve the first mutation's result, while using Person Info as part of variables NOT hard-code it into the query itself?
Thank you!
You will need to pass the insert_info objects as the variables
mutation insertPerson ($info_objects: [insert_info_insert_input!]!) {
insert_info(objects: $info_objects, on_conflict: {
constraints: person_pk,
update_columns: [f_name, l_name]
}) {
affected_rows
}
}
And your variables will be an array of the info_objects
{info_objects: [{
f_name: "User1",
l_name: "Test"
address: {
data: [{
"add_text_line1": "123 Main Street",
"zip_code": 50501
}]
},
on_conflict: {
constraint: person_id_pk,
update_column: [add_text_line1, zip_code]
}
},
emails: {
data: [{
email_text: "FirstLastName#email.com"
}],
on_conflict: {
constraint: person_id_pk,
update_column: [email_text]
}
}
}]}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Given an array of objects exampled below.
[
{ group: '1' },
{ group: '1' },
{ group: '1' },
{ group: '2' },
{ group: '1' }
]
Expected output would be:
[
[{ group: '1' }, { group: '1' }, { group: '1' }],
[{ group: '2' }],
[{ group: '1' }]
]
Important to note that even though "group 1" occurs 4 times, there will be 2 different groupings because we're taking the position of the object in the array as well... the group names are arbitrary as well.
Ruby does this with a builtin: Chunk
Enumerates over the items, chunking them together based on the return value of the block.
Consecutive elements which return the same block value are chunked together.
Which looks like exactly what you want:
data
.chunk{ |item| item[:group] }
.map{ |_chunk_value, items| items } # chunk gives a pair of the value the chunk used and the values in the chunk, but we only need the values.
arr = [
{ group: '1' },
{ group: '1' },
{ group: '1' },
{ group: '2' },
{ group: '1' }
]
arr.slice_when { |g,h| g[:group] != h[:group] }.to_a
#=> [[{:group=>"1"}, {:group=>"1"}, {:group=>"1"}],
# [{:group=>"2"}],
# [{:group=>"1"}]]
See Enumerable#slice_when.
You can initialize results = [] and then build it up by iterating over the input. As you process each input hash, you check whether the last element in results matches. If so, you add the input hash there. Otherwise, you start a new list in results:
input = [
{ group: '1', },
{ group: '1', },
{ group: '1', },
{ group: '2', },
{ group: '1', }
]
results = []
input.each do |hsh|
last = results.last
if last && last.last[:group] == hsh[:group]
last.push hsh
else
results.push [hsh]
end
end
print results
# => [
# [{:group=>"1"}, {:group=>"1"}, {:group=>"1"}],
# [{:group=>"2"}],
# [{:group=>"1"}]
# ]
I started to learn GraphQL and I'm trying to create the following relationship:
type User {
id: ID!,
name: String!,
favoriteFoods: [Food]
}
type Food {
id: ID!
name: String!
recipe: String
}
So basically, a user can have many favorite foods, and a food can be the favorite of many users. I'm using graphql.js, here's my code:
const Person = new GraphQLObjectType({
name: 'Person',
description: 'Represents a Person type',
fields: () => ({
id: {type: GraphQLNonNull(GraphQLID)},
name: {type: GraphQLNonNull(GraphQLString)},
favoriteFoods: {type: GraphQLList(Food)},
})
})
const Food = new GraphQLObjectType({
name: 'Food',
description: 'Favorite food(s) of a person',
fields: () => ({
id: {type: GraphQLNonNull(GraphQLID)},
name: {type: GraphQLNonNull(GraphQLString)},
recipe: {type: GraphQLString}
})
})
And here's the food data:
let foodData = [
{id: 1, name: 'Lasagna', recipe: 'Do this then that then put it in the oven'},
{id: 2, name: 'Pancakes', recipe: 'If you stop to think about, it\'s just a thin, tasteless cake.'},
{id: 3, name: 'Cereal', recipe: 'The universal "I\'m not in the mood to cook." recipe.'},
{id: 4, name: 'Hashbrowns', recipe: 'Just a potato and an oil and you\'re all set.'}
]
Since I'm just trying things out yet, my resolver basically just returns a user that is created inside the resolver itself. My thought process was: put the food IDs in a GraphQLList, then get the data from foodData usind lodash function find(), and replace the values in person.favoriteFoods with the data found.
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
description: 'Root Query',
fields: {
person: {
type: Person,
resolve(parent) {
let person = {
name: 'Daniel',
favoriteFoods: [1, 2, 3]
}
foodIds = person.favoriteFoods
for (var i = 0; i < foodIds.length; i++) {
person.favoriteFoods.push(_.find(foodData, {id: foodIds[i]}))
person.favoriteFoods.shift()
}
return person
}
}
}
})
But the last food is returning null. Here's the result of a query:
query {
person {
name
favoriteFoods {
name
recipe
}
}
}
# Returns
{
"data": {
"person": {
"name": "Daniel",
"favoriteFoods": [
{
"name": "Lasagna",
"recipe": "Do this then that then put it in the oven"
},
{
"name": "Pancakes",
"recipe": "If you stop to think about, it's just a thin, tasteless cake."
},
null
]
}
}
}
Is it even possible to return the data from the Food type by using only its ID? Or should I make another query just for that? In my head the relationship makes sense, I don't think I need to store the IDs of all the users that like a certain food in the foodData since it has an ID that I can use to fetch the data, so I can't see the problem with the code or its structure.
Calling shift and push on an array while iterating through that same array will invariably lead to some unexpected results. You could make a copy of the array, but it'd be much easier to just use map:
const person = {
name: 'Daniel',
favoriteFoods: [1, 2, 3],
}
person.favoriteFoods = person.favoriteFoods.map(id => {
return foodData.find(food => food.id === id)
})
return person
The other issue here is that if your schema returns a Person in another resolver, you'll have to duplicate this logic in that resolver too. What you really should do is just return the person with favoriteFoods: [1, 2, 3]. Then write a separate resolver for the favoriteFoods field:
resolve(person) {
return person.favoriteFoods.map(id => {
return foodData.find(food => food.id === id)
})
}
I am trying to write a part of a query to filter out any items with a type as "group" and that have a group id that isn't in a given array of ids. I started writing a bool query with a must and must_not but I was getting tripped up on how to write "id not in the given array.
EDIT:
I am actually converting an outdated query using "and" and "not" to be ES 5.5 compatible. Here is the old query that worked.
:and => [
{
term: {
type: 'group'
}
},
{
:not => {
terms: {
group_id: group_ids
}
}
},
{
:not => {
terms: {
user_id: user_ids
}
}
}
]
group_ids and user_ids are arrays.
You probably have not analyzed the arrays with the IDs. You can use a Bool query with a filter clause, and then within that filter start a new bool query with a mustNot clause and within that clause add a terms query with your IDs.
bool: {
must: {
term: {
kind: 'group'
}
},
must_not: [
{
terms: {
group_id: group_ids
}
},
{
terms: {
user_id: user_ids
}
}
]
}