问题
I need to store information per object in MongoDB. Each object can have a variable number of attributes, each attribute name may also be different.
Object 1:
- name : "Cupboard Number 1"
- type: "Cupboard"
- material : "Wood"
- dimensions : "12X15"
- built on : "2nd oct 2014"
- id : 12212
Object 2:
- name : "Tommy"
- type : "Pet"
- owner : "Tom"
- born : "1 June 2010"
- id : 12321
So each object may have different attributes/fields. I'd like to have the flexibility to query on this database by filtering on any combination of attributes. Since the database can be enormous, I'd like data retrieval to be fast, for which I'd want some kind of indexing to be possible which expedites the query.
The example query may be:
- Search all records which have material = "Wood" and type = "Table"
- Search all records which have type = "Dog" and owner = "Harry"
I was thinking of using a collection where all the attributes can fit into one object, but cannot see how indexing would be possible. I can obviously break down the object into individual attribute objects and then store it which would mean having something like this:
Object 1 has multiple individual objects:
- { "attr_name" : "name", "attr_value" : "Cupboard Number 1", "id" : 12212 }
- { "attr_name" : "type", "attr_value" : "Cupboard", "id" : 12212 }
- { "attr_name" : "material", "attr_value" : "Wood", "id" : 12212 }
- { "attr_name" : "dimensions", "attr_value" : "12X15", "id" : 12212 }
- { "attr_name" : "built on", "attr_value" : "2nd oct 2014", "id" : 12212 }
Now I can create index on attr_name and get 'id', which I can use to gather all the records for that object. However, this would not work beyond one attribute, while my requirement is to filter for several attributes in one query.
I would want to some how structure the entire object (without breaking it down as here) and still be able to create the indexes. Any clues how that may be done? How should problems like these be solved? Is there any NOSQL / other means to solve such problems? I am open to using another Database also if that serves this somehow.
回答1:
MongoDB has a reference architecture post for a retail implementation which mirrors the issue which you are trying to solve. It also talks about indexing and displaying a faceted search based on querying variant attributes. I guess you would find highly relevant information there and a good starting point to tackle your problem:
https://www.mongodb.com/blog/post/retail-reference-architecture-part-1-building-flexible-searchable-low-latency-product
来源:https://stackoverflow.com/questions/31510371/indexing-on-several-fields-in-mongodb