Storing player inventory

Storing player inventory

I have a simple game with every user having an inventory. Inventory is nothing but a list of items. Ex [“item1”, “item2”] etc…
I don’t have any data specific to an inventory item. My usecase is to just ensure that the player owns the item with the given id.

There are 2 ways to store this in storage

  1. Store the list as a single entry. (ex. CollectionName=“Inventory”, CollectionKey=“Inventory”, value="{“inventory”: [“item1”, “item2”]}.
  2. Store using different collection keys.
    (ex. CollectionName=“Inventory”, CollectionKey=“item1”, value="{}")

The advantage of the 1st approach is that if I need to get the entire inventory there is only one database read performed on a single key.
But if there are 1000s of items in inventory and if I need to see if an item is owned I would need to fetch everything.

In the second approach its easy to check if a user owns a particular item. I had seen this being suggested in a different forum post.

My concern is that if I need to fetch the complete inventory of a player I need to do a StorageList on “inventory” collection. Is this operation database heavy? I understand that the db is indexed with userid, collection name and key. However the database would have to read say 1000 records from different parts of the disk.

Is it better to use option 1 if I don’t have to store any data for each item in inventory?

Hello @geopaulm.

The approach 1 is the recommend one and as you said it may become a problem when having to deserialise a lot of data. When you reach such bottleneck, you can rely on custom queries to optimize the data search and retrieval.

A additional note on how do structure the data, ideally you should define your data model to facilitate most database access patterns, so if you need to access the items individually you could use an object indexed by the item_id (I’m assuming this field is truly unique) instead of an array that you need to iterate all the time to fetch one element.

@flavio I did not quite understand what you mentioned.

“A additional note on how do structure the data, ideally you should define your data model to facilitate most database access patterns, so if you need to access the items individually you could use an object indexed by the item_id (I’m assuming this field is truly unique) instead of an array that you need to iterate all the time to fetch one element.”
This denotes that ideally, I should be using 2, if I need to optimize for lookups.
But my usecase is frequent lookups and frequent fetch of the entire inventory

Sorry for the confusion. To be more precise I’m hinting you to model it like this:

{
  “inventory”: { // object instead of a array []
    “item1”: <whatever-you-need-here>,
    “item2": <whatever-you-need-here>
  }
}

Using an array would make you iterate over every entry to find if it’s present which is O(n), while an object/dictionary allows you to do it in O(1).

1 Like