0

I'm working on a project where each user has an inventory, which is really just an array of IDs that correspond to actual things in the project.

To store the inventory, I want to use Postgres and just serialize/deserialize data into a string format. However, in this array it is likely that they will have many of a single ID. The IDs are all integers so I'm planning on just joining them with a comma and separating them out during retrieval.

For example, the inventory might be [1, 2, 3, 3, 3, 4], but it would be best not to store it like 1,2,3,3,3,4 with a long repeating list.

Is there an efficient way to store duplicate items?

3
  • If you are storing the data is String format why not convert it to JSON which is supported by the latest Postgres DB?
    – Nishant
    Commented Dec 17, 2017 at 17:36
  • Oh, didn't know that existed. Well, even if I'm storing it as a JSON array, I'd still like a way to compress it. I think I've got a solution, will post it as answer.
    – notme1560
    Commented Dec 17, 2017 at 17:48
  • 2
    PostgreSQL also supports array columns so you could use an int[] column. Or just use a separate table so that you can have proper referential integrity in your database. Also, how huge are these arrays and how many duplicates do they have that you think this sort of optimization is necessary? Commented Dec 17, 2017 at 18:04

2 Answers 2

1

"Actual things in the project" should be another table in the database. The correct relational approach is to have a junction table:

create table userItems as (
    userItemId serial primary key,
    userId int references users(userId),
    itemId int references items(itemId)
);

You can then add additional information -- such as quantity, price, date when added, and so on.

There are some circumstances where an array would be more appropriate. However, for run-of-the-mill situations where you have users and items, a junction table would be the first approach and most likely to solve your problem.

1
  • The problem with this is that the "Actual things in the project" aren't in the database. I have some functions that convert the IDs into meaningful data for the application, so storing the items on the database wouldn't make sense.
    – notme1560
    Commented Dec 17, 2017 at 19:51
0

Thanks to Nishant I realized I can store the array in the JSON format instead. With this I can do the compression like this (using the original input):

{
    "1": 1,
    "2": 1,
    "3": 3,
    "4": 1
}

Which will allow me to just store a count of each element in the JSON.

EDIT: Here's the code.

function(array) {
    output = {};
    array.forEach((x) => {
        output[x] = (output[x] || 0) + 1
    });
    return output;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.