零售行业下MongoDB在产品目录系统、库存系统、个性推荐系统中的应用【转载】
retail reference architecture part 1: building a flexible, searchable, low-latency product catalog
product catalog data management is a complex problem for retailers today. after years of relying on multiple monolithic, vendor-provided systems, retailers are now reconsidering their options and looking to the future.
in today’s vendor-provided systems, product data must frequently be moved back and forth using etl processes to ensure all systems are operating on the same data set. this approach is slow, error prone, and expensive in terms of development and management. in response, retailers are now making data services available individually as part of a centralized service-oriented architecture (soa).
this is a pattern that we commonly see at mongodb, so much so that we’ve begun to define some best practices and reference architecture specifically targeted at the retail space. as part of that effort, today we’ll be taking a look at implementing a catalog service using mongodb as the first of a three part series on retail architecture.
why mongodb?
many different database types are able to fulfill our product catalog use case, so why choose mongodb?
-
document flexibility: each mongodb document can store data represented as rich json structures. this makes mongodb ideal for storing just about anything, including very large catalogs with thousands of variants per item.
-
dynamic schema: json structures within each document can be altered at any time, allowing for increased agility and easy restructuring of data when needs change. in mongodb, these multiple schemas can be stored within a single collection and can use shared indexes, allowing for efficient searching of both old and new formats simultaneously.
-
expressive query language: the ability to perform queries across many document attributes simplifies many tasks. this can also improve application performance by lowering the required number of database requests.
-
indexing: powerful secondary, compound and geo-indexing options are available in mongodb right out of the box, quickly enabling features like sorting and location-based queries.
-
data consistency: by default, all reads and writes are sent to the primary member of a mongodb replica set. this ensures strong consistency, an important feature for retailers, who may have many customers making requests against the same item inventory.
-
geo-distributed replicas: network latency due to geographic distance between a data source and the client can be problematic, particularly for a catalog service which would be expected to sustain a large number of low-latency reads. mongodb replica sets can be geo-distributed, so that they are close to users for fast access, mitigating the need for cdns in many cases.
these are just a few of the characteristics of mongodb that make it a great option for retailers. next, we’ll take a look at some of the specifics of how we put some of these to use in our retail reference architecture to support a number of features, including:
- searching for items and item variants
- retrieving per store pricing for items
- enabling catalog browsing with faceted search
item data model
the first thing we need to consider is the data model for our items. in the following examples we are showing only the most important information about each item, such as category, brand and description:
{ “_id”: “30671”, //main item id “department”: “shoes”, “category”: “shoes/women/pumps”, “brand”: “calvin klein”, “thumbnail”: “http://cdn.../pump.jpg”, “title”: “evening platform pumps”, “description”: “perfect for a casual night out or a formal event.”, “style”: “designer”, … }
this type of simple data model allows us to easily query for items based on the most demanded criteria. for example, using db.collection.findone
, which will return a single document that satisfies a query:
-
get item by id
db.definition.findone({_id:”301671”})
-
get items for a set of product ids
db.definition.findone({_id:{$in:[”301671”,”452318”]}})
-
get items by category prefix
db.definition.findone({category:/^shoes\/women/})
notice how the second and third queries used the $in
operator and a regular expression, respectively. when performed on properly indexed documents, mongodb is able to provide high throughput and low latency for these types of queries.
variant data model
another important consideration for our the product catalog is item variants, such as available sizes, colors, and styles. our item data model above only captures a small amount of the data about each catalog item. so what about all of the available item variations we may need to retrieve, such as size and color?
one option is to store an item and all its variants together in a single document. this approach has the advantage of being able to retrieve an item and all variants in a single query. however, it is not the best approach in all cases. it is an important best practice to avoid unbounded document growth. if the number of variants and their associated data is small, it may make sense to store them in the item document.
another option is to create a separate variant data model that can be referenced relative to the primary item:
{ “_id”: ”93284847362823”, //variant sku “itemid”: “30671”, //references the main item “size”: 6.0, “color”: “red” … }
this data model allows us to do fast lookups of specific item variants by their sku number:
db.variation.find({_id:”93284847362823”})
as well as all variants for a specific item by querying on the itemid
attribute:
db.variation.find({itemid:”30671”}).sort({_id:1})
in this way, we maintain fast queries on both our primary item for displaying in our catalog, as well as every variant for when the user requests a more specific product view. we also ensure a predictable size for the item and variant documents.
per store pricing
another consideration when defining the reference architecture for our product catalog is pricing. we’ve now seen a few ways that the data model for our items can be structured to quickly retrieve items directly or based on specific attributes. prices can vary by many factors, like store location. we need a way to quickly retrieve the specific price of any given item or item variant. this can be very problematic for large retailers, since a catalog with a million items and one thousand stores means we must query across a collection of a billion documents to find the price of any given item.
we could, of course, store the price for each variant as a nested document within the item document, but a better solution is to again take advantage of how quickly mongodb is able to query on _id
. for example, if each item in our catalog is referenced by an itemid, while each variant is referenced by a sku number, we can set the _id
of each document to be a concatenation of the itemid or sku and the storeid associated with that price variant. using this model, the _id
for the pair of pumps and its red variant described above would look something like this:
- item:
30671_store23
- variant:
93284847362823_store23
this approach also provides a lot of flexibility for handling pricing, as it allows us to price items at the item or the variant level. we can then query for all prices or just the price for a particular location:
- all prices:
db.prices.find({_id:/^30671/})
- store price:
db.prices.find({_id:/^30671_store23/})
we could even add other combinations, such as pricing per store group, and get all possible prices for an item with a single query by using the $in
operator:
db.prices.find({_id:{$in:[ “30671_store23”, “30671_sgroup12”, “93284847362823_store23”, “93284847362823_sgroup12” ]}})
browse and search products
the biggest challenge for our product catalog is to enable browsing with faceted search. while many users will want to search our product catalog for a specific item or criteria they are looking for, many others will want to browse, then narrow the returned results by any number of attributes. so given the need to create a page like this:
we have many challenges:
- response time: as the user browses, each page of results should return in milliseconds.
- multiple attributes: as the user selects different facets—e.g. brand, size, color—new queries must be run on multiple document attributes.
- variant-level attributes: some user-selected attributes will be queried at the item level, such as brand, while others will be at the variant level, such as size.
- multiple variants: thousands of variants can exist for each item, but we only want to display each item once, so results must be de-duplicated.
- sorting: the user needs to be allowed to sort on multiple attributes, like price and size, and that sorting operation must perform efficiently.
- pagination: only a small number of results should be returned per page, which requires deterministic ordering.
many retailers may want to use a dedicated search engine as the basis of these features. mongodb provides an open source connector project, which allows the use of apache solr and elasticsearch with mongodb. for our reference architecture, however, we wanted to implement faceted search entirely within mongodb.
to accomplish this, we create another collection that stores what we will call summary documents. these documents contain all of the information we need to do fast lookups of items in our catalog based on various search facets.
{ “_id”: “30671”, “title”: “evening platform pumps”, “department”: “shoes”, “category”: “women/shoes/pumps”, “price”: 149.95, “attrs”: [“brand”: “calvin klein”, …], “sattrs”: [“style”: ”designer”, …], “vars”: [ { “sku”: “93284847362823”, “attrs”: [{“size”: 6.0}, {“color”: “red”}, …], “sattrs”: [{“width”: 8.0}, {“heelheight”: 5.0}, …], }, … //many more skus ] <p>}
note that in this data model we are defining attributes and secondary attributes. while a user may want to be able to search on many different attributes of an item or item variant, there is only a core set that are most frequently used. for example, given a pair of shoes, it may be more common for a user to filter their search based on available size than filtering by heel height. by using both the attr
and sattr
attributes in our data model, we are able to make all of these item attributes available to search, but incur only the expense of indexing the most used attributes by indexing only attr
.
using this data model, we would create compound indices on the following combinations:
- department + attr + category + _id
- department + vars.attr + category + _id
- department + category + _id
- department + price + _id
- department + rating + _id
in these indices, we always start with department, and we assume users will chose the department to refine their search results. for a catalog without departments, we could have just as easily begun with another common facet like category or type. we can then perform the queries needed for faceted search and quickly return the results to the page:
-
get summary from itemid
db.variation.find({_id:”30671”})
-
get summary of specific item variant
db.variation.find({vars.sku:”93284847362823”},{“vars.$”:1})
-
get summaries for all items by department
db.variation.find({department:”shoes”})
-
get summaries with a mix of parameters
db.variation.find({ “department”:”shoes”,
“vars.attr”: {“color”:”red”},
“category”: “^/shoes/women”})
recap
we’ve looked at some best practices for modeling and indexing data for a product catalog that supports a variety of application features, including item and item variant lookup, store pricing, and catalog browsing using faceted search. using these approaches as a starting point can help you find the best design for your own implementation.
learn more
to discover how you can re-imagine the retail experience with mongodb, read our white paper. in this paper, you'll learn about the new retail challenges and how mongodb addresses them.
转载于 《》
retail reference architecture part 2: approaches to inventory optimization
in part one of our series on retail reference architecture we looked at some best practices for how a high-volume retailer might use mongodb as the persistence layer for a large product catalog. this involved index, schema, and query optimization to ensure our catalog could support features like search, per-store pricing and browsing with faceted search in a highly performant manner. over the next two posts we will be looking at approaches to similar types of optimization, but applied to an entirely different aspect of retail business, inventory.
a solid central inventory system that is accessible across a retailer’s stores and applications is a large part of the foundation needed for improving and enriching the customer experience. here are just a few of the features that a retailer might want to enable:
- reliably check real-time product availability.
- give the option for in-store pick-up at a particular location.
- detect the need for intra-day replenishment if there is a run on an item.
the problem with inventory systems
these are features that seem basic but they present real challenges given the types of legacy inventory systems commonly used by major retailers. in these systems, individual stores keep their own field inventories, which then report data back to the central rdbms at a set time interval, usually nightly. that rdbms then reconciles and categorizes all of the data received that day and makes it available for operations like analytics, reporting, as well as consumption by external and internal applications. commonly there is also a caching layer present between the rdbms and any applications, as relational databases are often not well-suited to the transaction volume required by such clients, particularly if we are talking about a consumer-facing mobile or web app.
so the problem with the status quo is pretty clear. the basic setup of these systems isn’t suited to providing a continually accurate snapshot of how much inventory we have and where that inventory is located. in addition, we also have the increased complexity involved in maintaining multiple systems, i.e. caching, persistence, etc. mongodb, however, is ideal for supporting these features with a high degree of accuracy and availability, even if our individual retail stores are very geographically dispersed.
design principles
to begin, we determined that the inventory system in our retail reference architecture needed to do the following:
- provide a single view of inventory, accessible by any client at any time.
- be usable by any system that needs inventory data.
- handle a high-volume, read-dominated workload, i.e. inventory checks.
- handle a high volume of real-time writes, i.e. inventory updates.
- support bulk writes to refresh the system of record.
- be geographically distributed.
- remain horizontally scalable as the number of stores or items in inventory grows.
in short, what we needed was to build a high performance, horizontally scalable system where stores and clients over a large geographic area could transact in real-time with mongodb to view and update inventory.
stores schema
since a primary requirement of our use case was to maintain a centralized, real-time view of total inventory per store, we first needed to create the schema for a stores collection so that we had locations to associate our inventory with. the result is a fairly straightforward document per store:
{ “_id”:objectid(“78s89453d8chw28h428f2423”), “classname”:”catalog.store”, “storeid”:”store100”, “name”:”bessemer store”, “address”:{ “addr1”:”1 main st.”, “city”:”bessemer”, “state”:”al”, “zip”:”12345”, “country”:”usa” }, “location”:[-86.95444, 33.40178], … }
we then created the following indices to optimize the most common types of reads on our store data:
-
{“storeid”:1},{“unique”:true}
: get inventory for a specific store. -
{“name”:1}
: get a store by name. -
{“address.zip”:1}
: get all stores within a zip code, i.e. store locator. -
{“location”: 2dsphere}
: get all stores around a specified geolocation.
of these, the location index is especially useful for our purposes, as it allows us to query stores by proximity to a location, e.g. a user looking for the nearest store with a product in stock. to take advantage of this in a sharded environment, we used a geonear command that retrieves the documents whose ‘location’ attribute is within a specified distance of a given point, sorted nearest first:
db.runcommand({ geonear:“stores”, near:{ type:”point”, coordinates:[-82.8006,40.0908], //geojson or coordinate pair maxdistance:10000.0, //in meters spherical:true //required for 2dsphere indexes } })
this schema gave us the ability to locate our objects, but the much bigger challenge was tracking and managing the inventory in those stores.
inventory data model
now that we had stores to associate our items with, we needed to create an inventory collection to track the actual inventory count of each item and all its variants. some trade-offs were required for this, however. to both minimize the number of roundtrips to the database, as well as mitigate application-level joins, we decided to duplicate data from the stores collection into the inventory collection. the document we came up with looked like this:
{ “_id”:”902372093572409542jbf42r2f2432”, “storeid”:”store100”, “location”:[-86.95444, 33.40178], “productid”:”20034”, “vars”:[ {“sku”:”sku1”, “quantity”:”5”}, {“sku”:”sku2”, “quantity”:”23”}, {“sku”:”sku3”, “quantity”:”2”}, … ] }
notice first that we included both the ‘storeid’ and ‘location’ attribute in our inventory document. clearly the ‘storeid’ is necessary so that we know which store has what items, but what happens when we are querying for inventory near the user? both the inventory data and store location data are required to complete the request. by adding geolocation data to the inventory document we eliminate the need to execute a separate query to the stores collection, as well as a join between the stores and inventory collections.
for our schema we also decided to represent inventory in our documents at the productid level. as was noted in part one of our retail reference architecture series, each product can have many, even thousands of variants, based on size, color, style, etc., and all these variants must be represented in our inventory. so the question is should we favor larger documents that contain a potentially large variants collection, or many more documents that represent inventory at the variant level? in this case, we favored larger documents to minimize the amount of data duplication, as well as decrease the total number of documents in our inventory collection that would need to be queried or updated.
next, we created our indices:
-
{storeid:1}
: get all items in inventory for a specific store. -
{productid:1},{storeid:1}
: get inventory of a product for a specific store. -
{productid:1},{location:”2dsphere”}
: get all inventory of a product within a specific distance.
it’s worth pointing out here that we chose not to include an index with ‘vars.sku’. the reason for this is that it wouldn’t actually buy us very much, since we are already able to do look ups in our inventory based on ‘productid’. so, for example, a query to get a specific variant sku that looks like this:
db.inventory.find( { “storeid”:”store100”, “productid”:“20034”, “vars.sku”:”sku11736” }, {“vars.$”:1} )
doesn’t actually benefit much from an added index on ‘vars.sku’. in this case, our index on ‘productid’ is already giving us access to the document, so an index on the variant is unnecessary. in addition, because the variants array can have thousands of entries, an index on it could potentially take up a large block in memory, and consequently decrease the number of documents stored in memory, meaning slower queries. all things considered, an unacceptable trade-off, given our goals.
so what makes this schema so good anyhow? we’ll take a look in our next post at some of the features this approach makes available to our inventory system.
learn more
to discover how you can re-imagine the retail experience with mongodb, read our white paper. in this paper, you'll learn about the new retail challenges and how mongodb addresses them.
转载于 《》
retail reference architecture part 3: query optimization and scaling
in part one of this series on reference architectures for retail, we discussed how to use mongodb as the persistence layer for a large product catalog. in part two, we covered the schema and data model for an inventory system. today we’ll cover how to query and update inventory, plus how to scale the system.
inventory updates and aggregations
at the end of the day, a good inventory system needs to be more than just a system of record for retrieving static data. we also need to be able to perform operations against our inventory, including updates when inventory changes, and aggregations to get a complete view of what inventory is available and where.
the first of these operations, updating the inventory, is both pretty straightforward and nearly as performant as a standard query, meaning our inventory system will be able to handle the high-volume we would expect to receive. to do this with mongodb we simply retrieve an item by its ‘productid’, then execute an in-place update on the variant we want to update using the $inc
operator:
db.inventory.update( { “storeid”:”store100”, “productid”:“20034”, “vars.sku”:”sku11736” }, {“$inc”:{“vars.$.q”:20}} )
for aggregations of our inventory, the aggregation pipeline framework in mongodb gives us many valuable views of our data beyond simple per-store inventory by allowing us to take a set of results and apply multi-stage transformations. for example, let’s say we want to find out how much inventory we have for all variants of a product across all stores. to get this we could create an aggregation request like this:
db.inventory.aggregate([ {$match:{productid:”20034”}, {$unwind:”$vars”}, {$group:{ _id:”$result”, count:{$sum:”$vars.q”}}}])
here, we are retrieving the inventory for a specific product from all stores, then using the $unwind
operator to expand our variants array into a set of documents, which are then grouped and summed. this gives us a total inventory count for each variant that looks like this:
{“_id”: “result”, “count”: 101752}
alternatively, we could have also matched on ‘storeid’ rather than ‘productid’ to get the inventory of all variants for a particular store.
thanks to the aggregation pipeline framework, we are able to apply many different operations on our inventory data to make it more consumable for things like reports and gain real insights into the information available. pretty awesome?
but wait, there’s more!
location-based inventory queries
so far we’ve primarily looked at what retailers can get out of our inventory system from a business perspective, such as tracking and updating inventory, and generating reports, but one of the most notable strengths of this setup is the ability to power valuable customer-facing features.
when we began architecting this part of our retail reference architecture, we knew that our inventory would also need to do more than just give an accurate snapshot of inventory levels at any given time, it would also need to support the type of location-based querying that has become expected in consumer mobile and web apps.
luckily, this is not a problem for our inventory system. since we decided to duplicate the geolocation data from our stores collection into our inventory collection, we can very easily retrieve inventory relative to user location. returning to the geonear
command that we used earlier to retrieve nearby stores, all we need to do is add a simple query to return real-time information to the consumer, such as the available inventory of a specific item at all the stores near them:
db.runcommand({ geonear:”inventory”, near:{ type:”point”, coordinates:[-82.8006,40.0908]}, maxdistance:10000, spherical:true, limit:10, query:{“productid”:”20034”, “vars.sku”:”sku1736”}})
or the 10 closest stores that have the item they are looking for in-stock:
db.runcommand({ geonear:”inventory”, near:{ type:”point”, coordinates:[-82.8006,40.0908]}, maxdistance:10000, spherical:true, limit:10, query:{“productid”:”20034”, “vars”:{ $elemmatch:{”sku1736”, //returns only documents with this sku in the vars array quantity:{$gt:0}}}}}) //quantity greater than 0
since we indexed the ‘location’ attribute of our inventory documents, these queries are also very performant, a necessity if the system is supporting the type of high-volume traffic commonly generated by consumer apps, while also supporting all the transactions from our business use case.
deployment topology
at this point, it’s time to celebrate, right? we’ve built a great, performant inventory system that supports a variety of queries, as well as updates and aggregations. all done!
not so fast.
this inventory system has to support the needs of a large retailer. that means it has to not only be performant for local reads and writes, it must also support requests spread over a large geographic area. this brings us to the topic of deployment topology.
datacenter deployment
we chose to deploy our inventory system across three datacenters, one each in the west, central and east regions of the u.s. we then sharded our data based on the same regions, so that all stores within a given region would execute transactions against a single local shard, minimizing any latency across the wire. and lastly, to ensure that all transactions, even those against inventory in other regions, were executed against the local datacenter, we replicated each all three shards in each datacenters.
since we are using replication, there is the issue of eventual consistency should a user in one region need to retrieve data about inventory in another region, but assuming a good data connection between datacenters and low replication-lag, this is minimal and worth the trade-off for the decrease in request latency, when compared to making requests across regions.
shard key
of course, when designing any sharded system we also need to carefully consider what shard key to use. in this case, we chose {storeid:1},{productid:1}
for two reasons. the first was that using the ‘storeid’ ensured all the inventory for each store was written to the same shard. the second was cardinality. using ’storeid’ alone would have been problematic, since even if we had hundreds of stores, we would be using a shard key with relatively low cardinality, a definite problem that could lead to an unbalanced cluster if we are dealing with an inventory of hundreds of millions or even billions of items. the solution was to also include ‘productid’ in our shard key, which gives us the cardinality we need, should our inventory grow to a size where multiple shards are needed per region.
shard tags
the last step in setting up our topology was ensuring that requests were sent to the appropriate shard in the local datacenter. to do this, we took advantage of tag-aware sharding in mongodb, which associates a range of shard key values with a specific shard or group of shards. to start, we created a tag for the primary shard in each region:
- sh.addshardtag(“shard001”,”west”) - sh.addshardtag(“shard002”,”central”) - sh.addshardtag(“shard003”,”east”)
then assigned each of those tags to a range of stores in the same region:
- sh.addtagrange(“inventorydb.inventory”),{storeid:0},{storeid:100},”west”) - sh.addtagrange(“inventorydb.inventory”),{storeid:100},{storeid:200},”central”) - sh.addtagrange(“inventorydb.inventory”),{storeid:200},{storeid:300},”east”)
in a real-world situation, stores would probably not fall so neatly into ranges for each region, but since we can assign whichever stores we want to any given tag, down to the level of assigning a single storeid to a tag, it allows the flexibility to accommodate our needs even if storeids are more discontinuous. here we are simply assigning by range for the sake of simplicity in our reference architecture.
recap
overall, the process of creating our inventory system was pretty simple, requiring relatively few steps to implement. the more important takeaway than the finished system itself is the process we used to design it. in mongodb, careful attention to schema design, indexing and sharding are critical for building and deploying a setup that meets your use case, while ensuring low latency and high performance, and as you can see, mongodb offers a lot of tools for accomplishing this.
up next in the final part of our retail reference architecture series: scalable insights, including recommendations and personalization!
learn more
to discover how you can re-imagine the retail experience with mongodb, read our white paper. in this paper, you'll learn about the new retail challenges and how mongodb addresses them.
转载于《》
retail reference architecture part 4: recommendations and personalizations
in the first three parts of our series on retail reference architecture, we focused on two practical applications of mongodb in the retail space: product catalogs and inventory systems. both of these are fairly conventional use cases where mongodb acts as a system of record for a relatively static and straightforward collection of data. for example, in part one of our series where we focused on the product catalog, we used mongodb to store and retrieve an inventory of items and their variants.
today we’ll be looking at a very different application of mongodb in the retail space, one that even those familiar with mongodb might not think it is well suited for: logging a high volume of user activity data and performing data analytics. this final use case demonstrates how mongodb can enable scalable insights, including recommendations and personalization for your customers.
activity logging
in retail, maintaining a record of each user’s activities gives a company the means to gain valuable predictive insight into user behavior, but it comes at a cost. for a retailer with hundreds of thousands or millions of customers, logging all of the activities generated by our customer base creates a huge amount of data, and storing that data in a useful and accessible way becomes a challenging task. the reason for this is that just about every activity performed by a user can be of interest to us, such as:
- search
- product views, likes or wishes
- shopping cart add/remove
- social network sharing
- ad impressions
even from this short list, it’s easy to see how the amount of data generated can quickly become problematic, both in terms of the cost/volume of storage needed, and a company’s ability to utilize the data in a meaningful way. after all, we’re talking about potentially hundreds of thousands of writes per second, which means to gain any insights from our data set we are effectively trying to drink from the fire hose. the potential benefits, however, are huge.
with this type of data a retailer can gain a wealth of knowledge that will help predict user actions and preferences for the purposes of upselling and cross-selling. in short, the better any retailer can predict what their users want, the more effectively they can drive a consumer to additional products they may want to purchase.
requirements
for mongodb to meet the needs of our use case, we need it to handle the following requirements:
ingestion of hundreds of thousands of writes per second: normally mongodb performs random access writes. in our use case this could lead to an unacceptable amount of disk fragmentation, so we used hvdf (more on this in a later) to store the data sequentially in an append-only fashion.
flexible schema: to minimize the amount of storage space required, the schema of each activity being logged is stored in the same format and size as it is received.
fast querying and sorting on varied fields: secondary btree indexes ensure that our most common lookups and sorts will be performed in milliseconds.
easy deletes of old data: typically, deleting large numbers of documents is a relatively expensive operation in mongodb. by time partitioning our data into collections using hvdf we are able to drop entire collections as a free operation.
data model
as mentioned earlier, one of the requirements of our solution is the use of flexible schemas so that data is stored in the same format it is received; however, we do still need to put some thought into a general data model for each activity being recorded.
the following is an example that outlines some of the attributes we may want to capture across all samples:
{ _id: objectid(), geocode: 1, // used to localize write operations sessionid: “2373bb…", // tracks activities across sessions device: { id: “1234", // tracks activities across different user devices type: "mobile/iphone", useragent: "chrome/34.0.1847.131" } type: "view|cart_add|cart_remove|order|…", // type of activity itemid: “301671", // item that was viewed, added to cart, etc. sku: “730223104376", //item sku order: { id: “12520185", // info about orders associated with the activity … }, location: [ -86.95444, 33.40178 ], //user’s location when the activity was performed tags: [ "smartphone", "iphone", … ], // associated tags timestamp: date("2014/04/01 …”) // time the activity was performed }
this is just one possibility of what an activity might look like. a major concern here is to persist only as much information as is necessary for each activity type to minimize required disk space. as a result, each document will vary depending on the type of activity data being captured.
high volume data feed (hvdf)
hvdf is an open-source framework created by the team at mongodb, which makes it easy to efficiently validate, store, index, query and purge time series data in mongodb via a simple rest api.
in hvdf, incoming data consists of three major components:
- feed: maps to a database. in our use case, we will have one feed per user to capture all of their activities.
- channel: maps to a collection. each channel represents an activity type or source being logged.
- sample: maps to a document. a separate document is written for each user activity being logged.
hvdf allows us to easily use mongodb in an append-only fashion, meaning that our documents will be stored sequentially, minimizing any wasted space when we write to disk. as well, hvdf handles a number of configuration details that make mongodb more efficient for this type of high-volume data storage, including time-based partitioning, and disabling of the default power of 2 sizes disk allocation strategy.
more information and the source code for hvdf are available on github.
time partitioning
in our usage, we take advantage of hvdf’s time slicing feature, which automatically time partitions samples by creating a new collection at a specified time interval. this has four advantages:
-
sequential writes: since a new collection is created for each time interval, samples are always written to disk sequentially.
-
fast deletes: by treating the data as sets, deletes are essentially free. all we need to do is drop the collection.
-
index size: user activity logging creates a huge amount of data. were we to create one collection for all samples per channel our index of of those samples could quickly become huge. by slicing our channels into time intervals, we keep our indexes small enough to fit in ram, meaning queries using those indexes remain very performant.
-
collections optimized for reads: the time interval for each collection can be configured to match the interval we are most likely to want to retrieve. in general, a best practice is to keep time partitions small enough that their indexes will fit in ram, but large enough that you will only need to query across two collections for any given query.
-
automatic sharding: hvdf automatically creates a shard key for each time interval as the collection is created. this ensures any lookups for a given time interval are performant, since samples for the same interval are written to the same shard.
to specify how our data will be time partitioned, we simply pass the following to our channel configuration:
{ "time_slicing" : { "type" : "periodic", "config" : { "period" : {"weeks" : 4} } } }
in this example, we are configuring hvdf to create a new collection per channel every 4 weeks. the ‘period’ may be specified in years, weeks, hours, minutes, seconds, milliseconds or any combination of these.
setting _id
to keep our queries highly performant, we also need to put some thought into the construction of the ‘_id’ for our documents. since we know this data is going to be used primarily for performing time-bounded user analytics, it’s logical to choose an ‘_id’ that embeds both the creation timestamp and the ‘userid’. hvdf makes this very simple. all we need to do is specify that hvdf should use the the ‘source_time_document’ id_type channel plugin in the channel configuration:
"storage" : { "type" : "raw", "config" : { "id_factory" : { "type" : "source_time_document", "config" : { } } } } ``` <p>this will give us an ‘_id’ that looks like this:</p> <pre><code>"_id" : { "source" : "user457", "ts" : numberlong(324000000) } </code></pre> <p>by using this format for ‘_id’, we guarantee near instantaneous queries for many of the most common queries we will need in order to perform analytics on our data.</p> <h2 id="user-insights">user insights</h2> <p>now that we’ve figured out how our user’s activities will be logged in mongodb, it’s time to actually look at what we can do with that data. the first important thing to keep in mind is that, as mentioned earlier, we are trying to drink from the fire hose. capturing this type of user data very often leads to huge data sets, so all of our queries must be time bound. not only does this limit the number of collections that are hit by each query thanks to our time partitioning, it also keeps the amount of data being searched sane. when dealing with terabytes of data, a full table scan isn’t even an option.</p> <h3 id="queries">queries</h3> <p>here are a couple of simple queries we might commonly use to gain some insight into a user’s behavior. these would require secondary indexes on ‘userid’ and ‘itemid’:</p> <ul> <li>recent activity for a user:</li> </ul> <pre><code>db.activity.find({ userid: “u123”, ts: {“$g”t:1301284969946, // time bound the query “$lt”: 1425657300} }) .sort({ time: -1 }).limit(100) // sort in desc order </code></pre> <ul> <li>recent activity for a product:</li> </ul> <pre><code>db.activity.find({ itemid: “301671", // requires a secondary index on timestamp + itemid ts: {“$g”t:1301284969946, “$lt”: 1425657300} }) .sort({ time: -1 }).limit(100)</code></pre> <p>to gain even more insight into what our users are doing, we can also make use of the <a href="http://docs.mongodb.org/manual/aggregation/">aggregation framework</a> in mongodb:</p> <ul> <li>recent number of views, purchases, etc for user</li> </ul> <pre><code>db.activities.aggregate(([ { $match: { userid: "u123", ts: { $gt: date }}}, // get a time bound set of activities for a user { $group: { _id: "$type", count: { $sum: 1 }}}]) // group and sum the results by activity type </code></pre> <ul> <li>recent total sales for a user</li> </ul> <pre><code>db.activities.aggregate(([ { $match: { userid:"u123", ts:{$gt:date}, type:"order"}}, { $group: { _id: "result", count: {$sum: "$total" }}}]) // sum the total of all orders</code></pre> <p>-recent number of views, purchases, etc for item</p> <pre><code>db.activities.aggregate(([ { $match: { itemid: "301671", ts: { $gt: date }}}, { $group: { _id: "$type", count: { $sum: 1 }}}])</code></pre> <p>there are, of course, many different things the results of these queries might tell us about our user’s behaviors. for example, over time, we might see that the same user has viewed the same item multiple times, meaning we might want to suggest that item to them the next time they visit our site. similarly, we may find that a particular item has had a surge in purchases due to a sale or ad campaign, meaning we might want to suggest it to users more frequently to further drive up sales. </p> <p>up-selling is a big possibility here as well. for example, let’s say we know a user has looked at several different low-end cell phones, but that in general their total purchases are relatively high. in this case, we might suggest that they look at a higher-end device that is popular amongst users with similar stats.</p> <h3 id="map-reduce">map-reduce</h3> <p>another option for performing analytics with mongodb is to use <a href="http://docs.mongodb.org/manual/core/map-reduce/">map-reduce</a>. this is often a good choice for very large data sets when compared with the aggregation framework for a few reasons. for example, take the following aggregation that calculates the total number of times an activity has been logged in the past hour for all unique visitors:</p> <pre><code> db.activities.aggregate(([ { $match: { time: { $gt: now-1h } }}, { $group: { _id: "$userid", count: {$sum: 1} } }], { allowdiskuse: 1 })</code></pre> <p>here we have several problems:</p> <ul> <li><p>allowdiskuse: in mongodb, any aggregation that involves a data set greater than 100mb will throw an error, since the aggregation framework is designed to be executed in ram. here, the <code>allowdiskuse</code> property mitigates this issue by forcing the aggregation to be performed on disk, which as you might imagine gets extremely slow for a very large data set.</p> </li> <li><p>single shard final grouping: calculating uniques is hard for any system, but there is a particular aspect of the aggregation framework that can make performance suffer heavily. in a sharded mongodb instance, our aggregation would first be performed per shard. next, the results would be recombined on the primary shard and then the aggregation would be run again to remove any duplication across shards. this can become prohibitively expensive for a very large result set, particularly if the data set is large enough to require disk to be used for the aggregation.</p> </li> </ul> <p>for these reasons, while map-reduce is <a href="http://blog.mongodb.org/post/62900213496/qaing-new-code-with-mms-map-reduce-vs">not always a more performant option</a> than the aggregation framework, it is better for this particular use case. plus, the implementation is quite simple. here’s the same query performed with map-reduce:</p> <pre><code> var map = function() { emit(this.userid, 1); } // emit samples by userid with value of 1 var reduce = function(key, values) { return array.sum(values); } // sum the total samples per user db.activities.mapreduce(map, reduce, { query: { time: { $gt: now-1h } }, // time bound the query to the last hour out: { replace: "lasthouruniques", sharded: true }) // persist the output to a collection</code></pre> <p>from here we can execute queries against the resulting collection:</p> <ul> <li>number activities for a user in the last hour</li> </ul> <pre><code>db.lasthouruniques.find({ userid: "u123" })</code></pre> <ul> <li>total uniques in the last hour</li> </ul> <pre><code>db.lasthouruniques.count()</code></pre> <h3 id="cross-selling">cross-selling</h3> <p>now to put it all together. one of the most valuable features our analytics can enable is the ability to cross-sell products to our users. for example, let’s say a user buys a new iphone. there’s a vast number of related products they might also want to buy, such as cases, screen protectors, headphones, etc. by analyzing our user activity data, we can actually figure out what related items are commonly bought together and present them to the user to drive sales of additional items. here’s how we do it.</p> <p>first, we calculate the items bought by a user:</p> <pre><code> var map = function() { emit(userid, this.itemid); } // emit samples as userid: itemid var reduce = function(key, values) { return values; } // return the array of itemids the user has bought db.activities.mapreduce(map, reduce, { query: { type: “order”, time: { $gt: now-24h }}, // include only activities of type order int he last day out: { replace: "lastdayorders", sharded: true }) // persist the output to a collection</code></pre> <p>this will give an output collection that contains documents that look like this:</p> <pre><code>{ _id: "u123", items: [ 2, 3, 8 ] }</code></pre> <p>next, we run a second map-reduce job on the outputed ‘lastdayorders’ collection to compute the number of occurrences of each item pair:</p> <pre><code> var map = function() { for (i = 0; i < this.items.length; i++) { for (j = i + 1; j <= this.items.length; j++) { emit({a: this.items[i] ,b: this.items[j] }, 1); // emit each item pair } } } var reduce = function(key, values) { return array.sum(values); } // sum all occurrences of each item pair db.lastdayorders.mapreduce(map, reduce, {out: { replace: "pairs", sharded: true }) // persist the output to a collection</code></pre> <p>this will give us an output collection that contains a count of how many times each set of items has been ordered together. the collection will contain documents that look like this:</p> <pre><code>{ _id: { a: 2, b: 3 }, value: 36 }</code></pre> <p>all we need to do from here is to create a secondary index on each item and its count, e.g. <code>{_id.a:”u123”, count:36}</code>. this makes determining which items to cross-sell a matter of a simple query to retrieve the items most commonly ordered together. in the following example, we retrieve only those items that have been ordered with itemid u123 more than 10 times, and sort in descending order: </p> <pre><code>db.pairs.find( { _id.a: "u123", count: { $gt: 10 }} ) .sort({ count: -1 })</code></pre> <p>we can also optionally make the data more compact by grouping the most popular pairs in a separate collection, like this:</p> <pre><code>{ itemid: 2, recom: [ { itemid: 32, weight: 36}, { itemid: 158, weight: 23}, … ] }</code></pre> <h2 id="hadoop-integration">hadoop integration</h2> <p>for many applications, either using the aggregation framework for real-time data analytics, or the map-reduce function for less frequent handling of large data sets in mongodb are great options, but clearly, for complex number crunching of truly massive datasets, <a href="http://hadoop.apache.org">hadoop</a> is going to be the tool of choice. for this reason, we have created a <a href="https://github.com/mongodb/mongo-hadoop">hadoop connector</a> for mongodb that makes processing data from a mongodb cluster in hadoop a much simpler task. here are just a few of the features:</p> <ul> <li>read/write from mongodb or exported bson</li> <li>integration with pig, spark, hive, mapreduce and others</li> <li>works with apache hadoop, cloudera cdh, hortonworks hdp</li> <li>open source</li> <li>support for filtering with mongodb queries, authentication, reading from replica set tags, and more</li> </ul> <p>for more information on the mongodb hadoop connector, check out the project on <a href="https://github.com/mongodb/mongo-hadoop">github</a>.</p> <h2 id="recap">recap</h2> <p>performing user analytics, whether in real-time or incrementally, is no small task. every step of the process from capturing user data, to data storage, to data retrieval, to crunching the numbers present challenges that require significant planning if the system is to perform well. luckily, mongodb and hvdf can be great tools for accomplishing these types of tasks, either on their own or used in conjunction with other tools like hadoop.</p> <p>that’s it for our four part series on retail reference architecture! in just four blog posts we’ve covered how mongodb can be used to power some of the most common and complex needs of large-scale retailers, including <a href="https://www.mongodb.com/blog/post/retail-reference-architecture-part-1-building-flexible-searchable-low-latency-product">product catalogs</a>, <a href="https://www.mongodb.com/blog/post/retail-reference-architecture-part-2-approaches-inventory-optimization">inventory</a>, and <a href="https://www.mongodb.com/blog/post/retail-reference-architecture-part-3-query-optimization-and-scaling">query optimization</a>. for more tools and examples of what mongodb can do for you, check out our <a href="https://github.com/mongodb/">github</a>.</p> <h2 id="learn-more">learn more</h2> <p>to discover how you can re-imagine the retail experience with mongodb, <a href="https://www.mongodb.com/lp/white-paper/serving-the-digitally-oriented-consumer?jmp=blog" target="_blank">read our white paper</a>. in this paper, you'll learn about the new retail challenges and how mongodb addresses them.</p> <p></p><hr> learn more about how leading brands differentiate themselves with technologies and processes that enable the omni-channel retail experience.<p></p> <p></p><center><a class="btn btn-primary" href="https://www.mongodb.com/collateral/serving-digitally-oriented-consumer?jmp=blog" target="_blank">read our guide on the digitally oriented consumer</a></center><p></p> <hr> <p style="float:left; margin-bottom:0px;font-size: 18px;"><strong><a href="https://www.mongodb.com/blog/post/retail-reference-architecture-part-3-query-optimi
上一篇: 第一章 JavaScript简介
下一篇: go 语言学习笔记