How to keep a list of 'used' data per user - sql

I'm currently working on a project in MongoDB where I want to get a random sampling of new products from the DB. But my problem is not MongoDB specific, I think it's a general database question.
The scenario:
Let's say we have a collection (or table) of products. And we also have a collection (or table) of users. Every time a user logs in, they are presented with 10 products. These products are selected randomly from the collection/table. Easy enough, but the catch is that every time the user logs in, they must be presented with 10 products that they have NEVER SEEN BEFORE. The two obvious ways that I can think of solving this problem are:
Every user begins with their own private list of all products. Each time they get one of these products, the product is removed from their private list. The result is that the next time products are chosen from this previously trimmed list, it already contains only new items.
Every user has a private list of previously viewed products. When a user logs in, they select 10 random products from the master list, compare the id of each against their list of previously viewed products, and if the item appears on the previously viewed list, the application throws this one away selects a new one, and iterates until there are 10 new items, which it then adds to the previously viewed list for next time.
The problem with #1 is it seems like a tremendous waste. You would basically be duplicating the list data for n number of users. Also removing/adding new items to the system would be a nightmare since it would have to iterate through all users. #2 seems preferable, but it too has issues. You could end up making a lot of extra and unnecessary calls to the DB in order to guarantee 10 new products. As a user goes through more and more products, there are less new ones to choose from, so the chances of having to throw one away and get new one from the DB greatly increases.
Is there an alternative solution? My first and primary concern is performance. I will give up disk space in order to optimize performance.

Those 2 ways are a complete waste of both primary and secondary memory.
You want to show 2 never before seen products, but is this a real must?
If you have a lot of products 10 random ones have a high chance of being unique.
3 . You could list 10 random products, even though not as easy as in MySQL, still less complicated than 1 and 2.

If you don't care how random the sequence of id's is you could do this:
Create a single randomized table of just product id's and a sequential integer surrogate key column. Start each customer at a random point in the list on first login and cycle through the list ordered by that key. If you reach the end, start again from the top.
The customer record would contain a single value for the last product they saw (the surrogate from the randomized list, not the actual id). You'd then pull the next ten on login and do a single update to the customer. It wouldn't really be random, of course. But this kind of table-seed strategy is how a lot of simpler pseudo-random number generators work.
The only problem I see is if your product list grows more quickly than your users log in. Then they'd never see the portions of the list which appear before wherever they started. Even so, with a large list of products and very active users this should scale much better than storing everything they've seen. So if it doesn't matter that products appear in a set psuedo-random sequence, this might be a good fit for you.
Edit:
If you stored the first record they started with as well, you could still generate the list of all things seen. It would be everything between that value and last viewed.

