{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# mParticle Real Time Data + Personalize - Lab 6 (optional)\n", "\n", "In this module you are going to be adding the ability to maintain a real-time dataset that represents the latest user behavior for users of the Retail Demo Store. You will then connect that dataset to the Personalize dataset groups that you built in Labs 1-4 of the workshop. This will enable your Personalize models to be kept up to date with the latest events your users are performing.\n", "\n", "This workshop will use the mParticle web sdk npm library (https://github.com/mParticle/mparticle-web-sdk) to collect real-time data from the Retail Demo Store, and then feed that event data into the mParticle platform, where it can be routed directly to a Personalize Event Tracker, and then used to maintain the latest behavioral data for your personalization user-item interaction data.\n", "\n", "*Recommended Time: 45 Minutes*\n", "\n", "## Prerequisites\n", "In order to complete this workshop, you will need to complete Labs 1 through 4 of the Personalize workshop in this directory. You will also need a mParticle workspace. If you are doing this workshop as part of a live workshop event, ask your moderator how to set up a mParticle workspace. \n", "\n", "If you are running this workshop on your own, you can sign up for a free trial (https://www.mparticle.com/free-trial) to request for the creation of a mParticle account. We do not recommend using your production mParticle workspace for this workshop.\n", "\n", "## mParticle Platform Overview\n", "mParticle is a customer data platform (CDP) that helps you collect, clean, and control your customer data. mParticle provides several types of Sources which you can use to collect your data, and which you can choose from based on the needs of your app or site. For websites, you can use a javascript library to collect data. If you have a mobile app, you can embed one of mParticle’s Mobile SDKs, and if you’d like to create messages directly on a server (if you have, for example a dedicated .NET server that processes payments), mParticle has several server-based libraries that you can embed directly into your backend code. With mParticle, you can also use cloud-sources to import data about your app or site from other tools like Zendesk or Salesforce, to enrich the data sent through mParticle. By using mParticle to decouple data collection from data use, you can create a centralized data supply chain based on organized and modular data.\n", "\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Setup\n", "If you have already entered your mParticle API key and secret into your Cloud Formation deployment, you can skip to the next section.\n", "\n", "mParticle uses *connections* as a way to organize data inputs into the platform. Configuring a input will allow you to collect real-time event data from the Retail Demo Store user interface, and pass that information to mParticle. You need to be signed into your mParticle workspace to begin this process. Once you are signed in to the mParticle console [https://app.mparticle.com](https://app.mparticle.com), click on your workspace, and then ‘Setup’ in the left hand navigation bar of the screen. Then, click ‘Inputs’.\n", "\n", "\n", "\n", "Select the ‘Web’ type within Platforms.\n", "\n", "\n", "\n", "And click ‘Web’ then click Issue Keys.\n", "\n", "\n", "\n", "mParticle will generate a pair of key and secret which you will use as part of the cloud formation template setup earlier.\n", "\n", "\n", "\n", "Now that you are here, set the write key for your new source in the environment variable below. \n", "\n", "You will need this in a few minutes, when you enable mParticle events collection in the Retail Demo Store.\n", "\n", "Make sure you run the cell after you paste the key. This will allow us to set the mParticle API key in the web UI deployment, and pass the keys securely to other back-end services via SSM." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# THIS IS ONLY REQUIRED IF YOU DID NOT SET THE mPARTICLE API KEYS AND ORG ID IN YOUR ORIGINAL DEPLOYMENT\n", "\n", "# IF YOU ARE RUNNING THIS IN A GUIDED WORKSHOP, YOU WILL NEED TO SET THESE VALUES BEFORE CONTINUING\n", "\n", "mparticle_api_key = \"\"\n", "mparticle_secret_key = \"\"\n", "\n", "import boto3\n", "import json\n", "\n", "ssm = boto3.client('ssm')\n", "iam = boto3.client('iam')\n", "sts = boto3.client('sts')\n", "\n", "aws_account_id = sts.get_caller_identity().get('Account')\n", "region_name = boto3.Session().region_name" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "if mparticle_api_key:\n", " response = ssm.put_parameter(\n", " Name='/retaildemostore/webui/mparticle_api_key',\n", " Value='{}'.format(mparticle_api_key),\n", " Type='String',\n", " Overwrite=True\n", " )\n", "\n", "if mparticle_secret_key:\n", " response = ssm.put_parameter(\n", " Name='/retaildemostore/webui/mparticle_secret_key',\n", " Value='{}'.format(mparticle_secret_key),\n", " Type='String',\n", " Overwrite=True\n", " )\n", "\n", "\n", "print(\"mParticle API Key:\")\n", "print(mparticle_api_key)\n", "print(\"mParticle Secret Key:\")\n", "print(mparticle_secret_key)\n", "print(\"AWS Account ID:\")\n", "print(aws_account_id)\n", "print(\"AWS Region:\")\n", "print(region_name)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You now have an environment variable that will enable the mParticle data collection library in the code in `AnalyticsHandler.js`. All we need to do now, is force a re-deploy of the Retail Demo Store. \n", "\n", "To do that, go back to your AWS Console tab or window, and select Code Pipeline from the Services search. Then, find the pipeline name that contains `WebUIPipeline` and click that link.\n", "\n", "Then, select the ‘Release Change’ button, and confirm the release once the popup shows up. You will see a confirmation that the pipeline is re-deploying the web ui for the Retail Demo Store.\n", "\n", "This process should complete in a few minutes. Once this is done, you will see the bottom tile confirm that your deployment has completed.\n", "\n", "Now that you have a working source, let's try to see if the Events from the Retail Demo Store are flowing into mParticle.\n", "\n", "## Sending Real-Time Events via the Retail Demo Store\n", "\n", "Navigate to your Retail Demo Store Web App and refresh the screen to reload the user interface. This will load the libraries you just deployed, and will allow your instance of the Retail Demo Store to send events to mParticle.\n", "\n", "mParticle provides a variety of ways to collect real time events, and a full discussion of how this works is beyond the scope of this document, however the Retail Demo Store represents a fairly typical deployment for most web applications, in that it uses the mParticle Web SDK library, loaded via NPM, to inject their code into the web application. \n", "\n", "To verify if mParticle JS is fully instantiated within the Retail Demo Store, just open developer console of your web browser and type \n", "```javascript window.mParticle.Identity.getCurrentUser().getMPID()```\n", "\n", "You should get the following response:\n", "\n", "\n", "\n", "Then, open another tab to the mParticle console, and select Live Stream under Data Master:\n", "\n", "\n", "\n", "You should see events collected by the mParticle SDK being streamed real-time within your mParticle instance. Feel free to view the events and see the actualy information hold per each event.\n", "\n", "You can also try logging in or creating an account within the AWS Retail Demo Store Web application. Feel free to check the difference between a logged in user vs a user who is a guest within the retail demo store web app.\n", "\n", "\n", "\n", "## Configure the mParticle Personalize Destination\n", "\n", "mParticle uses Outputs to route real-time event data to a data consumer application. In this case, you will be using Amazon Kinesis as the destination. This destination will take real-time events from mParticle, pass them through an AWS Lambda function, and then into the user-item interactions dataset in your Retail Demo Store.\n", "\n", "For this use case you will need to bring together mParticle and three AWS resources:\n", "\n", " 1.) An Amazon Kinesis stream to receive real-time events from mParticle\n", " 2.) An Amazon Personalize campaign to create product recommendations\n", " 3.) A Lambda function to act as a broker to transform data from Kinesis into a format accepted by Amazon Personalize (and ingested via a Personalize Event Tracker)\n", "\n", "When you deployed the Retail Demo Store, a Cloud Formation template deployed a Kinesis stream and Lambda function for this workshop, as well as the necessary IAM account and policy for mParticle to write to your Kinesis stream. Let's connect these to your mParticle environment.\n", "\n", "### Connect mParticle to Kinesis\n", "\n", "mParticle offers an \"event\" output for streaming event data to Kinesis in real time. This can be set up and controlled from the mParticle dashboard without writing code. You can read an overview of event outputs in the mParticle docs (https://docs.mparticle.com/guides/getting-started/connect-an-event-output/).\n", "\n", "Amazon Kinesis is an AWS service for processing streaming data. mParticle will forward commerce event data to Kinesis, where it will be picked up by the Lambda function you will set up in a moment.\n", "\n", "Click ‘Directory’ in the left hand navigation bar of the screen, and then search ‘Amazon Kinesis’.\n", "\n", "\n", "\n", "\n", "#### Create configuration\n", "\n", "First, you will need to create an overall configuration for Kinesis. This holds all the settings that will remain the same for every input you connect.\n", "\n", "\n", "\n", "To obtain an Access Key ID and Secret Access Key, please run the following code below and enter the generated Access Key ID and Secret in mParticle.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create keys for Kinesis\n", "\n", "# The Uid is a unique ID and we need it to find the role made by CloudFormation\n", "with open('/opt/ml/metadata/resource-metadata.json') as f:\n", " data = json.load(f)\n", "sagemaker = boto3.client('sagemaker')\n", "sagemakerResponce = sagemaker.list_tags(ResourceArn=data[\"ResourceArn\"])\n", "for tag in sagemakerResponce[\"Tags\"]:\n", " if tag['Key'] == 'Uid':\n", " Uid = tag['Value']\n", " break\n", "\n", "print('Uid:', Uid)\n", "\n", "# policy JSON\n", "# replace the region and account id\n", "# arn:aws:kinesis:us-east-1:683819462896:stream/finalbuildtest-us-east-1-mParticlePersonalizeEventsKinesisStream\n", "kinesisarn = \"arn:aws:kinesis:\"+region_name+\":\"+aws_account_id+\":stream/\"+Uid+\"-mParticlePersonalizeEventsKinesisStream\"\n", "print('kinesisarn:', kinesisarn)\n", "\n", "customPolicy = {\n", " \"Version\": \"2012-10-17\",\n", " \"Statement\": [\n", " {\n", " \"Effect\": \"Allow\",\n", " \"Action\": [\n", " \"kinesis:PutRecord\"\n", " ],\n", " \"Resource\": [\n", " kinesisarn\n", " ]\n", " }\n", " ]\n", "}\n", "\n", "# create the policy\n", "\n", "policy = iam.create_policy(\n", " PolicyName='KinesismParticlePolicy',\n", " PolicyDocument=json.dumps(customPolicy)\n", ")\n", "\n", "policy_arn = policy['Policy']['Arn']\n", "\n", "print(policy_arn)\n", "\n", "user_name = 'mParticleRetailDemoStoreKinesis'\n", "\n", "#create user\n", "created_user = iam.create_user(\n", " UserName=user_name\n", ")\n", "\n", "print(created_user)\n", "\n", "response = iam.attach_user_policy(\n", " UserName=user_name,\n", " PolicyArn=policy_arn\n", " )\n", "\n", "print(response)\n", "\n", "#create programmatic access_key for mParticle\n", "response = iam.create_access_key(\n", " UserName=user_name\n", ")\n", "\n", "access_key_id = response['AccessKey']['AccessKeyId']\n", "\n", "print(response)\n", "\n", "# The AWS region you are running in is:\n", "\n", "print(f'AWS Region: {region_name}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Connect all sources\n", "\n", "Next, you will connect the Retail Demo Store Web UI as an input: Web to Kinesis. To do that, click Connections then Connect. Select JS Web Platform as the Input\n", "\n", "\n", "\n", "Click + Connect Output\n", "\n", "\n", "\n", "Select Kinesis and the configuration You've just recently created earlier\n", "\n", "\n", "\n", "\n", "The settings you need to provide here are the Amazon Region in which you deployed the Retail Demo Store and the name of the Kinesis stream in your environment. The region will depend on which region you are using in your AWS account or workshop account. The name of the Kinesis stream will be `mParticlePersonalizeEventsKinesisStream`. This was deployed for you when you deployed the workshop environment.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "\n", "\n", "After setting up the Kinesis service region, make sure you untick all the checkboxes but leave Send eCommerce Events only ticked or selected. Click Save to save your settings. We only need to send eCommerece Events to Kinesis as these are the only events relevant for AWS Personalize.\n", "\n", "\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Configure Lambda Parameters and Review Code\n", "\n", "Before the destination can send events to your Amazon Personalize events tracker, you will need to tell the destination lambda where to send the events. It looks for an environment variable called 'personalize_tracking_id'.\n", "\n", "Let's set that. Run the following cell to look up the relevant Amazon Personalize tracker from the Personalize workbook.\n", "\n", "We can then set the appropriate value in the destination Lambda." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Within the mParticle Platform, navigate to Directory and within the search for Custom Feed.\n", "\n", "\n", "\n", "\n", "Click Setup and it should generate you a pair of key and secret. The key and secret generated here will be the keys you'll used for your lambda environment configuration.\n", "\n", "\n", "\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Set the Custom Feed Server to Server API Key and Secret from mParticle\n", "mparticle_s2s_api_key = \"us1-18cdb48aae1fb2459b805df5122f60a3\"\n", "mparticle_s2s_secret_key = \"17VD4QWXLezi7_Qc5-RWF5kyxM4BgKN9Y_s5Krd4qspmCdtltU7fH-gNrFwGlBUN\"\n", "\n", "# Let's look up the appropriate tracking string\n", "response = ssm.get_parameter(\n", " Name='/retaildemostore/personalize/event-tracker-id'\n", ")\n", "\n", "tracking_id = response['Parameter']['Value']\n", "\n", "\n", "# Get the Campaign ARN\n", "response = ssm.get_parameter(\n", " Name='/retaildemostore/personalize/recommended-for-you-arn'\n", ")\n", "\n", "product_recommendation_arn = response['Parameter']['Value']\n", "\n", "\n", "# set the Parameters via SSM\n", "if mparticle_s2s_api_key:\n", " response = ssm.put_parameter(\n", " Name='/retaildemostore/webui/mparticle_s2s_api_key',\n", " Value='{}'.format(mparticle_s2s_api_key),\n", " Type='String',\n", " Overwrite=True\n", " )\n", "\n", "if mparticle_s2s_secret_key:\n", " response = ssm.put_parameter(\n", " Name='/retaildemostore/webui/mparticle_s2s_secret_key',\n", " Value='{}'.format(mparticle_s2s_secret_key),\n", " Type='String',\n", " Overwrite=True\n", " )\n", "\n", "#Print\n", "print(\"mParticle S2S API Key:\")\n", "print(mparticle_s2s_api_key)\n", "print(\"mParticle S2S Secret Key:\")\n", "print(mparticle_s2s_secret_key)\n", "print(\"AWS Personalize Tracking ID:\")\n", "print(tracking_id)\n", "print(\"AWS Product Recommendation ARN:\")\n", "print(product_recommendation_arn)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Go to your AWS console tab or window, and select Lambda from the Services menu.\n", "\n", "Find the mParticlePersonalizeLambda, and click on it in the list.\n", "\n", "\n", "\n", "\n", "Feel free to look at the Lambda code. Make sure the Kinesis component is added as a trigger in the Lambda. If the Kinesis component is not added, make sure to add it.\n", "\n", "\n", "\n", "If the Kinesis component is already added, verify if it is set to Enabled. If its not set to Enabled, you would need to enable the Kinesis configuration in your Lambda function. Most likely the Kinesis component will be in a disabled state when it was initially created via the cloud formation template. Click the Enable Button.\n", "\n", "\n", "\n", "\n", "\n", "Take some time to look at the code that this Lambda uses to send events to Personalize. You can use this code in your own deployment, however you may need to change the event parameters sent to Amazon Personalize depending on the dataset you set up.\n", "\n", "```javascript\n", "// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n", "// SPDX-License-Identifier: MIT-0\n", "\n", "const AWS = require('aws-sdk');\n", "const SSM = new AWS.SSM();\n", "const mParticle = require('mparticle');\n", "const reportActions = [\"purchase\", \"view_detail\", \"add_to_cart\", \"checkout\",\"add_to_wishlist\"];\n", "const personalizeEvents = new AWS.PersonalizeEvents();\n", "const personalizeRuntime = new AWS.PersonalizeRuntime();\n", "const axios = require('axios');\n", "\n", "exports.handler = async function (event, context) {\n", " // Load all of our variables from SSM\n", " try {\n", " let params = {\n", " Names: ['/retaildemostore/services_load_balancers/products',\n", " '/retaildemostore/webui/mparticle_s2s_api_key',\n", " '/retaildemostore/webui/mparticle_s2s_secret_key',\n", " '/retaildemostore/personalize/event-tracker-id',\n", " '/retaildemostore/personalize/recommended-for-you-arn'],\n", " WithDecryption: false\n", " };\n", " let responseFromSSM = await SSM.getParameters(params).promise();\n", " \n", " for(const param of responseFromSSM.Parameters) {\n", " if( param.Name === '/retaildemostore/services_load_balancers/products') {\n", " var productsServiceURL = param.Value;\n", " } else if (param.Name === '/retaildemostore/webui/mparticle_s2s_api_key') {\n", " var mpApiKey = param.Value;\n", " } else if (param.Name === '/retaildemostore/webui/mparticle_s2s_secret_key') {\n", " var mpApiSecret = param.Value;\n", " } else if (param.Name === '/retaildemostore/personalize/event-tracker-id') {\n", " var personalizeTrackerID = param.Value; \n", " } else if (param.Name === '/retaildemostore/personalize/recommended-for-you-arn') {\n", " var personalizeARN = param.Value;\n", " }\n", " }\n", " \n", " // Init mParticle libraries for the function invocation\n", " var mpApiInstance = new mParticle.EventsApi(new mParticle.Configuration(mpApiKey, mpApiSecret));\n", " } catch (e) {\n", " console.log(\"Error getting SSM parameter for loadbalancer.\");\n", " console.log(e); \n", " throw e; \n", " }\n", "\n", " for (const record of event.Records) {\n", " const payloadString = Buffer.from(record.kinesis.data, 'base64').toString('ascii');\n", " const payload = JSON.parse(payloadString);\n", " const events = payload.events;\n", " var amazonPersonalizeUserId;\n", " console.log(`EVENTS: ${JSON.stringify(events)}`);\n", " \n", " // First, get the mParticle user ID from the events payload. In this example, mParticle will send all the events\n", " // for a particular user in a batch to this lambda.\n", " // retreive the mParticle user id which is available for anonymous and known customer profiles\n", " var anonymousID = events[0].data.custom_attributes.mpid.toString();\n", " \n", " // if the customer profile is known then replace the amazon Personalize User id with the actual\n", " // personalize Id captured from the user's profile\n", " if(payload.user_attributes && payload.user_attributes.amazonPersonalizeId)\n", " amazonPersonalizeUserId = payload.user_attributes.amazonPersonalizeId; \n", " else\n", " amazonPersonalizeUserId = anonymousID;\n", " // Verify in mParticle's payload if there is a customer id set within the customer profile\n", " // this will be used for identity resolution later on within mParticle.\n", " var customerId = null;\n", " if(payload.user_identities){\n", " for (const identityRecord of payload.user_identities)\n", " {\n", " if(identityRecord.identity_type===\"customer_id\")\n", " customerId = identityRecord.identity; \n", " }\n", " }\n", "\n", " var params = {\n", " sessionId: payload.message_id,\n", " userId: amazonPersonalizeUserId,\n", " trackingId: personalizeTrackerID,\n", " eventList: []\n", " };\n", "\n", " // Check for variant and assign one if not already assigned\n", " /*var variantAssigned;\n", " var variant;\n", " if(payload.user_attributes && payload.user_attributes.ml_variant) {\n", " variantAssigned = Boolean(payload.user_attributes.ml_variant); \n", " variant = variantAssigned ? payload.user_attributes.ml_variant : Math.random() > 0.5 ? \"A\" : \"B\";\n", " }*/\n", " \n", " for (const e of events) {\n", " if (e.event_type === \"commerce_event\" && reportActions.indexOf(e.data.product_action.action) >= 0) {\n", " const timestamp = Math.floor(e.data.timestamp_unixtime_ms / 1000);\n", " const action = e.data.product_action.action;\n", " const event_id = e.data.event_id;\n", " \n", "\n", " let params = {\n", " sessionId: payload.message_id,\n", " userId: amazonPersonalizeUserId,\n", " trackingId: personalizeTrackerID,\n", " eventList: []\n", " };\n", "\n", " // Build the list of events for the user session...\n", " for (const product of e.data.product_action.products) {\n", " const purchasedItem = { itemId: product.id };\n", " params.eventList.push({\n", " properties: purchasedItem,\n", " sentAt: timestamp,\n", " eventId: event_id,\n", " eventType: action\n", " });\n", " }\n", " }\n", " }\n", " \n", " console.log(JSON.stringify(params));\n", " \n", " // Send the events to Amazon Personalize for training purposes\n", " try {\n", " await personalizeEvents.putEvents(params).promise();\n", " } catch (e) {\n", " console.log(`ERROR - Could not put events - ${e}`);\n", " }\n", " \n", " // Get Recommendations from Personalize for the user ID we got up top\n", " let recommendationsParams = {\n", " numResults: '5',\n", " userId: amazonPersonalizeUserId\n", " };\n", "\n", " if (personalizeARN.split(':')[5].startsWith('recommender/')) {\n", " recommendationsParams.recommenderArn = personalizeARN;\n", " }\n", " else {\n", " recommendationsParams.campaignArn = personalizeARN;\n", " }\n", " \n", " try {\n", " var recommendations = await personalizeRuntime.getRecommendations(recommendationsParams).promise();\n", " console.log(`RECOMMENDATIONS - ${JSON.stringify(recommendations)}`);\n", " } catch (e) {\n", " console.log(`ERROR - Could not get recommendations - ${e}`);\n", " }\n", " \n", " // Reverse Lookup the product ids to actual product name using the product service url\n", " let itemList = [];\n", " var productNameList = [];\n", " for (let item of recommendations.itemList) {\n", " itemList.push(item.itemId);\n", " var productRequestURL = `${productsServiceURL}/products/id/${item.itemId}`;\n", " var productInfo = await axios.get(productRequestURL);\n", " productNameList.push(productInfo.data.name);\n", " }\n", "\n", " \n", " //build the mParticle object and send it to mParticle\n", " let batch = new mParticle.Batch(mParticle.Batch.Environment.development);\n", "\n", " // if the customer profile is anonymous, we'll use the mParticle ID to tie this recommendation back to the anonymous user\n", " // else we will use the customer Id which was provided earlier\n", " if(customerId == null) {\n", " batch.mpid = anonymousID;\n", " } else {\n", " batch.user_identities = new mParticle.UserIdentities();\n", " batch.user_identities.customerid = customerId; // identify the user via the customer id \n", " } \n", " batch.user_attributes = {};\n", " batch.user_attributes.product_recs = itemList;\n", " batch.user_attributes.product_recs_name=productNameList;\n", " \n", " \n", " // Create an Event Object using an event type of Other\n", " let event = new mParticle.AppEvent(mParticle.AppEvent.CustomEventType.other, 'AWS Product Personalization Recs Update');\n", " event.custom_attributes = {product_recs: itemList.join()};\n", " batch.addEvent(event);\n", " var body = [batch]; // {[Batch]} Up to 100 Batch objects\n", " console.log(event);\n", " console.log(batch);\n", " let mp_callback = function(error, data, response) {\n", " if (error) {\n", " console.error(error);\n", " } else {\n", " console.log('API called successfully.');\n", " }\n", " };\n", " \n", " // Send to Event to mParticle\n", " mpApiInstance.bulkUploadEvents(body, mp_callback);\n", " }\n", "};\n", " \n", "```\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Validate that Real-Time Events are Flowing to AWS Kinesis\n", "\n", "To validate if events being captured from mParticle are being sent to Kinesis, you would need to go back to the mParticle UI/Platform and Click Data Master then Livestream.\n", "\n", "Under Message Direction, select Both In and Out\n", "\n", "\n", "\n", "Go back to the Retail Demo Store Web App, and do a eCommerce event. This can be done by viewing a product, click add to Cart, Checkout or Purchase.\n", "\n", "You should see the following entries within Livestream which will contain Amazon Kinesis with an outward arrow.\n", "\n", "\n", "\n", "If you haven't seen any outbound events generated to Amazon Kinesis, you might need to wait for a while before the settings are applied properly." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## Save AWS Personalize Recommended Products back to mParticle\n", "\n", "Aside from just sending events from the AWS Retail Demo Store to mParticle, the Lambda function above also sends the commerce events to AWS Personalize. This allows AWS Personalize to receive specific commerce events made by a anonymous and known user and from there allow AWS Personalize to do its magic by providing product recommendation information back to mParticle. Once AWS Personalize has finished computing the relevant products that is associated to the recent events the customer has made, the said product recommendation information will be sent back to mParticle using the mParticle NodeJS SDK. The said code snippet below will set the product_recommendation information as a user attribute (product_recs) within the user's profile. \n", "\n", "```javascript\n", " // if Events are more than 10 splice the events \n", " if(params.eventList.length > 10)\n", " {\n", " var lastTenRecords = params.eventList.length / 2;\n", " params.eventList = params.eventList.slice(lastTenRecords);\n", " }\n", " if (params.eventList.length > 0) {\n", " \n", " \n", " // Reverse Lookup the product ids to actual product name using the product service url\n", " let itemList = [];\n", " var productNameList = [];\n", " for (let item of recommendations.itemList) {\n", " itemList.push(item.itemId);\n", " var productRequestURL = '{productsServiceURL}/products/id/${item.itemId}';\n", " var productInfo = await axios.get(productRequestURL);\n", " productNameList.push(productInfo.data.name);\n", " }\n", "\n", " \n", " //build the mParticle object and send it to mParticle\n", " let batch = new mParticle.Batch(mParticle.Batch.Environment.development);\n", "\n", " // if the customer profile is anonymous, we'll use the mParticle ID to tie this recommendation back to the anonymous user\n", " // else we will use the customer Id which was provided earlier\n", " if(customerId == null){\n", " batch.mpid = anonymousID;\n", " }\n", " else{\n", " batch.user_identities = new mParticle.UserIdentities();\n", " batch.user_identities.customerid = customerId; // identify the user via the customer id \n", " } \n", " batch.user_attributes = {};\n", " batch.user_attributes.product_recs = itemList;\n", " batch.user_attributes.product_recs_name=productNameList;\n", " \n", " \n", " // Create an Event Object using an event type of Other\n", " let event = new mParticle.AppEvent(mParticle.AppEvent.CustomEventType.other, 'AWS Product Personalization Recs Update');\n", " event.custom_attributes = {product_recs: itemList.join()};\n", " batch.addEvent(event);\n", " var body = [batch]; // {[Batch]} Up to 100 Batch objects\n", " console.log(event);\n", " console.log(batch);\n", " let mp_callback = async function(error, data, response) {\n", " if (error) {\n", " console.error(error);\n", " } else {\n", " console.log('API called successfully.');\n", " }\n", " };\n", " \n", " // Send to Event to mParticle\n", " await mpApiInstance.bulkUploadEvents(body, mp_callback);\n", " \n", " }\n", "};\n", "\n", "```\n", "\n", "\n", "\n", "\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# When you are done with this module, you can delete the user and policies you created earlier\n", "\n", "# detach the policy from the user we created\n", "\n", "result = iam.detach_user_policy(\n", " PolicyArn=policy_arn,\n", " UserName=user_name )\n", "\n", "result = iam.delete_access_key(\n", " AccessKeyId = access_key_id,\n", " UserName = user_name )\n", "\n", "# delete the kinesis policy\n", "policy = iam.delete_policy(\n", " PolicyArn=policy_arn )\n", "\n", "# delete the user we created\n", "created_user = iam.delete_user(\n", " UserName=user_name\n", ")" ] } ], "metadata": { "interpreter": { "hash": "0dcd9f5e34f8df8f8894486951f66d4acf74e4779e08f447b14b2a31d4107ec6" }, "kernelspec": { "display_name": "conda_python3", "language": "python", "name": "conda_python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.13" } }, "nbformat": 4, "nbformat_minor": 2 }