I would like to build a website that has some elements of a social network.
So I have been trying to think of an efficient way to store a friend list (somewhat like Facebook).
And after searching a bit the only suggestion I have come across is making a "table" with two "ids" indicating a friendship.
That might work in small websites but it doesn't seem efficient one bit.
I have a background in Java but I am not proficient enough with PHP.
An idea has crossed my mind which I think could work pretty well, problem is I am not sure how to implement it.
the idea is to have all the "id"s of your friends saved in a tree data structure,each node in that tree resembles one digit from the friend's id.
first starting with 1 node, and then adding more nodes as the user adds friends.
(A bit like Lempel–Ziv).
every node will be able to point to 11 other nodes, 0 to 9 and X.
"X" marks the end of the Id.
for example see this tree:
An Example
In this tree the user has 4 friends with the following "id"s:
0
143
1436
15
Update: as it might have been unclear before, the idea is that every user will have a tree in a form of multidimensional array in which the existence of the pointers themselves indicate the friend's "id".
If every user had such a multidimensional array, searching if id "y" is a friend of mine, deleting id "y" from my friend list or adding id "y" to my friend list would all require constant time O(1) without being dependent on the number of users the website might have, only draw back is, taking such a huge array, serializing it and pushing it into each row of the table just doesn't seem right.
-Is this even possible to implement?
-Would using serializing to insert that tree into a table be practical?
-Is there any better way of doing this?
The benefits upon which I chose this is that even with a really large number of ids (millions or billions) the search,add,delete time is linear (depends of the number of digits).
I'd greatly appreciate any help with implementing this or any suggestions for alternative ways to improve or change this method.
I would strongly advise against this.
Storage savings are not significant, and may (probably?) be worse. In a real dataset, the actual space-savings afforded to you with this approach are minimal. Computing the average savings is a very difficult problem, but use some real numbers and try a few samples with random IDs. If you have a million users, consider a user with 15 friends. How much data do you save with this approch? You may actually use more space, since tree adjacency models can require significant data.
"Rendering" a list of users requires CPU investment.
Inserts are non-deterministic and non-trivial. When you add a new user to an existing tree, you will have a variety of methods of inserting them. Assuming you don't choose arbitrarily, it is difficult to compute which approach is the best (and would only be based on heuristics).
This are the big ones that came to my mind. But generally, I think you are over-thinking this.
You should check out OQGRAPH, the Open Query graph storage engine. It is designed to handle efficient tree and graph storage for MySQL.
You can also check out my presentation Models for Hierarchical Data with SQL and PHP, or my answer to What is the most efficient/elegant way to parse a flat table into a tree? here on Stack Overflow.
I describe a design I call Closure Table, which records all paths between ancestors and descendants in a hierarchy.
You say 'using PHP' in the title, but this seems to be just a database question at its heart. And believe it or not the linking table is by far the best way to go. Especially if you have millions or billions of users. It would be faster to process, easier to handle in the PHP code and smaller to store.
Update
Users table:
id | name | moreInfo
1 | Joe | stuff
2 | Bob | stuff
3 | Katie | stuff
4 | Harold | stuff
Friendship table:
left | right
1 | 4
1 | 2
3 | 1
3 | 4
In this example Joe knows everyone and Katie knows Harold.
This is of course a simplified example.
I'd love to hear if someone has a better logic to the left and right and an explanation as to why.
Update
I gave some php code in a comment below but it was marked up wrong so here it is again.
$sqlcmd = sprintf( 'SELECT IF( `left` = %1$d, `right`, `left`) AS "friend" FROM `friendship` WHERE `left` = %1$d OR `right` = %1$d', $userid);
Few ideas:
ordered lists - searching through ordered list is fast, though ordering itself might be heavier;
horizontal partitioning data;
getting rid of premature optimizations.
Related
I'm aware this is normally a bad idea, and I've done my reading - in particular, this question.
However the total normalisation route seems more complex and will give me and my code more hoops to jump through. Here's my scenario:
I'm building a test creation system where users can create tests, questions and answers, and associate them all together, i.e. associate answers with questions, and questions with tests. This approach means there's no hard-linking any one kind of data to any other; a given question can be part of two or more tests, for example. So, I was thinking (simplified):
Tests table:
id (PK)
name (varchar)
questions (com-sep list of question IDs)
Questions table:
id (PK)
question text (varchar)
answers (com-sep list of answer IDs)
Answers table:
id (PK)
answer text (varchar)
So a given row in the tests table might look like:
---------------------------------------
| ID | NAME | QUESTIONS |
---------------------------------------
| 1 | SOME TEST | 1,4,7,8,11,19 |
---------------------------------------
Then, when I fetch a test and its questions, I just do some magic with group concat.
Question: is this all a bad idea? It seems a lot simpler than the alternative which is to have two further tables dedicated, respectively, to logging associations between tests and questions, and questions and answers, meaning more tables involved in any queries.
Yes, it probably is a bad idea.
Why do you think of having two more whole tables (whoa!!) as a big deal? It really isn't.
Anyway, if you're really definitely never going to want to do something like "find out which tests question 3 appears in" then go nuts, but the moment you do find you have to do something like that you'll wish you had just done it the right way.
And how will you make sure that your data is even halfway sensible? If 564 appears as an entry in one of your comma-separated lists, will you be sure that there is definitely a question number 564 in the Questions table, that it hasn't been deleted since? What a lot of extra complication to avoid creating two tables. If you don't like typing the SQL to perform the joins, you could just use an ORM.
Sure, there are cases when denormalization is worthwhile.
But keep in mind that denormalization helps simplify a subset of queries against your data, at the expense of all other queries.
The scenarios listed in my answer to Is storing a delimited list in a database column really that bad? show how many other types of queries or updates you might have to do against your data. Searching, sorting, inserting, deleting... Also, relying on referential integrity to avoid your data turning to a collection of orphans.
But if you know that fetching or updating the whole list of id's is the only thing you need to optimize for, and this will never change (famous last words), then go for it, use denormalization.
If you want any of those other types of queries to be convenient or efficient, stick with a normalized design.
When storing relationship data for a user (potentially a thousand friends per user), would it be faster to create a new row for each relationship, or to concatenate all of of their friends into a string and then parse that later?
I.e.
Primary id | Friend1ID | Friend2ID|
1| 234| 5789|
2| 5789| 234|
Where the IDs are references to primary IDs in a 'Users' table.
Or for the 'Users' table to just have a column called friends which may look like this:
Primary id | Friend1ID |
234| 5789.123.8474|
5789| 234|
I'm of the understanding that string concatenation and parsing is generally quite slow, so I'd be tempted to lean towards the first method. However as the number of users grows, this then becomes a case of selecting one row and parsing it V searching millions of rows for rows which match the WHERE criteria.
Is one method distinctly faster than the other? Particularly as the number of users grows.
You should use a second table to store the friends.
Users Table
----------
userid | username
1 | Bob
2 | Mike
3 | John
Users Friends Table
--------------------
userid | friend_id
1 | 2
3 | 2
Here you can see that Mike is friends with both Bob and John.... This is of course a very simply demonstration.
Your second option will not scale, some people may have hundreds of thousands of friends, storing each Id in a single field is going to cause a headache further down the line. adding friends, removing friends. working out complex relationships between people. Lots of over head.
Querying millions of records with a WHERE clause on a properly indexed table should take no more than a second, the first option is the better one.
The "correct" way would probably be keeping multiple rows. This allows for much easier statistical analysis and more complex queries (like friends of friends) without any hacky stuff. Integer storage size is also often smaller than string storage, even though you're repeating one ID - especially if you use an appropriately sized integer store (like mediumint).
It's also more maintainable, scalable (if they start getting a damn lot of friends) export and importable. The speed gain from concatenation, if any, wouldn't be worth the rest of the benefits.
If you wanted for instance to search if Bob was a friend of Jane, this would be a single row lookup in the multiple row implementation, or in the single row implementation: get Bob's row, decode field, loop through field looking for Jane - found Jane. DBMS optimisation and indexing would make the multiple row implementation much faster in this case - if you had the primary key as (id, friendid) then it'd be pretty much instantaneous as the table would probably be hashed on that key.
I believe the proper way to do it which might be more faster is two do a two columns table
user | friend
1 | 2
1 | 3
It will simple and will make queering and updating much easier and you can have as many relationship as you want.
Don't over complicate the problem...
... Asking for the more "correct" way is wrong itself.
It depends based on case.
If you have low access rate to your web application having more rows won't change anything on the other side of the coins (i'm not English), on large and medium application access it's maybe better to have the minimal access to the db possible.
To obtain this as you've already thinked you can concatenate the values and then split them on login of the user and then put everything into the $_SESSION supervar.
At least this is what i think.
I'm trying to add a comment system that uses hierarchical design. Here's a sample from my database that keeps track of posts/replies (note that more rows are added as more people reply):
post_id | parent_id
1 1
2 1
3 1
4 2
5 3
6 2
7 4
I've done some research about different methods to output and manipulate the data to get what you need, but I'm not sure which method would be best for a comment system and how I would do it.
I know that adjacency lists wouldn't work because it can't handle deep trees.
Please help.
Judging by nowadays trends, AL is quite acceptable solution. All modern sites tend to dump all the comments on one page - means no sophisticated SQL logic ever required but just simple query for all the comments belongs to single article. And one loop to store them in array.
If you want no loops but get all the comments in one query already sorted, then Materialized Path would be handy. For the implementation you can find plenty of examples, I am sure.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the most efficient/elegant way to parse a flat table into a tree?
This I am finding rather tricky and would like some opinions on the matter.
I am trying to store hierarchal data (tree like) with an unknown number of levels and branches. I am wanting to be able to add new ones and delete any at any time.
I need to be able to query from any node in the hierarchy for all of the children id's in one go and efficiently due to large user base.
Lets take a hypothetical example of a website where families socialise and update their status like in facebook and at any time you can be viewing a family members "Wall" which will also include all of the recent status updates form the people below them in the hierarchy in chronological order.
Obviously the fetching posts once you have the array of family members id's who are children of this family members node is easy enough in a loop.
Lets take an example simple table structure of:
id | parentId | name
________________________
1 | NULL | John
2 | 1 | Peter
3 | 1 | Bob
4 | 3 | Emma
5 | 2 | Sam
6 | 4 | Gill
etc.... You get the idea.
I need to be able to do the above with something like this unless you think the structure needs to be adapted.
I have read up on mySql nested set model.
This seems very fiddly and could be unreliable if something was not to update correctly and would mess everything up.
I am used to using php and mysql but have been reading a bit on cassandra and thrift. Not sure if this would be easier?
There are already good approaches out there which are more simple than the solution you propose.
Here are a couple of links which explain how to do it (we use this ourselves for much the same problem you describe and it works well).
Managing Hierarchical Data in MySQL (from MySQL)
Storing Hierarchical Data in a Database (from Sitepoint, but a clearer explanation, I think)
This makes inserting/updating more complex, but selecting portions of the tree structure far faster (with only one query). It allows finding all children of any given node in one query, and finding all the ancestors of a given node with one query.
So I think I have come up with an idea.
The reason I am against the nested set model is because it seems like it is still not the best way and is not going to be the ideal performance solution.
I am going to cover a proposed solution I have been thinking about.
The concept means creating an hierarchal map table to keep track of all the relationships between each family member/node.
The way it would work is:
Using map table structure of this:
id | fMemberId | parentid
=====================================
1 | 3 | 2
2 | 4 | 3
3 | 4 | 2
1) As a new family member is created as a child of a parent we would take the parents id and create a new row in our family members table with the parent id set for future additional uses and functionality.
2) As this row is created we will create new rows with all of the parent id's for the new family member.
A quick way to do this would be to take the parent id from the new family member and do a query to the map table to find all the rows with the family member id the same as the new family members parent id and then store an array in php of the subsequent parent ids required for storing alongside the new family members id in the map table. This would then only require one sql query for grabbing all the parent id's for adding them rather than a number of queries based on the number of nodes
This would mean when we are viewing a family members feed of posts we would be able to query the db for simply the rows in the map table to get all the children id's of the current family member and subsequently query other tables for the post data.
The main trade off being the amount of potential storage required for this kind of system.
However I believe reading speed would be quicker as there is no conditional SQL statements and also maybe just as quick to write to db in this way.
We could overcome this by using InnoDB's cluster id's assigning an initial family id index and creating a new table with the "next family members id" based on the family id.
Also reliability, if a row wasn't written it would be easy enough to add it in. It prevents having to continually edit rows just to create a member.
What are your thoughts on this?
So far this seems to be a good way in my opinion. Took a lot of thinking to get to here. I also believe it could maybe be improved with time and being able to store arrays of id's per member rather than all of them. Still trying to work that one out!
Yes, your solution is called a transitive closure. I have written about it before:
What is the most efficient/elegant way to parse a flat table into a tree?
Models for Hierarchical Data
You also need the zero-length paths, e.g. 2-2, 3-3, 4-4.
Greetings All, I've seen similar questions asked before with no conclusive or tested answers.
I'm designing a News Feed system using PHP/MySQL similar to facebooks. Seeing as this table could grow to be quite large -- any inefficiency could result in a significant bottleneck.
Example Notifications:
(Items in bold are linked objects)
User_A and USER_B commented on User_C's new album.
User_A added a new Vehicle to [his/her] garage.
Initially, I implemented this using excessive columns for Obj1:Type1 | Obj2:Type2 | etc..
It works but I fear it's not nearly scalable enough, now I'm looking to object serialization.
So, for example my new database is set up like so:
News_ID | User_ID | News_Desc | Timestamp
2643 904 {User904} and {User890} commented on SomeTimestamp
{User222}'s new {Album724}.
Anything inside {'s represents data that would be serialized using JSON.
Is this a smart (efficient / scalable) way to move forward?
Will it be difficult to separate the serialized data from the rest of the string using regular expressions?
What happens if User890 deletes his/her comment? I think you need to be more atomic - possibly storing the type of action (comment) with the actioner (User890), then generate the actual story on the fly, with heavy caching. This would also help the issue of translation, if you extend your site to several markets/audiences.