How about doing this: crate a collection prodUser where you will have just the id of the product and the list of customersID, (who have seen these products) .
{
prodID : 1,
userID : []
}
when a customer logs in you find the 10 prodID which has not been assigned to that user
db.prodUser.find({
userID : {
$nin : [yourUser]
}
})
(For some reason $not is not working :-(. I do not have time to figure out why. If you will - plz let me know.). After showing the person his products - you can update his prodUser collection. To mitigate mongos inability to find random elements - you can insert elements randomly and just find first 10.
Everything should work really fast.

Related

Reducing database load from consecutive queries

I have an application which calls the database multiple times to achieve one simple goal.
A little information about this application; In short, the application scrapes data from a webpage & stores specific information from this page into a database. The important information in this query is: Player name, Position. There can be multiple sitting at one specific position, kill points & Class
Player name has every potential to change or remain the same every day
Regarding the Position, there can be multiple sitting in one position
Kill points has the potential to increase or remain the same every day
Class, there is only 2 possibilities that a name can be, Ex: A can change to B or remain A (same in reverse), but cannot be C,D,E,F
The player name can change at any particular day, Position can also change dependent on the kill point increase from the last update which spins back around to the goal. This is to search the database day by day, from the current date to as far back as 2021-02-22 starting at the most recent entry for a player name and back track to the previous day to check if that player name is still the same or has changed.
What is being used as a main reference to the change is the kill points. As the days go on, this number will either be the exact same or increase, it can never decrease.
So now onto the implementation of this application.
The first query which runs finds the most recent entry for the player name
SELECT TOP(1) * FROM [changes] WHERE [CharacterName]=#charname AND [Territory]=#territory AND [Archived]=0 ORDER BY [Recorded] DESC
Then continue to check the previous days entries with the following query:
SELECT TOP(1) * FROM [changes] WHERE [Territory]=#territory AND [CharacterName]=#charname AND [Recorded]=#searchdate AND ([Class] LIKE '%{Class}%' OR [Class] LIKE '%{GetOpposite(Class)}%' AND [Archived]=0 )
If no results are found, will then proceed to find an alternative name with the following query:
SELECT TOP(5) * FROM [changes] WHERE [Kills] <= #kills AND [Recorded]='{Data.Recorded.AddDays(-1):yyyy-MM-dd}' AND [Territory]=#territory AND [Mode]=#mode AND ([Class] LIKE #original OR [Class] LIKE #opposite) AND [Archived]=0 ORDER BY [Kills] DESC
The aim of the query above is to get the top 5 entries that are the closest possible matches & Then cross references with the day ahead
SELECT COUNT(*) FROM [changes] WHERE [CharacterName]=#CharacterName AND [Territory]=#Territory AND [Recorded]=#SearchedDate AND [Archived]=0
So with checking the day ahead, if the character name is not found in the day ahead, then this is considered to be the old player name for this specific character, else after searching all 5 of the results and they are all found to be present in the day aheads searches, then this name is considered to be new to the table.
Now with the date this application started to run up to today's date which is over 400 individual queries on the database to achieve one goal.
It is also worth a noting that this table grows by 14,400 - 14,500 Rows each and every day.
The overall question to this specific? Is it possible to bring all these queries into less calls onto the database, reduce queries & improve performance?
What you can do to improve performance will be based on what parts of the application stack you can manipulate. Things to try:
Store Less Data - Database content retrieval speed is largely based on how well the database is ordered/normalized and just how much data needs to be searched for each query. Managing a cache of prior scraped pages and only storing data when there's been a change between the current scrape and the last one would guarantee less redundant requests to the db.
Separate specific classes of data - Separating data into dedicated tables would allow you to query a specific table for a specific character, etc... effectively removing one where clause.
Reduce time between queries - Less incoming concurrent requests means less resource contention and faster response times to prior requests.
Use another data structure - The only reason you're using top() is because you need data ordered in some specific way (most-recent, etc...). If you just used a code data structure that keeps the data ordered and still easily-query-able you could then perhaps offload some sql requests to this structure instead of the db.
The suggestions above are not exhaustive, but what you do to improve performance is largely a function of what in the application stack you have the ability to modify.

Most efficient way to find random item not present in join table and without repeating previous random item

In my Rails 4 app I have an Item model and a Flag model. Item has_many Flags. Flags belong_to Item. Flag has the attributes item_id, user_id, and reason. I am using enum for pending status. I need the most efficient way to get an item that doesn't exist in the flags table because I have a VERY large table. I also need to make sure that when a user clicks to generate another random item, it will not repeat the current random item back to back. It would be OK to repeat any time afterwards, just not back to back.
This is what I have so far:
def pending_item
#pending_items = Item.joins("LEFT OUTER JOIN flags ON flags.item_id = items.id").
where("items.user_id != #{current_user.id} and flags.id is null")
#pending_item = #pending_badges.offset(rand #pending_badges.count).first
end
Is there a more efficient way than this?
And how can I make sure there are no back to back repeats of the same pending_item?
What you have is the fastest way to do it in the database I know of (which is why I gave it here). Many other Stack Overflow posts discuss ways to efficiently select random rows from tables; there are more efficient methods if you're selecting from an entire table, but they don't apply when you're selecting a random result from a query whose results can be different every time.
If performance is critical, it would be much faster to do it in memory.
The first time you need to pick a random pending item for a given user, select all of the user's pending items from the database and store them in the Rails cache. (This only works if there's a reasonable number of pending items per user.)
Each time you need to pick a random pending item for a given user, get the full list from the cache and pick a random member with .sample or whatever.
Here's the tricky part: to keep the cache consistent, every time you do anything that could change a user's full list of pending items (including something like adding a new flag type), you'll need to invalidate the cache entry.
This is a lot of effort, so you really have to want to do it.
Regarding avoiding repeats, the only way to do that reliably is to store the last pending item displayed and exclude it from your query
def pending_item
#pending_items = UserItem.
joins("LEFT OUTER JOIN flags ON flags.item_id = items.id").
where("items.user_id != ?", current_user.id).
where("flags.id is null").
where("items.id != ?", previous_shown_item_id)
#pending_item = #pending_badges.offset(rand #pending_badges.count).first
end
or, if you do the random selection in memory, exclude the last shown pending item when you do that.

MS Access manual Auto incrementing field

