RUBY Grouping data by parsed REST JSON result property - ruby-on-rails

First of all, I am very new to Ruby so go easy on me! I have the parsed JSON in my sourceHash variable and I am trying to group data by the "displayName" property. The JSON format is something like this (I've simplified it without changing the structure):
{
"results": [
{
"id": "12345",
"title": "my blog post",
"history": {
"createdOn": "2017-09-18 15:38:26",
"createdBy": {
"userName": "myUserName",
"displayName": "Michael W."
}
}
},
{ ... same stuff for some other blog post ... },
{ ... same stuff for some other blog post ... },
{ ... same stuff for some other blog post ... }
]
}
Basically, there are two things I want to do.
Imagine this list as "list of blog posts including the author data" of them.
Find the person who posted the most amount of entries
Get the top 10 bloggers, ordered by their blog post count, descending
So the first would look something like this:
Michael W. (51 posts)
However, the second one would look like this:
Michael Wayne (51 posts)
Emilia Clarke (36 posts)
Charlize Theron (19 posts)
Scarlett Johansson (7 posts)
I've played around these queries, trying to merge my LINQ logic into this, but I failed... (I'm a Ruby noob so be easy!)
sourceHash = #mainData["results"]
hashSetPrimary = sourceHash.group_by{|h| h['history']['createdBy']['displayName']}
return hashSetPrimary
So long story short, I am trying to write to separate queries that would group the data by those criteria, any help is appreciated as I can't find any proper way to do it.

Firstly, you need to look at your hash syntax. When you define a hash using h = { "foo": "bar" }, the key is not actually a string, but rather a symbol. Therefore accessing h["foo"] is not going to work (it will return nil); you have to access it as h[:foo].
So addressing that, this does what you need:
sourceHash = #mainData[:results]
hashSetPrimary = sourceHash.group_by{ |h| h.dig(:history, :createdBy, :displayName) }
.map { |k, v| [k, v.count] }
.sort_by(&:last)
return hashSetPrimary
Hash#dig requires Ruby 2.3+. If you are running on a lower version, you can do something like this instead of dig:
h[:history] && h[:history][:createdBy] && h[:history][:createdBy][:displayName]

Related

Is it possible to query multiple keys in a single query? [duplicate]

This question already has an answer here:
Speed up fetching posts for my social network app by using query instead of observing a single event repeatedly
(1 answer)
Closed 1 year ago.
I am new to Firebase. The following is my database's structure.
{
"dvdStores": {
"store1": {
"movies": {
"0": "Don't Look Up",
"1": "Top Gun"
}
},
"store2": {
"movies": {
"0": "Jungle Book",
"1": "Taken"
}
},
"store3": {
"movies": {
"0": "The Matrix",
"1": "Home Alone"
}
},
"store4": {
"movies": {
"0": "The Lion King"
}
}
}
}
Can I get all the movies corresponding to multiple keys in a single query?
I would e.g. want to get all the movies corresponding to keys store1 and store4. Can this be done in a single query?
Thanks in advance :)
This is not possible. You must request them each individually. All queries for a node always get the entire node, including all of its nested children. Children cannot be selectively included or excluded.
It's worth noting also that there is not much overhead in making multiple requests. The data for each query is pipelined over a single socket connection, so as long as you keep that connected saturated with requests, you are not losing very much perceived performance.

Complex queries in CouchDB across multiple types of documents

I'm relatively new to CouchDB (more specifically Cloudant if it matters) and I'm having a hard time wrapping my head around something.
Assume the following (simplified) document examples:
{ "docType": "school", "_id": "school1", "state": "CA" }
{ "docType": "teacher", "_id": "teacher1", "age": "40", "school": "school1" }
I want to find all the teachers aged $age (eg. 40) in state $state (eg. CA).
Views only consider one document at a time; that is queries can't directly combine data from different documents. You can query across multiple fields in the same document using Cloudant Query. You can write a selector directly in the Cloudant dashboard. Something like
"selector": {
"age": {
"$gte": 40
},
"state": {
"$eq": "CA"
}
}
See https://cloud.ibm.com/docs/services/Cloudant/tutorials?topic=cloudant-creating-an-ibm-cloudant-query
with the full reference here: https://cloud.ibm.com/docs/services/Cloudant/tutorials?topic=cloudant-query
You could also use a so-called linked document to emulate basic joins, as outlined in the CouchDB docs https://docs.couchdb.org/en/stable/ddocs/views/joins.html

What is The default JSON specification used in RoR response?

