RavenDB Complex Model - asp.net-mvc

I am trying to learn RavenDB by replacing my RDBMS in a project that I've already worked on so that I'm using it in a real situation. I've come to a standstill while trying to create the database, and I'd love to know the best way to model this in a document database. Every possibility I come up with either ends up looking like a relational database or ends up repeating vasts amount of information. Repeating the information in the database isn't a big deal, but keeping it all up to date when changes occur would be.
I'm hoping that I'm stuck in SQL mode and I'm just completely unable to see an obvious answer.
Here are the basic objects I need to record data for:
-Event
-Person
-Organization
-Cabin
Simple Requirements:
-A person can be a part of multiple organizations.
-An organization can have many members (people).
-A person can attend multiple events.
-An event has many people that attend.
-Some details about a cabin may change depending on the event (e.g. Accommodations).
Complex Requirements:
-I need to be able to reserve cabins for an event so that a single cabin is not used by two events at once. (with RDBMS I would just create an "EventCabins" table).
-I need to be able to record which people are attending an event. People attending an event will have information associated with them that is not part of Person or Event.
-I need to be able to record which organizations are attending an event. Organizations attending will have information associated with them that is not part of Organization or Event.
-I need to be able to record which People are assigned to which cabins in a particular event.
-I need to be able to record which People are attending a particular event as a part of an organization (it's not required to attend as a part of an organization). Even though a person can belong to more than one organization, he/she can only attend as a part of one of those organizations for a particular event. He/she might attend as a part of a different organization for another event.
-In the program, the user will be looking at only one event at a time. In that event, the user can look at attenders grouped by cabin or grouped by organization.
It seems obvious that I will need separate collections for Events, People, Organizations, and Cabins. Fulfilling the complex requirements above is where I hit the wall.
Do I put Attenders inside the Event collection? If so, then what do I do with Cabins and Organizations?
Do I create a separate collection for Attenders? If so, then there will be 4 different related collections that I will need to store Ids for and query at various times (Organizations, Cabins, Events, People). This seems opposite of the document database approach.
Thanks!

It seems to me that you should just use a relational database for this project.
If you want to use RavenDB I would suggest to use completely separated collections for all of these objects, but keeping references to other documents. Then you could query database using .Include functionality. And the best way - to create map/reduce indecies for all of the possible cases, like an index returning object for Event filled with all of invited people.

Related

MVC Web Api Differentiate between user and public data in RESTful approach

When it comes down to good RESTfull setup, what is the best practice for providing results that pertain to the owner as the requestor and results that pertain to a user wanting data owned by another user.
I have read that a resource should have max 2 base URLs so how to handle say,
Get all items for authenticated user
Get a single item for Authenticated user
Get all items for a particular user
Get a single item for a particular user
Although your question is a bit unclear, it seems to me you might mix up "Resources" as in HTTP resources, and Model objects or database rows.
The two do not necessarily have a 1-to-1 relationship, or even 1-to-2 relationship as you seem to imply. You can expose a database row in multiple "forms" as resources, there is no limitation how many times you can aggregate, transform or publish the same information, as long as those are all semantically different things.
So, back to your problem. You can publish resources pertaining to the authenticated user, and just users independently which might also contain the current user. With an URI structure for example like this:
/currentuser
/user/1
/user/2 <- might be the same as /currentuser
/user/3
...
There also could be a list of users recently logged in:
/recentuser/444
/recentuser/445 <- might be again /currentuser
...
That would be a third reference on the same user, but it is ok, because all of those have a different meaning, might even have different representations to offer (one might offer more information than others).

What is the best way to store a user's Facebook friends list in my database?

Overview
I'm creating a Ruby on Rails website which uses Facebook to login.
For each user I have a database entry which stores their Facebook User ID along with other basic information.
I'm also using the Koala gem in order to retrieve a user's friendlist from Facebook, but I'm unsure as to how I should store this data...
Option 1
I could store the user's friends as a serialized hash in the User table, then if I wanted to display a list of all the current user's friends, I could grab this hash and do something along the lines of SELECT FROM Users WHERE facebook_user_id IN hash
Each time the user logs in I could update this field to store the latest friends list.
Option 2
I could create a Friend table and store friendship information in here, where a User has many Friends. So there would be a row for each friendship, (User1 and User2 columns). Then to display a list of the current user's friends I could do something like SELECT User2 FROM Friends WHERE User1 = current_user
This seems like the better option to me, but...
It has the disadvantage that there would be many rows... If there were 100,000 users, each with 100 friends, that's now 10,000,000 rows in the Friends table.
It also means each time the user logs in, I'd need to loop over their Facebook friends list returned using Koala and create a Friend record if someone on their friendlist is in my User table and there isn't a corresponding entry in the Friends table. This seems like it'd be slow if a user has 1000 Facebook friends?
I'd appreciate any guidance on how it would be best to achieve this.
Apologies for the badly worded question, I'll try and reword/organise it shortly.
Thanks for any help in advance.
If you need to store a lot of data, then you need to store a lot of data. If you are like most, you probably won't run into that problem sooner than you have the cash to solve it. In other words, you are probably assuming you'll have more traffic and data than you'll get, at least in the short-term. So I doubt this is an issue, even though it is a good sign that you are thinking about it now rather than later.
As I mentioned in my comment below, the easiest solution is to have a tie table with a row for each side of the friend relationship (a has_many :friends, through: :facebook_friend_relationships, class_name: 'FacebookFriend' on FacebookFriend, per the design mentioned below). But your question seemed to be about how to reduce the number of records, so that is what the remainder of the answer will address.
If you have to store in the DB and you know for sure that you will absolutely have every FB user on the planet hitting your site because it is so awesome, but they won't all hit at once, then if you are limited in storage, you may want to use a LRU algorithm (remove the least recently used records) possibly with timed expiration also. You could just have a cron job that does a query on the DB then deletes old/unused records to do this. Wouldn't be perfect, but it would be a simple solution.
You could also archive older data rather than throw it away. So, frequently used data could stay in the table of active users, and then you might offload older data to another table or even another database (and you might see the apartment and second_base gems for that). However, once you get to the size, you're probably looking at a number of other architectural solutions that have much less to do with ActiveRecord models/associations or schema design. Though it pays to plan ahead, I wouldn't worry about that excessively until you are sure that the application will get enough users to invest the time in that.
Even though ActiveRecord has some caching, you could just avoid the DB and cache friends in memory yourself in the beginning for speed, especially if you don't yet have many users, which you probably don't yet. If you think you'll run out of memory because of the high number of users, LRU might be a good option here also, and lru_redux looks interesting. Again, you might want to time the cache also so expires and re-gets friends when the cache expires. Even just storing the results in the user session may be adequate, i.e. in the controller action method, just do #friends ||= Something.find_friends(fb_user_id), and the latter is what most might do as a first shot at it while you're getting started.
If you use ActiveRecord, in your query in the controller (or on the association in the model) consider using include: to avoid n+1 queries. That will speed up things.
For the schema design, maybe:
User - users table with email and authN info. Look at the Devise gem.
FacebookUser - info about the Facebook user.
FacebookFriendRelationship - a tie model with (id and) two columns, one for one FacebookUser id and one for the other.
By separating the authN info (User) from the FB data (FacebookUser and FacebookFriendRelationship), you make it easier to have other social media accounts, etc. each with information specific to those accounts in other tables.
The complexity comes in FacebookUser's relationship with friends if the goal is to minimize rows in the relationship table. To half the number of rows, you'd have a single row for a relationship where the id of FacebookUser could be in either foreign key column. Either the user has a friend or is a friend, so you could have two has_many :through associations on FacebookFriend that each use a different foreign key in FacebookFriendRelationship. Or you could do HABTM without the model and use foreign_key and association_foreign_key options in each association. Either way, you could add a method to add both associations together (because they are arrays). Instead, you could use custom SQL in a single has_many if you didn't care about having to use ActiveRecord to remove associations the normal way. However, per your comments, I think you want to avoid this complexity, and I agree with you, unless you really must limit the number of relationship rows. However, it isn't the number of tie table rows that will eat the data, it is going to be all of the user info you keep in the FacebookFriends table.

Rails: Multiple databases, same schema

I'm in the middle of a fictional scenario project where I have allowed multiple users for a company to log in, create records, and so on, who all connect to the one database. They can all records absence records, attendance records, and so on.
What I want to do however, is use this same schema but expands this to allow several companies to have their own databases using the same schema. So each company will have their own data, but all companies use the same data model. In other words all company's can create absence records, but they each only have access to their own absence records that they created themselves.
How can I achieve this?
All I need is two or three files for this, I'm not going commercial with it in case you guys think I'm cutting corners at someone else's expense!
Something as simple as an if-else that decides which file to use would be very useful to me, so if such a line of code exists please let me know.
I think you are doing it wrong (unless you have a really good reason to have a database for each company), because it seems like you are repeating your data model over and over while introducing unnecessary complexity to your code.
Try to have all the companies in one DB/tables with having separated by the company_id.
Ex: data structure would be as follows
companies table
id
name
users table
id
user_name
company_id
However if you really want to connect to multiple databases, check this SO question.

Dimensional Modeling - Queries without facts

I'm creating a dimensional model about a "calls recording system", for a VoIP service.
I'll give demonstrate just a little example to show my question.
Suppose I have a fact that represents a single call. And I have a dimension called Client, and another one called Provider. (pretend that there are other dimensions, like Date of course, and etc...)
(Dimension)Client ---> (Fact)Call <--- (Dimension)Provider
With this, i'll be able to see how many calls a client did, or how many calls were sent through a provider, and other questions.
And lets suppose that one client is associated with a provider, and one provider can have many clients.
So, here comes the question. Hhow can I create a query like: What clients each provider has?
It seems to be a query that is just between both dimensions. I cant involve the fact on that, because if a client never used the service, he wont be on the calls fact table, and he wont apper on this "Clients per Provider" query.
I was thinking with myself that one way to do that would be by creating a Role-Playing-Dimension, a view of the Client dimension and add it directly to the Provider dimension, just to do queries like this. It would be something like this:
(Dimension)Client ---> (Fact)Call <--- (Dimension)Provider <--- (Dimension)View Client
Of course, with this approach the user must be very carefull to dont use this View Client dimension with the fact table, because it would duplicate fact rows.
So, is this one of the situations where I need to use the famous factless fact tables?
Whats the right way to do this?
Thanks!
Role-playing dimensions should be used when you are "recycling" a dimension to be used multiple times in the same fact table (i.e Date of Call, Date of Service, etc).
It doesn't sound like that's what you're looking for. Instead, if the relationship is truly one to many, then I would just add the provider ID directly on the client dimension (no need for a view or anything), with the recognition that this relationship has nothing to do with the facts.
Essentially, think of the "provider" as just an attribute snowflaked off of client, when it comes to this sort of query.
However, it sounds like you might want to be sure that you don't have a many to many relationship between Clients and Providers (a client can use multiple providers, and a provider can have multiple clients). A many-to-many relationship is modeled dimensionally as a fact table. Your fact table could be a snapshot of the current point in time, with or without history. Just two columns are needed, Client and Provider. If you wanted to keep a record of the client/provider relationship by some timeframe, you'd just add a date stamp.
Note that a factless fact will work to model the one-many relationship as well (and if the model changes on the back end, your ETL is already done..)

How do social networking websites compute friend updates?

Social networking website probably maintain tables for users, friends and events...
How do they use these tables to compute friends events in an efficient and scalable manner?
Many of the social networking sites like Twitter don't use an RDBMS at all but a Message Queue application. A lot of them start out with a already present application like RabbitMQ. Some of them get big enough they have to heavily customize or build their own. Twitter is in the process of doing this for the second time.
A message queue application works by holding messages from one service for one or more other services. For instance say service Frank is publishing messages to a queue foo. Joe and Jill are subscribed to Franks foo queue. the application will keep track of whether or not Joe or Jill have recieved the messages and once every subscriber to the queue has recieved the message it discards it. Frank fires messages and forgets about it. Joe and Jill ask for messages from foo and get whatever messages they haven't gotten yet. Joe and Jill do whatever they need to do with the message. Perhaps keeping it around perhaps not.
The message queue application guarantees that everyone who is supposed to get the message can and will get the message when they request them. The publisher can send the messages confident that subscriber can get them eventually. This has the benefit of being completely asynchronous and not requiring costly joins.
EDIT: I should mention also that usually the storage for these kind of things at high scale are heavily denormalized. So Joe and Jill may be storing a copy of the exact same message. This is considered ok because it helps the application scale to billions of users.
Other reading:
http://www.rabbitmq.com/
http://qpid.apache.org/
The mainstay data structure of social networking sites is the graph. On facebook the graph is undirected (When you're someone's friend, they're you're friend). On twitter the graph is directed (You follow someone, but they don't necessarily follow you).
The two popular ways to represent graphs are adjacency lists and adjacency matrices.
An adjacency list is simply a list of edges on the graph. Consider a user with an integer userid.
User1, User2
1 2
1 3
2 3
The undirected interpretation of these records is that user 1 is friends with users 2 and 3 and user 2 is also friends with user 3.
Representing this in a database table is trivial. It is the many to many relationship join table that we are familiar with. SQL queries to find friends of a particular user are quite easy to write.
Now that you know a particular user's friends, you just need to join those results to the updates table. This table contains all the user's updates indexed by user id.
As long as all these tables are properly indexed, you'd have a pretty easy time designing efficient queries to answer the questions you're interested in.
Travis wrote a great post on this ,
Activity Logs and Friend Feeds on Rails & pfeed
For the small scale doing a join on users.friends and users.events and query caching is probably fine but does slow down pretty quickly as friends and events grow. You could also try an event based model in which every time a user creates an event an entry is created in a join table (perhaps called "friends_events"). Thus whenever a user wants to see what events their friends have created they can simply do a join between their own id and the friends_events table and find out. In this way you avoid grabbing all a users with friends and then joining their friends with the events table.

Resources