Im building a system for my company to keep track of internal orders, inbetween our warehouses, we have material that goes out warehouse 1 to warehouse 2 and we kind of lose track of how much of "x" is in warehouse 1 and how much in warehouse 2, so i want to implement this access db where a user fills a form and says: order 1: 500 of "x" order 2: 300 of "y". then another user fills an exit form where he says 1 of "x" going out, so i would need the program to keep track of total order and how much as gone out to fill order 1 and so on...
My idea here is to have both an order number and an id number for each of "x" everytime someoneone assembles 1 "x" they fill the form and print a label directly from the access (i have this part working already) while keeping a record of when it was assembled, who verified and what was verified (it will work as a quality control also).
What i dont know is how to program the db so when it reaches 500 of "x", the id number for "x" starts again from 1
This is the one major issue with my program right now, i'm not experienced in access db's or vba, but im getting there with a tip and a trick from here and there, so, no need to be careful with the technical language, i will google it if i have to :p
EDIT:
The table structure goes as follows:
1 table as the main table where I record the check that is made for every product, where I include the model of the product, the said ID that I want to reset after a number of products checked, and a concatenated field that includes most of this information to generate a qr code.
Then there is a table for the Order Number, which is connected to a form to record each new order with a date/time field, the order number itself and the number of products. This number of products must then be called from the code that will count how many products have been checked to date and keep the order number field updated so we can keep track of the order.
Then there is another minor table just to get values for the form, the product models
Thank you for your answers ;)
See this MSDN Documentation
Unfortunately in Access, you cannot 'reset' an ID field, unless you move the records to a newly created table and use that table for every 500 records.
As for the user control and login form, I'm afraid those are separate questions that must be asked in a different thread.
To get you started:
You can set the RecordSource of a form to a table, and when users make entries, the data will be saved to the table. You can also use a form with controls (text boxes, comboboxes, etc.) and create a button that runs a query to insert these records into a table.
The login piece - you can encrypt the database with a password. That may/may not be sufficient.
I would suggest you change your schema, if possible. Something like the following:
Orders
OrderID (Autonumber)
ProductID (link to your Products table)
QuantityRequested
Deliverables
DeliverableID (Autonumber)
OrderID (link to your Orders table)
SequenceNumber: in the BeforeInsert event set this value equal to:
DCount("*", "Deliverables", "OrderID=" & Me.OrderID) + 1
I'm assuming that your form has a control named OrderID that is bound to the OrderID field of the Deliverables table.
The code uses the DCount() function to get the count of all the other deliverables that have already been created for this order. If this is the first deliverable, DCount() will return 0. It then adds 1 to this count to get the sequence number of the next deliverable.
If the new SequenceNumber is greater than the quantity requested, you could display a message saying that the order has been filled and cancel the creation of the Deliverable record.
This is just one approach and it is not a complete solution. I'm assuming that once assigned a sequence number a deliverable cannot be deleted. You might need to make allowances for deliverables that get lost or damaged. You could incorporate a status field to the Deliverable table to deal with this, but you would still need to make a decision about what to do with the SequenceNumber.

How to fetch data for a news feed like system?

I have few tables as shown below
Polls
PollId Question Option
1 What 1
2 Why 4
Updates
UpdateId Text
1 Sleep
2 Play
Polls and updates are just two sample tables (In reality there are more tables like ,photos, videos,links etc). But when a user visit his home (like facebook new feed) he must be displayed with data relevant to him (no such data included in this example). ie I want to select data from all tables with less number of query executions. (ie, I want to present a mixture of datas, ie polls, photos, videos etc )
Currently, I'm fetching only ids and type (ie which table) from all of the tables and gather further data while iterating through this resultset. (ie from c# calling another SqlQuery) .
Is there a way to query the data from whole tables at once? (OUTER JOIN?, UNION?)
Or simply,
How can I select different type of entities at once in a single sql Query?
You could write your query so that you have one long select list for everything you want and it all comes back in one result set but I suspect that wouldn't work too well because you might have varying numbers of different types of items per user.
If you really must have it all in one hit then you can issue multiple queries in one go and get multiple result sets back. To handle this you can use an ADO.Net DataSet. See this SO example (but not the accepted answer - see Vikram Dibyal's answer as that gives a very basic overview of what I think you're asking for).
I won't copy and paste the stuff from the linked thread, just head over and take a look.

Storing a php integer array

I need to store an array of ints. Now my issue is, there's an operation that's done quite a few times so I'd like to limit it to one single query. In tha query, I would need to add an int to a certain int from the array.
It's for a timer of the time spent on a certain page. Currently it's just a general counter that counts for all the pages in the same field, so I only have to do
UPDATE user SET active = active+$totaltime WHERE id=:id
with the $totaltime being the time difference between last check and then. Now I'd like to store for certain pages seperately. The problem is I don't know exactly how many pages there will be. I thought about using serialize, but then I'd need to do 2 queries a lot of times which doesn't seem like a good solution.
Are there any other methods to do so?
What you need is a separate table for the levels which keeps track of active time associated with each user on each level.
Lets calls this table userlevels, and give it the following columns:
userid INT
levelid INT
active INT
The primary key should be a combination of the userid and leveid columns, since there can only be one entry for a particular combination of user and level.
Then when you want to update the amount of time a user has spent on a certain level, you would do something like:
INSERT INTO userlevels (userid,levelid,active)
VALUES (:userid,:levelid,$totaltime)
ON DUPLICATE KEY UPDATE active=active+$totaltime;
This creates a new entry in the table if the user has never been on that level before, or adds to the active time if there is already an entry.
This is mysql specific syntax, but the same thing can be achieved on other databases with different calls.