I'm using RoR for a couple of time. But after read many json specification for example jsonapi.org and json-schema.org I have the next question: What is the default JSON specification used in RoR ?
Because when you render a json in RoR you get this for example:
post: {
id: 1,
title: 'Stackoverflow rised 1 billion of alien money',
description: 'blablabla'
}
Is it a good practice if I used the default response in RoR when I'm creating an API ?
One specific thing that may or may not be helpful...
One thing that bothers me about the default rendering of JSON w/ Rails is that it leaves the key names unquoted when serializing a Hash, which is (technically) not valid JSON. The way to fix this is to add
ActiveSupport::JSON.unquote_hash_key_identifiers = false
to a configuration file like environment.rb. Once you've done that, serializing
my_hash = { post: { id: 1, title: 'Stackoverflow rised 1 billion of alien money', description: 'blablabla' } }
to JSON would change to
post: {
"id": 1,
"title": 'Stackoverflow rised 1 billion of alien money',
"description": 'blablabla'
}
vs. what you have above without the quotes.

Get event rsvp summary using koala gem in rails

I have been able to retrieve event details using
#graph = Koala::Facebook::API.new(access_token)
#eventSummary = #graph.get_object(eventId)
and getting users list invited using
#eventSummary = #graph.get_connections(eventId, "invited")
I want to get count for all user invited, maybe, Declined and accepted for the event. for which i'm using
#eventSummary = #graph.get_connections(eventId, "invited?summary=1")
which again giving me the list of users only. when used graph.facebook like
https://graph.facebook.com/***eventId***/invited?access_token=*****access_token****&summary=1
i'm getting the count in result.
{
"data": [
{
"name": "xyz",
"rsvp_status": "attending",
"id": "10000000123"
}
],
"paging": {
"next": "https://graph.facebook.com/***eventId***/invited?summary=1&access_token=***accesstoken***&limit=5000&offset=5000&__after_id=100004389574321"
},
"summary": {
"noreply_count": 0,
"maybe_count": 0,
"declined_count": 0,
"attending_count": 1,
"count": 1
}
}
for just solving purpose i'm getting result using fql, as:
#eventSummary = #graph.get_object("fql", :q => "SELECT all_members_count, attending_count, declined_count, not_replied_count, unsure_count FROM event WHERE eid = #{eventId}")
But this is not convenient to use.
Can anyone please help, what am i doing wrong ? To get Event RSVP counts.
I'm using rails v.3.2, for facebook using Koala gem.
Thanks in advance.
I've seen it too, that when you request the event itself, those attendee count fields aren't included. You can use the second parameter to specifically ask for them though:
#eventSummary = #graph.get_object(eventId)
#eventSummary.merge(#graph.get_object(eventId, fields: "attending_count,declined_count,interested_count"))
The first call gets your "standard" event details, something like this:
{"description"=>"Blah blah blah",
"name"=>"My Event Will Rock",
"place"=>{"name"=>"Venue Bar",
"location"=>{"city"=>"Citytown",
"country"=>"United States",
"latitude"=>43.05308,
"longitude"=>-87.89614,
"state"=>"WI",
"street"=>"1216 E Brady St",
"zip"=>"53202"},
"id"=>"260257960731155"},
"start_time"=>"2016-04-22T21:00:00-0500",
"id"=>"1018506428220311"}
The second call gets just those "additional" requested fields:
{"attending_count"=>3,
"declined_count"=>0,
"interested_count"=>12,
"id"=>"1018506428220311"}
You can store them in separate variables, or as I'm suggesting above, use the hash#merge method. (There shouldn't be any problematic overlap between the keys of these two hashes.)
Alternatively, you can get all these details in one request by explicitly requesting everything you want.

Set based updates in RavenDB

I am working with RavenDB documents. I need to change a field in all the documents at once. I read there is something called set based updates in Raven DB documentation. I need a little help to put me in right direction here.
A patron Document looks something like this:
{
"Privilege": [
{
"Level": "Gold",
"Code": "12312",
"EndDate": "12/12/2012"
}
],
"Phones": [
{
"Cell": "123123",
"Home": "9783041284",
"Office": "1234123412"
}
]
{
In Patrons document collection, there is a Privilege.Level field in each doc. I need to write a query to update it to "Gold" for all documents in that Patrons collection. This is what I know so far. I need to create an Index (ChangePrivilegeIndex) first:
from Patrons in docs.patrons
select new {Patrons.Privilege.Level}
and then write a curl statement to patch documents all at once something like this:
PATCH http://localhost:8080/bulk_docs/ChangePrivilegeIndex
[
{ "Type": "Set", "Name": "Privilege.Level", "Value": "Gold"}
]
I need help to get this to work .. thank you. I know there are lots of loose ends in the actual scripts.. that's why its not working. Can some one look at the scenario and the script above to put me in right direction.

Resources