I'd like to have a simple, Ontology-style, tagging system for a product database in Google App Engine.

As a basic example, the tags would be pre-defined:

root
--Household
----Bedroom
------Bed
--------Sheets
--------Pillows
----Bathroom
------Bath
------Shower

For product tagged with Sheets, I would expect a search for the Bedroom tag to return that product. And I would want to ensure that when a product is tagged, only valid tags are entered.

What would be the best way to achieve this?

I was thinking something along the lines of:

class HierarchicalTag(ndb.Model):
    name = ndb.StringProperty(required=True)
    parent = ndb.KeyProperty(required=True, kind='HierarchicalTag')

Any help would be greatly appreciated!

有帮助吗?

解决方案

If the hierarchy is only defined once I'd define a dictionary (or structure of your choice) of the hierarchy. When creating a product, I'd save the path of tags against the product.

The model would look something like this:

class Product(ndb.model):
    tags = ndb.StringProperty(repeated=True)
    name = ndb.StringProperty()

e.g. Using your example hierarchy, if saving a pillow I'd include: Household, Bedroom, Bed, Pillows.

Product(tags=['Household', 'Bedroom', 'Bed', 'Pillows'], name='Best pillow case')

Querying is then easy for any level in the hierarchy. e.g. querying bed products:

qry = Product.query(Product.tags=='Bed')

Or querying only for pillows:

qry = Product.query(Product.tags=='Pillows')
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top