

# Getting started with a Custom dataset group
<a name="getting-started-custom"></a>

**Important**  
In this tutorial you create a solution that uses automatic training. By default, all new solutions use automatic training. With automatic training, you incur training costs while your solution is active. To avoid unnecessary costs, make sure to delete the solution when you are finished. For more information, see [Requirements for deleting Amazon Personalize resources](deleting-resources.md).

 This getting started guide shows you how to provide personalized movie recommendations for your users with a Custom dataset group and the [User-Personalization-v2 recipe](native-recipe-user-personalization-v2.md) recipe. The tutorial uses historical data that consists of 100,000 movie ratings on 9,700 movies from 600 users.

To begin, complete the [Getting started prerequisites](gs-prerequisites.md) and then proceed to either [Getting started (console)](getting-started-console.md), [Getting started (Amazon CLI)](getting-started-cli.md), [Getting started (SDK for Python (Boto3))](getting-started-python.md), or [Getting started (SDK for Java 2.x)](getting-started-java.md).

When you finish the getting started exercise, to avoid incurring unnecessary charges, delete the resources that you created. For more information, see [Requirements for deleting Amazon Personalize resources](deleting-resources.md). 

**Topics**
+ [

# Getting started (console)
](getting-started-console.md)
+ [

# Getting started (Amazon CLI)
](getting-started-cli.md)
+ [

# Getting started (SDK for Python (Boto3))
](getting-started-python.md)
+ [

# Getting started (SDK for Java 2.x)
](getting-started-java.md)

# Getting started (console)
<a name="getting-started-console"></a>

In this exercise, you use the Amazon Personalize console to create a Custom dataset group with a solution that returns movie recommendations for a given user. Before you start this exercise, review the [Getting started prerequisites](gs-prerequisites.md).

When you finish the getting started exercise, to avoid incurring unnecessary charges, delete the resources that you created. For more information, see [Requirements for deleting Amazon Personalize resources](deleting-resources.md). 

## Step 1: Create a dataset group and a dataset
<a name="getting-started-console-create-dataset"></a>

In this procedure, you first create a dataset group. Next, you create an Amazon Personalize *Item interactions dataset* dataset in the dataset group.

**To create a dataset group and a dataset**

1. Open the Amazon Personalize console at [https://console.amazonaws.cn/personalize/home](https://console.amazonaws.cn/personalize/home) and sign in to your account.

1. Choose **Create dataset group**.

1. In **Dataset group details**, for **Dataset group name**, specify a name for your dataset group. 

1. For **Domain** choose **Custom**. Your screen should look similar to the following:  
![\[Depicts Create dataset group page with Name, Domain, and Tags fields.\]](http://docs.amazonaws.cn/en_us/personalize/latest/dg/images/gs-1-dataset-group-v02.png)

1. Choose **Create group**. The **Overview** page appears.

1. In **Step 1. Create datasets and import data**, choose **Create dataset** and choose **Item interactions dataset**.

1. Choose **Import data directly into Amazon Personalize datasets** and choose **Next**.

1. On the **Configure item interactions dataset** page, for **Dataset name**, specify a name for your dataset.

1. For **Dataset schema**, choose **Create new schema**. In the **Schema definition** section, a minimal Item interactions schema is displayed. The schema matches the headers you previously added to the `ratings.csv` file, so you don't need to make any changes. If you haven't created the training data, see [Getting started prerequisites](gs-prerequisites.md). 

1. For **Schema name**, specify a name for the new schema. Your screen should look similar to the following:  
![\[Depicts the Configure item interactions schema page with dataset and schema fields.\]](http://docs.amazonaws.cn/en_us/personalize/latest/dg/images/gs-2-schema.png)

1. Choose **Next**. The **Configure item interactions dataset import job** page appears. Next, complete [Step 2: Import item interactions data](#getting-started-console-import-data) to import interactions data.

## Step 2: Import item interactions data
<a name="getting-started-console-import-data"></a>

 Now that you have created a dataset, it's time to import item interactions data into the dataset. 

**To import item interactions data**

1. On the **Configure item interactions dataset import job** page, for **Data import source** choose **Import data from S3**. 

1. For **Dataset import job name**, specify a name for your import job.

1. In the **Additional S3 bucket policy required** dialog box, if you haven't granted Amazon Personalize permissions, follow the instructions to [add the required Amazon S3 bucket policy](granting-personalize-s3-access.md).

1. For **Data location**, specify where your movie data file is stored in Amazon Simple Storage Service (S3). Use the following syntax:

   **s3://amzn-s3-demo-bucket/<folder path>/filename.csv**

1. In the **IAM Role** section, for **IAM service role**, choose **Enter a custom IAM role ARN**.

1. For **Custom IAM role ARN**, specify the role that you created in [Creating an IAM role for Amazon Personalize](set-up-required-permissions.md#set-up-create-role-with-permissions).

    The **Dataset import job details** and **IAM role** sections should be similar to the following:   
![\[Depicts the Configure item interactions dataset import job page with import job fields.\]](http://docs.amazonaws.cn/en_us/personalize/latest/dg/images/gs-3-import-job.png)

1. Leave the **Publish event metrics to S3 ** and **Tags** sections unchanged and choose **Start import**. The data import job starts and the **Overview** page is displayed. Initially, the status is **Create pending** (followed by **Create in progress**), and the **Create solution** button is disabled.

   When the data import job has finished, the status changes to **Active** and the **Create solution** button is enabled.

1. Now that you have imported data, you are ready to create a solution in [Step 3: Create a solution](#getting-started-console-create-solution).

## Step 3: Create a solution
<a name="getting-started-console-create-solution"></a>

In this tutorial, you use the dataset that you imported in [Step 2: Import item interactions data](#getting-started-console-import-data) to train a model. A trained model is referred to as a *solution version*.

**Important**  
In this tutorial you create a solution that uses automatic training. With automatic training, you incur training costs while your solution is active. To avoid unnecessary costs, make sure to delete the solution when you are finished. For more information, see [Requirements for deleting Amazon Personalize resources](deleting-resources.md).

**To create a solution**

1. On the **Overview** page for your dataset group, in **Step 3. Set up training and recommendation resources** choose **Create solutions**.

1. For **Solution name**, specify a name for your solution.

1. For **Solution type** choose **Item recommendations**.

1. For **Recipe**, choose `aws-user-personalization-v2`.

   Your screen should look similar to the following:  
![\[Depicts the Configure solution page with solution name, type and recipe fields.\]](http://docs.amazonaws.cn/en_us/personalize/latest/dg/images/gs-5-create-solution.png)

1. Choose **Next**. Leave the **Training configuration** fields unchanged. The solution you create automatically trains new models every 7 days and gives more weight to the most recent item interaction data.

1. Choose **Next** and review the details for the solution.

1. Choose **Create solution** and the details page for the solution displays. After you create a solution, Amazon Personalize starts creating your first solution version within an hour. When training starts, it appears in the **Solution versions** section on the details page and you can monitor its status.

   When the **Solution version status** is *Active*, you are ready to move to [Step 4: Create a campaign](#getting-started-console-deploy-solution).

## Step 4: Create a campaign
<a name="getting-started-console-deploy-solution"></a>

In this procedure, you create a campaign, which deploys the solution version you created in the previous step.

**To create a campaign**

1. In the navigation pane, expand **Custom resources** and choose **Campaigns**.

1. Choose **Create campaign**. The **Create new campaign** page appears.

1. In **Campaign details**, for **Campaign name**, specify a name for your campaign.

1. For **Solution**, choose the solution you created in the previous step.

1. Choose **Automatically use the latest solution version**. Leave all other fields unchanged.

   Your screen should look similar to the following:  
![\[Depicts the Create new campaign page with campaign configuration fields.\]](http://docs.amazonaws.cn/en_us/personalize/latest/dg/images/getting-started-create-new-campaign.png)

1. Choose **Create campaign**. Campaign creation starts and the campaign details pages with the **Personalization API** section displayed.

   Creating a campaign can take a couple minutes. After Amazon Personalize finishes creating your campaign, the page is updated to show the **Test campaign results** section. Your screen should look similar to the following:  
![\[Depicts the test campaign section with fields for a recommendation request.\]](http://docs.amazonaws.cn/en_us/personalize/latest/dg/images/gs-campaign-test-before-results.png)

## Step 5: Get recommendations
<a name="getting-started-console-get-recommendations"></a>

In this procedure, use the campaign that you created in the previous step to get recommendations.

**To get recommendations**

1. In **Test campaign results**, for **User ID**, specify a value from the *ratings* dataset, for example, **83**. Leave all other fields unchanged.

1. Choose **Get recommendations**. The **Recommendations** panel lists the item IDs and scores for the recommended items.

   Your screen should look similar to the following:  
![\[Depicts the Test campaign section for a campaign with recommendation results.\]](http://docs.amazonaws.cn/en_us/personalize/latest/dg/images/gs-test-campaign-with-results.png)

# Getting started (Amazon CLI)
<a name="getting-started-cli"></a>

In this exercise, you use the Amazon Command Line Interface (Amazon CLI) to explore Amazon Personalize. You create a campaign that returns movie recommendations for a given user ID.

Before you start this exercise, do the following:
+ Review the Getting Started [Getting started prerequisites](gs-prerequisites.md).
+ Set up the Amazon CLI, as specified in [Setting up the Amazon CLI](aws-personalize-set-up-aws-cli.md).

When you finish the getting started exercise, to avoid incurring unnecessary charges, delete the resources that you created. For more information, see [Requirements for deleting Amazon Personalize resources](deleting-resources.md). 

**Note**  
The Amazon CLI commands in this exercise were tested on Linux. For information about using the Amazon CLI commands on Windows, see [Specifying parameter values for the Amazon Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-using-param.html) in the *Amazon Command Line Interface User Guide*.

## Step 1: Import training data
<a name="gs-create-ds"></a>

Follow the steps to create a dataset group, add a dataset to the group, and then populate the dataset using the movie ratings data.

1. Create a dataset group by running the following command. You can encrypt the dataset group by passing a [Amazon Key Management Service](https://docs.amazonaws.cn/kms/latest/developerguide/overview.html) key ARN and the ARN of an IAM role that has access permissions to that key as input parameters. For more information about the API, see [CreateDatasetGroup](API_CreateDatasetGroup.md).

   ```
   aws personalize create-dataset-group --name MovieRatingDatasetGroup --kms-key-arn arn:aws:kms:us-west-2:01234567890:key/1682a1e7-a94d-4d92-bbdf-837d3b62315e --role-arn arn:aws:iam::01234567890:KMS-key-access
   ```

   The dataset group ARN is displayed, for example:

   ```
   {
     "datasetGroupArn": "arn:aws:personalize:us-west-2:acct-id:dataset-group/MovieRatingDatasetGroup"
   }
   ```

   Use the `describe-dataset-group` command to display the dataset group you created, specifying the returned dataset group ARN.

   ```
   aws personalize describe-dataset-group \
   --dataset-group-arn arn:aws:personalize:us-west-2:acct-id:dataset-group/MovieRatingDatasetGroup
   ```

   The dataset group and its properties are displayed, for example:

   ```
   {
       "datasetGroup": {
           "name": "MovieRatingDatasetGroup",
           "datasetGroupArn": "arn:aws:personalize:us-west-2:acct-id:dataset-group/MovieRatingDatasetGroup",
           "status": "ACTIVE",
           "creationDateTime": 1542392161.262,
           "lastUpdatedDateTime": 1542396513.377
       }
   }
   ```
**Note**  
Wait until the dataset group's `status` shows as ACTIVE before creating a dataset in the group. This operation is usually quick.

   If you don't remember the dataset group ARN, use the `list-dataset-groups` command to display all the dataset groups that you created, along with their ARNs.

   ```
   aws personalize list-dataset-groups
   ```
**Note**  
The `describe-object` and `list-objects` commands are available for most Amazon Personalize objects. These commands are not shown in the remainder of this exercise but they are available.

1. Create a schema file in JSON format by saving the following code to a file named `MovieRatingSchema.json`. The schema matches the headers you previously added to `ratings.csv`. The schema name is `Interactions`, which matches one of the types of datasets recognized by Amazon Personalize. For more information, see [Creating schema JSON files for Amazon Personalize schemas](how-it-works-dataset-schema.md).

   ```
   {
     "type": "record",
     "name": "Interactions",
     "namespace": "com.amazonaws.personalize.schema",
     "fields": [
         {
             "name": "USER_ID",
             "type": "string"
         },
         {
             "name": "ITEM_ID",
             "type": "string"
         },
         {
             "name": "TIMESTAMP",
             "type": "long"
         }
     ],
     "version": "1.0"
   }
   ```

1. Create a schema by running the following command. Specify the file you saved in the previous step. The example shows the file as belonging to the current folder. For more information about the API, see [CreateSchema](API_CreateSchema.md).

   ```
   aws personalize create-schema \
     --name MovieRatingSchema \
     --schema file://MovieRatingSchema.json
   ```

   The schema Amazon Resource Name (ARN) is displayed, for example:

   ```
   {
     "schemaArn": "arn:aws:personalize:us-west-2:acct-id:schema/MovieRatingSchema"
   }
   ```

1. Create an empty dataset by running the following command. Provide the dataset group ARN and schema ARN that were returned in the previous steps. The `dataset-type` must match the schema `name` from the previous step. For more information about the API, see [CreateDataset](API_CreateDataset.md).

   ```
   aws personalize create-dataset \
     --name MovieRatingDataset \
     --dataset-group-arn arn:aws:personalize:us-west-2:acct-id:dataset-group/MovieRatingDatasetGroup \
     --dataset-type Interactions \
     --schema-arn arn:aws:personalize:us-west-2:acct-id:schema/MovieRatingSchema
   ```

   The dataset ARN is displayed, for example:

   ```
   {
     "datasetArn": "arn:aws:personalize:us-west-2:acct-id:dataset/MovieRatingDatasetGroup/INTERACTIONS"
   }
   ```

1. Add the training data to the dataset.

   1. Create a dataset import job by running the following command. Provide the dataset ARN and Amazon S3 bucket name that were returned in the previous steps. Supply the Amazon Identity and Access Management (IAM) role ARN you created in [Creating an IAM role for Amazon Personalize](set-up-required-permissions.md#set-up-create-role-with-permissions). For more information about the API, see [CreateDatasetImportJob](API_CreateDatasetImportJob.md).

      ```
      aws personalize create-dataset-import-job \
        --job-name MovieRatingImportJob \
        --dataset-arn arn:aws:personalize:us-west-2:acct-id:dataset/MovieRatingDatasetGroup/INTERACTIONS \
        --data-source dataLocation=s3://amzn-s3-demo-bucket/ratings.csv \
        --role-arn roleArn
      ```

      The dataset import job ARN is displayed, for example:

      ```
      {
        "datasetImportJobArn": "arn:aws:personalize:us-west-2:acct-id:dataset-import-job/MovieRatingImportJob"
      }
      ```

   1. Check the status by using the `describe-dataset-import-job` command. Provide the dataset import job ARN that was returned in the previous step. For more information about the API, see [DescribeDatasetImportJob](API_DescribeDatasetImportJob.md).

      ```
      aws personalize describe-dataset-import-job \
        --dataset-import-job-arn arn:aws:personalize:us-west-2:acct-id:dataset-import-job/MovieRatingImportJob
      ```

      The properties of the dataset import job, including its status, are displayed. Initially, the `status` shows as CREATE PENDING, for example:

      ```
      {
        "datasetImportJob": {
            "jobName": "MovieRatingImportJob",
            "datasetImportJobArn": "arn:aws:personalize:us-west-2:acct-id:dataset-import-job/MovieRatingImportJob",
            "datasetArn": "arn:aws:personalize:us-west-2:acct-id:dataset/MovieRatingDatasetGroup/INTERACTIONS",
            "dataSource": {
                "dataLocation": "s3://amzn-s3-demo-bucket/ratings.csv"
            },
            "roleArn": "role-arn",
            "status": "CREATE PENDING",
            "creationDateTime": 1542392161.837,
            "lastUpdatedDateTime": 1542393013.377
        }
      }
      ```

      The dataset import is complete when the status shows as ACTIVE. Then you are ready to train the model using the specified dataset.
**Note**  
Importing takes time. Wait until the dataset import is complete before training the model using the dataset.

## Step 2: Create a solution (train the model)
<a name="gs-create-solution"></a>

To train a model, you create the configuration for training the model using the [CreateSolution](API_CreateSolution.md) operation and leave automatic training on. The solution automatically starts training the first solution within an hour.

You train a model using a recipe and your training data. Amazon Personalize provides a set of predefined recipes. For more information, see [Choosing a recipe](working-with-predefined-recipes.md). For this exercise, you use the User-Personalization-v2 recipe.

1. Create the configuration for training a model by running the following command. This command creates a solution that uses automatic training. It automatically creates a new solution version every seven days (the default).

   ```
   aws personalize create-solution \
     --name MovieSolution \
     --dataset-group-arn arn:aws:personalize:us-west-2:acct-id:dataset-group/MovieRatingDatasetGroup \
     --recipe-arn arn:aws:personalize:::recipe/aws-user-personalization-v2 \ 
     --perform-auto-training \
     --solution-config "{\"autoTrainingConfig\": {\"schedulingExpression\": \"rate(7 days)\"}}"
   ```

   The solution ARN is displayed, for example:

   ```
   {
     "solutionArn": "arn:aws:personalize:us-west-2:acct-id:solution/MovieSolution"
   }
   ```

1. Check the *create* status using the `describe-solution` command. Provide the solution ARN that was returned in the previous step. For more information about the API, see [DescribeSolution](API_DescribeSolution.md).

   ```
   aws personalize describe-solution \
     --solution-arn arn:aws:personalize:us-west-2:acct-id:solution/MovieSolution
   ```

   The properties of the solution and the create `status` are displayed. For example:

   ```
   {      
     "solution": {
         "name": "MovieSolution",
         "solutionArn": "arn:aws:personalize:us-west-2:acct-id:solution/MovieSolution",
         "performHPO": false,
         "performAutoML": false,
         "recipeArn": "arn:aws:personalize:::recipe/aws-user-personalization-v2",
         "datasetGroupArn": "arn:aws:personalize:us-west-2:acct-id:dataset-group/MovieRatingDatasetGroup",
         "solutionConfig": {
               "algorithmHyperParameters": {
                   "apply_recency_bias": "true"
               },
               "featureTransformationParameters": {},
               "autoTrainingConfig": {
                   "schedulingExpression": "rate(7 days)"
               }
          },
         "status": "ACTIVE",
         "creationDateTime": "2021-05-12T16:27:59.819000-07:00",
         "lastUpdatedDateTime": "2021-05-12T16:27:59.819000-07:00"
     }
   }
   ```

1.  With automatic training, solution version training starts within one after the solution is ACTIVE. After training starts, you can get the solution version's Amazon Resource Name (ARN) with the following [ListSolutionVersions](https://docs.amazonaws.cn/personalize/latest/dg/API_ListSolutionVersions.html) command: 

   ```
   aws personalize list-solution-versions --solution-arn arn:aws:personalize:us-west-2:acct-id:solution/MovieSolution
   ```

1. Check the *training* status of the solution version by using the `describe-solution-version` command. Provide the solution version ARN that was returned in the previous step. For more information about the API, see [DescribeSolutionVersion](API_DescribeSolutionVersion.md).

   ```
   aws personalize describe-solution-version \
     --solution-version-arn arn:aws:personalize:us-west-2:acct-id:solution/MovieSolution/version-id
   ```

   The properties of the solution version and the training `status` are displayed. Initially, the status shows as CREATE PENDING, for example:

   ```
   {
     "solutionVersion": {
         "solutionVersionArn": "arn:aws:personalize:us-west-2:acct-id:solution/MovieSolution/<version-id>",
         ...,
         "status": "CREATE PENDING"
     }
   }
   ```

1. When the solution version `status` is ACTIVE, the training is complete.

   Now you can review training metrics and create a campaign using the solution version.
**Note**  
Training takes time. Wait until training is complete (the *training* status of the solution version shows as ACTIVE) before using this version of the solution in a campaign.

1. You can validate the performance of the solution version by reviewing its metrics. Get the metrics for the solution version by running the following command. Provide the solution version ARN that was returned previously. For more information about the API, see [GetSolutionMetrics](API_GetSolutionMetrics.md).

   ```
   aws personalize get-solution-metrics \
     --solution-version-arn arn:aws:personalize:us-west-2:acct-id:solution/MovieSolution/version-id
   ```

   A sample response is shown:

   ```
   {
     "solutionVersionArn": "arn:aws:personalize:us-west-2:acct-id:solution/www-solution/<version-id>",
     "metrics": {
           "coverage": 0.0485,
           "mean_reciprocal_rank_at_25": 0.0381,
           "normalized_discounted_cumulative_gain_at_10": 0.0363,
           "normalized_discounted_cumulative_gain_at_25": 0.0984,
           "normalized_discounted_cumulative_gain_at_5": 0.0175,
           "precision_at_10": 0.0107,
           "precision_at_25": 0.0207,
           "precision_at_5": 0.0107
       }
   }
   ```

## Step 3: Create a campaign (deploy the solution)
<a name="gs-create-campaign"></a>

Before you can get recommendations, you must deploy a solution version. Deploying a solution is also known as creating a campaign. Once you've created your campaign, your client application can get recommendations using the [GetRecommendations](API_RS_GetRecommendations.md) API.

1. Create a campaign by running the following command. Provide the solution version ARN that was returned in the previous step. For more information about the API, see [CreateCampaign](API_CreateCampaign.md).

   ```
   aws personalize create-campaign \
     --name MovieRecommendationCampaign \
     --solution-version-arn arn:aws:personalize:us-west-2:acct-id:solution/MovieSolution/version-id \
     --min-provisioned-tps 1
   ```

   A sample response is shown:

   ```
   {
     "campaignArn": "arn:aws:personalize:us-west-2:acct-id:campaign/MovieRecommendationCampaign"
   }
   ```

1. Check the deployment status by running the following command. Provide the campaign ARN that was returned in the previous step. For more information about the API, see [DescribeCampaign](API_DescribeCampaign.md).

   ```
   aws personalize describe-campaign \
     --campaign-arn arn:aws:personalize:us-west-2:acct-id:campaign/MovieRecommendationCampaign
   ```

   A sample response is shown:

   ```
   {
     "campaign": { 
         "name": "MovieRecommendationCampaign",
         "campaignArn": "arn:aws:personalize:us-west-2:acct-id:campaign/MovieRecommendationCampaign",
         "solutionVersionArn": "arn:aws:personalize:us-west-2:acct-id:solution/MovieSolution/<version-id>",
         "minProvisionedTPS": "1",
         "creationDateTime": 1543864775.923,
         "lastUpdatedDateTime": 1543864791.923,
         "status": "CREATE IN_PROGRESS"
     }
   }
   ```
**Note**  
Wait until the `status` shows as ACTIVE before getting recommendations from the campaign.

## Step 4: Get recommendations
<a name="gs-test"></a>

Get recommendations by running the `get-recommendations` command. Provide the campaign ARN that was returned in the previous step. In the request, you specify a user ID from the movie ratings dataset. For more information about the API, see [GetRecommendations](API_RS_GetRecommendations.md).

**Note**  
Not all recipes support the `GetRecommendations` API. For more information, see [Choosing a recipe](working-with-predefined-recipes.md).  
The Amazon CLI command you call in this step, `personalize-runtime`, is different than in previous steps.

```
aws personalize-runtime get-recommendations \
  --campaign-arn arn:aws:personalize:us-west-2:acct-id:campaign/MovieRecommendationCampaign \
  --user-id 123
```

In response, the campaign returns a list of item recommendations (movie IDs) the user might like. The list is sorted in descending order of relevance for the user.

```
{
  "itemList": [
      {
          "itemId": "14"
      },
      {
          "itemId": "15"
      },
      {
          "itemId": "275"
      },
      {
          "itemId": "283"
      },
      {
          "itemId": "273"
      },
      ...
  ]
}
```

# Getting started (SDK for Python (Boto3))
<a name="getting-started-python"></a>

This tutorial shows you how to complete the Amazon Personalize workflow from start to finish with the SDK for Python (Boto3). 

When you finish the getting started exercise, to avoid incurring unnecessary charges, delete the resources that you created. For more information, see [Requirements for deleting Amazon Personalize resources](deleting-resources.md). 

**Topics**
+ [

## Prerequisites
](#gs-sdk-prerequisites)
+ [

## Tutorial
](#gs-python-custom-tutorial)
+ [

## Getting started using Amazon Personalize APIs with Jupyter (iPython) notebooks
](#gs-jupyter-notebook)

## Prerequisites
<a name="gs-sdk-prerequisites"></a>

The following are prerequisite steps for using the Python examples in this guide:
+ Complete the [Getting started prerequisites](gs-prerequisites.md) to set up the required permissions and create the training data. If you are using your own source data, make sure that your data is formatted like the prerequisites.
+ Set up your Amazon SDK for Python (Boto3) environment as specified in [Setting up the Amazon SDKs](aws-personalize-set-up-sdks.md).

## Tutorial
<a name="gs-python-custom-tutorial"></a>

In the following steps, you verify your environment and create SDK for Python (Boto3) clients for Amazon Personalize. Then you import data, create and deploy a solution version with a campaign, and get recommendations.

### Step 1: Verify your Python environment and create boto3 clients
<a name="gs-python-example"></a>

After you complete the prerequisites, run the following Python example to confirm that your environment is configured correctly. This code also creates the Amazon Personalize boto3 clients you use in this tutorial. If your environment is configured correctly, a list of the available recipes is displayed, and you can run the other examples in this tutorial.

```
import boto3

personalizeRt = boto3.client('personalize-runtime')
personalize = boto3.client('personalize')

response = personalize.list_recipes()

for recipe in response['recipes']:
    print (recipe)
```

### Step 2: Import data
<a name="getting-started-python-import-dataset"></a>

After you create Amazon Personalize boto3 clients and verify your environment, import the historical data you created when you completed the [Getting started prerequisites](gs-prerequisites.md). To import historical data into Amazon Personalize, do the following:

1. Use the following code to create a schema in Amazon Personalize. Replace `getting-started-schema` with a name for the schema. 

   ```
   import json
   schema = {
     "type": "record",
     "name": "Interactions",
     "namespace": "com.amazonaws.personalize.schema",
     "fields": [
         {
             "name": "USER_ID",
             "type": "string"
         },
         {
             "name": "ITEM_ID",
             "type": "string"
         },
         {
             "name": "TIMESTAMP",
             "type": "long"
         }
     ],
     "version": "1.0"
   }
   
   create_interactions_schema_response = personalize.create_schema(
       name='getting-started-schema',
       schema=json.dumps(schema)
   )
   
   interactions_schema_arn = create_interactions_schema_response['schemaArn']
   print(json.dumps(create_interactions_schema_response, indent=2))
   ```

1. Create a dataset group with the following code. Replace `dataset group name` with a name for the dataset group.

   ```
   response = personalize.create_dataset_group(name = 'dataset group name')
   dataset_group_arn = response['datasetGroupArn']
   
   description = personalize.describe_dataset_group(datasetGroupArn = dataset_group_arn)['datasetGroup']
   
   print('Name: ' + description['name'])
   print('ARN: ' + description['datasetGroupArn'])
   print('Status: ' + description['status'])
   ```

1. Create an Item interactions dataset in your new dataset group with the following code. Give the dataset a name and provide the `schema_arn` and `dataset_group_arn` from the previous steps.

   ```
   response = personalize.create_dataset(
       name = 'datase_name',
       schemaArn = 'schema_arn',
       datasetGroupArn = 'dataset_group_arn',
       datasetType = 'Interactions'
   )
   
   dataset_arn = response['datasetArn']
   ```

1. Import your data with a dataset import job with the following code. The code uses the describe\$1dataset\$1import\$1job method to track the status of the job. 

   Pass the following as parameters: a name for the job, the `dataset_arn` from the previous step, the Amazon S3 bucket path (`s3://bucket name/folder name/ratings.csv`) where you stored the training data, and your IAM service role's ARN. You created this role as part of the [Getting started prerequisites](gs-prerequisites.md). Amazon Personalize needs permission to access the bucket. See [Giving Amazon Personalize access to Amazon S3 resources](granting-personalize-s3-access.md). 

   ```
   import time
   response = personalize.create_dataset_import_job(
       jobName = 'JobName',
       datasetArn = 'dataset_arn',
       dataSource = {'dataLocation':'s3://amzn-s3-demo-bucket/filename.csv'},
       roleArn = 'role_arn',
       importMode = 'FULL'
   )
   
   dataset_interactions_import_job_arn = response['datasetImportJobArn']
   
   description = personalize.describe_dataset_import_job(
       datasetImportJobArn = dataset_interactions_import_job_arn)['datasetImportJob']
   
   print('Name: ' + description['jobName'])
   print('ARN: ' + description['datasetImportJobArn'])
   print('Status: ' + description['status'])
   
   max_time = time.time() + 3*60*60 # 3 hours
   while time.time() < max_time:
       describe_dataset_import_job_response = personalize.describe_dataset_import_job(
           datasetImportJobArn = dataset_interactions_import_job_arn
       )
       status = describe_dataset_import_job_response["datasetImportJob"]['status']
       print("Interactions DatasetImportJob: {}".format(status))
       
       if status == "ACTIVE" or status == "CREATE FAILED":
           break
           
       time.sleep(60)
   ```

### Step 3: Create a solution
<a name="getting-started-python-create-solution"></a>

After importing your data, you create a solution and solution version as follows. The *solution* contains the configurations to train a model and a *solution version* is a trained model. 

1.  Create a new solution with the following code. Pass the following as parameters: the `dataset_group_arn` from earlier, a name for the solution, and the ARN for the User-Personalization-v2 recipe (`arn:aws:personalize:::recipe/aws-user-personalization-v2`). Store the ARN of your new solution for later use. 

   ```
   create_solution_response = personalize.create_solution(
     name='solution name', 
     recipeArn= 'arn:aws:personalize:::recipe/aws-user-personalization-v2', 
     datasetGroupArn = 'dataset group arn'
   )
   solution_arn = create_solution_response['solutionArn']
   print('solution_arn: ', solution_arn)
   ```

1. Create a solution version with the following code. Pass as a parameter the `solution_arn` from the previous step. The following code creates a solution version. During training, the code uses the [DescribeSolutionVersion](API_DescribeSolutionVersion.md) operation to retrieve the solution version's status. When training is complete, the method returns the ARN of your new solution version. Store it for later use. 

   ```
   import time
   import json
   
   create_solution_version_response = personalize.create_solution_version(
       solutionArn = solution_arn
   )
   
   solution_version_arn = create_solution_version_response['solutionVersionArn']
   print(json.dumps(create_solution_version_response, indent=2))
   
   max_time = time.time() + 3*60*60 # 3 hours
   while time.time() < max_time:
       describe_solution_version_response = personalize.describe_solution_version(
           solutionVersionArn = solution_version_arn
       )
       status = describe_solution_version_response["solutionVersion"]["status"]
       print("SolutionVersion: {}".format(status))
       
       if status == "ACTIVE" or status == "CREATE FAILED":
           break
           
       time.sleep(60)
   ```

### Step 4: Create a campaign
<a name="getting-started-python-deploy-solution"></a>

After you create your solution version, deploy it with an Amazon Personalize campaign. Use the following code to create a campaign that deploys your solution version. Pass the following as parameters: the `solution_version_arn`, and a name for the campaign. The method returns the Amazon Resource Name (ARN) of your new campaign. Store it for later use.

```
response = personalize.create_campaign(
    name = 'campaign name',
    solutionVersionArn = 'solution version arn'
)

arn = response['campaignArn']

description = personalize.describe_campaign(campaignArn = arn)['campaign']
print('Name: ' + description['name'])
print('ARN: ' + description['campaignArn'])
print('Status: ' + description['status'])
```

### Step 5: Get recommendations
<a name="getting-started-python-get-recommendations"></a>

After you create a campaign, you can use it to get recommendations. The following code shows how to get recommendations from a campaign and print out each recommended item's ID. Pass the ARN of the campaign you created in the previous step. For user ID, you pass the ID of a user that from the training data, such as `123`.

```
response = personalizeRt.get_recommendations(
    campaignArn = 'Campaign ARN',
    userId = '123',
    numResults = 10
)

print("Recommended items")
for item in response['itemList']:
    print (item['itemId'])
```

## Getting started using Amazon Personalize APIs with Jupyter (iPython) notebooks
<a name="gs-jupyter-notebook"></a>

 To get started using Amazon Personalize using Jupyter notebooks, clone or download a series of notebooks found in the [getting\$1started](https://github.com/aws-samples/amazon-personalize-samples/tree/master/getting_started) folder of the [Amazon Personalize samples](https://github.com/aws-samples/amazon-personalize-samples) repository. The notebooks walk you through importing training data, creating a solution, creating a campaign, and getting recommendations using Amazon Personalize.

**Note**  
 Before starting with the notebooks, make sure to build your environment following the steps in the [README.md](https://github.com/aws-samples/amazon-personalize-samples/blob/master/getting_started/README.md) 

# Getting started (SDK for Java 2.x)
<a name="getting-started-java"></a>

This tutorial shows you how to complete the Amazon Personalize workflow from start to finish with the Amazon SDK for Java 2.x. 

When you finish the getting started exercise, to avoid incurring unnecessary charges, delete the resources that you created. For more information, see [Requirements for deleting Amazon Personalize resources](deleting-resources.md). 

For more examples, see [Complete Amazon Personalize project](#gs-java-example).

**Topics**
+ [

## Prerequisites
](#gs-java-prerequisites)
+ [

## Complete Amazon Personalize project
](#gs-java-example)

## Prerequisites
<a name="gs-java-prerequisites"></a>

The following are prerequisite steps for completing this tutorial:
+ Complete the [Getting started prerequisites](gs-prerequisites.md), to set up the required permissions and create the training data. You can use the same source data used in the [Getting started (console)](getting-started-console.md) or [Getting started (Amazon CLI)](getting-started-cli.md) exercises. If you are using your own source data, make sure that your data is formatted like in the prerequisites.
+ Set up your SDK for Java 2.x environment and Amazon credentials as specified in the [Setting up the Amazon SDK for Java 2.x](https://docs.amazonaws.cn/sdk-for-java/latest/developer-guide/setup.html) procedure in the *Amazon SDK for Java 2.x Developer Guide*. 

### Tutorial
<a name="gs-custom-java-tutorial"></a>

In the following steps you set up your project to use Amazon Personalize packages and create Amazon Personalize SDK for Java 2.x clients. Then you import data, create and deploy a solution version with a campaign, and get recommendations.

#### Step 1: Set up your project to use Amazon Personalize packages
<a name="gs-java-set-up-project"></a>

After you complete the prerequisites, add Amazon Personalize dependencies to your pom.xml file and import Amazon Personalize packages. 

1.  Add the following dependencies to your pom.xml file. The latest version numbers may be different than the example code. 

   ```
   <dependency>
   	<groupId>software.amazon.awssdk</groupId>
   	<artifactId>personalize</artifactId>
   	<version>2.16.83</version>
   </dependency>
   <dependency>
   	<groupId>software.amazon.awssdk</groupId>
   	<artifactId>personalizeruntime</artifactId>
   	<version>2.16.83</version>
   </dependency>
   <dependency>
   	<groupId>software.amazon.awssdk</groupId>
   	<artifactId>personalizeevents</artifactId>
   	<version>2.16.83</version>
   </dependency>
   ```

1.  Add the following import statements to your project. 

   ```
   // import client packages
   import software.amazon.awssdk.services.personalize.PersonalizeClient;
   import software.amazon.awssdk.services.personalizeruntime.PersonalizeRuntimeClient;
   // Amazon Personalize exception package
   import software.amazon.awssdk.services.personalize.model.PersonalizeException;
   // schema packages
   import software.amazon.awssdk.services.personalize.model.CreateSchemaRequest;
   // dataset group packages
   import software.amazon.awssdk.services.personalize.model.CreateDatasetGroupRequest;
   import software.amazon.awssdk.services.personalize.model.DescribeDatasetGroupRequest;
   // dataset packages
   import software.amazon.awssdk.services.personalize.model.CreateDatasetRequest;
   // dataset import job packages
   import software.amazon.awssdk.services.personalize.model.CreateDatasetImportJobRequest;
   import software.amazon.awssdk.services.personalize.model.DataSource;
   import software.amazon.awssdk.services.personalize.model.DatasetImportJob;
   import software.amazon.awssdk.services.personalize.model.DescribeDatasetImportJobRequest;
   // solution packages
   import software.amazon.awssdk.services.personalize.model.CreateSolutionRequest;
   import software.amazon.awssdk.services.personalize.model.CreateSolutionResponse;
   // solution version packages
   import software.amazon.awssdk.services.personalize.model.DescribeSolutionRequest;
   import software.amazon.awssdk.services.personalize.model.CreateSolutionVersionRequest;
   import software.amazon.awssdk.services.personalize.model.CreateSolutionVersionResponse;
   import software.amazon.awssdk.services.personalize.model.DescribeSolutionVersionRequest;
   // campaign packages
   import software.amazon.awssdk.services.personalize.model.CreateCampaignRequest;
   import software.amazon.awssdk.services.personalize.model.CreateCampaignResponse;
   // get recommendations packages
   import software.amazon.awssdk.services.personalizeruntime.model.GetRecommendationsRequest;
   import software.amazon.awssdk.services.personalizeruntime.model.GetRecommendationsResponse;
   import software.amazon.awssdk.services.personalizeruntime.model.PredictedItem;
   // Java time utility package
   import java.time.Instant;
   ```

#### Step 2: Create Amazon Personalize clients
<a name="getting-started-java-clients"></a>

After you add Amazon Personalize dependencies to your pom.xml file and import the required packages, create the following Amazon Personalize clients:

```
PersonalizeClient personalizeClient = PersonalizeClient.builder()
  .region(region)
  .build();

PersonalizeRuntimeClient personalizeRuntimeClient = PersonalizeRuntimeClient.builder() 
  .region(region)
  .build();
```

#### Step 3: Import data
<a name="getting-started-java-import-dataset"></a>

After you initialize your Amazon Personalize clients, import the historical data you created when you completed the [Getting started prerequisites](gs-prerequisites.md). To import historical data into Amazon Personalize, do the following:

1.  Save the following Avro schema as a JSON file in your working directory. This schema matches the columns in the CSV file you created when you completed the [Getting started prerequisites](gs-prerequisites.md). 

   ```
   {
     "type": "record",
     "name": "Interactions",
     "namespace": "com.amazonaws.personalize.schema",
     "fields": [
         {
             "name": "USER_ID",
             "type": "string"
         },
         {
             "name": "ITEM_ID",
             "type": "string"
         },
         {
             "name": "TIMESTAMP",
             "type": "long"
         }
     ],
     "version": "1.0"
   }
   ```

1. Use the following `createSchema` method to create a schema in Amazon Personalize. Pass the following as parameters: an Amazon Personalize service client, the name for your schema, and the file path for the schema JSON file you created in the previous step. The method returns the Amazon Resource Name (ARN) of your new schema. Store it for later use. 

   ```
       public static String createSchema(PersonalizeClient personalizeClient, String schemaName, String filePath) {
   
           String schema = null;
           try {
               schema = new String(Files.readAllBytes(Paths.get(filePath)));
           } catch (IOException e) {
               System.out.println(e.getMessage());
           }
   
           try {
               CreateSchemaRequest createSchemaRequest = CreateSchemaRequest.builder()
                       .name(schemaName)
                       .schema(schema)
                       .build();
   
               String schemaArn = personalizeClient.createSchema(createSchemaRequest).schemaArn();
   
               System.out.println("Schema arn: " + schemaArn);
   
               return schemaArn;
   
           } catch (PersonalizeException e) {
               System.err.println(e.awsErrorDetails().errorMessage());
               System.exit(1);
           }
           return "";
       }
   ```

1. Create a dataset group. Use the following `createDatasetGroup` method to create a dataset group. Pass the following as parameters: an Amazon Personalize service client and the name for the dataset group. The method returns the ARN of your new dataset group. Store it for later use.

   ```
       public static String createDatasetGroup(PersonalizeClient personalizeClient, String datasetGroupName) {
   
           try {
               CreateDatasetGroupRequest createDatasetGroupRequest = CreateDatasetGroupRequest.builder()
                       .name(datasetGroupName)
                       .build();
               return personalizeClient.createDatasetGroup(createDatasetGroupRequest).datasetGroupArn();
           } catch (PersonalizeException e) {
               System.out.println(e.awsErrorDetails().errorMessage());
           }
           return "";
       }
   ```

1. Create an Item interactions dataset. Use the following `createDataset` method to create an Item interactions dataset. Pass the following as parameters: an Amazon Personalize service client, the name for your dataset, your schema's ARN, your dataset group's ARN, and `Interactions` for the dataset type. The method returns the ARN of your new dataset. Store it for later use.

   ```
       public static String createDataset(PersonalizeClient personalizeClient,
               String datasetName,
               String datasetGroupArn,
               String datasetType,
               String schemaArn) {
           try {
               CreateDatasetRequest request = CreateDatasetRequest.builder()
                       .name(datasetName)
                       .datasetGroupArn(datasetGroupArn)
                       .datasetType(datasetType)
                       .schemaArn(schemaArn)
                       .build();
   
               String datasetArn = personalizeClient.createDataset(request)
                       .datasetArn();
               System.out.println("Dataset " + datasetName + " created.");
               return datasetArn;
   
           } catch (PersonalizeException e) {
               System.err.println(e.awsErrorDetails().errorMessage());
               System.exit(1);
           }
           return "";
       }
   ```

1. Import your data with a dataset import job. Use the following `createPersonalizeDatasetImportJob` method to create a dataset import job. 

   Pass the following as parameters: an Amazon Personalize service client, a name for the job, your Item interactions dataset's ARN, the Amazon S3 bucket path (`s3://bucket name/folder name/ratings.csv`) where you stored the training data, and your service role's ARN (you created this role as part of the [Getting started prerequisites](gs-prerequisites.md)). The method returns the ARN of your dataset import job. Optionally store it for later use. 

   ```
       public static String createPersonalizeDatasetImportJob(PersonalizeClient personalizeClient,
               String jobName,
               String datasetArn,
               String s3BucketPath,
               String roleArn) {
   
           long waitInMilliseconds = 60 * 1000;
           String status;
           String datasetImportJobArn;
   
           try {
               DataSource importDataSource = DataSource.builder()
                       .dataLocation(s3BucketPath)
                       .build();
   
               CreateDatasetImportJobRequest createDatasetImportJobRequest = CreateDatasetImportJobRequest.builder()
                       .datasetArn(datasetArn)
                       .dataSource(importDataSource)
                       .jobName(jobName)
                       .roleArn(roleArn)
                       .build();
   
               datasetImportJobArn = personalizeClient.createDatasetImportJob(createDatasetImportJobRequest)
                       .datasetImportJobArn();
               DescribeDatasetImportJobRequest describeDatasetImportJobRequest = DescribeDatasetImportJobRequest.builder()
                       .datasetImportJobArn(datasetImportJobArn)
                       .build();
   
               long maxTime = Instant.now().getEpochSecond() + 3 * 60 * 60;
   
               while (Instant.now().getEpochSecond() < maxTime) {
   
                   DatasetImportJob datasetImportJob = personalizeClient
                           .describeDatasetImportJob(describeDatasetImportJobRequest)
                           .datasetImportJob();
   
                   status = datasetImportJob.status();
                   System.out.println("Dataset import job status: " + status);
   
                   if (status.equals("ACTIVE") || status.equals("CREATE FAILED")) {
                       break;
                   }
                   try {
                       Thread.sleep(waitInMilliseconds);
                   } catch (InterruptedException e) {
                       System.out.println(e.getMessage());
                   }
               }
               return datasetImportJobArn;
   
           } catch (PersonalizeException e) {
               System.out.println(e.awsErrorDetails().errorMessage());
           }
           return "";
       }
   ```

#### Step 4: Create a solution
<a name="getting-started-java-create-solution"></a>

After you import your data, you create a solution and solution version as follows. The *solution* contains the configurations to train a model and a *solution version* is a trained model. 

1. Create a new solution with the following `createPersonalizeSolution` method. Pass the following as parameters: an Amazon Personalize service client, your dataset groups Amazon Resource Name (ARN), a name for the solution, and the ARN for the User-Personalization-v2 recipe (`arn:aws:personalize:::recipe/aws-user-personalization-v2`). The method returns the ARN your new solution. Store it for later use. 

   ```
       public static String createPersonalizeSolution(PersonalizeClient personalizeClient,
               String datasetGroupArn,
               String solutionName,
               String recipeArn) {
   
           try {
               CreateSolutionRequest solutionRequest = CreateSolutionRequest.builder()
                       .name(solutionName)
                       .datasetGroupArn(datasetGroupArn)
                       .recipeArn(recipeArn)
                       .build();
   
               CreateSolutionResponse solutionResponse = personalizeClient.createSolution(solutionRequest);
               return solutionResponse.solutionArn();
   
           } catch (PersonalizeException e) {
               System.err.println(e.awsErrorDetails().errorMessage());
               System.exit(1);
           }
           return "";
       }
   ```

1. Create a solution version with the following `createPersonalizeSolutionVersion` method. Pass as a parameter the ARN of the solution the previous step. The following code first checks to see if your solution is ready and then creates a solution version. During training, the code uses the [DescribeSolutionVersion](API_DescribeSolutionVersion.md) operation to retrieve the solution version's status. When training is complete, the method returns the ARN of your new solution version. Store it for later use. 

   ```
       public static String createPersonalizeSolutionVersion(PersonalizeClient personalizeClient, String solutionArn) {
           long maxTime = 0;
           long waitInMilliseconds = 30 * 1000; // 30 seconds
           String solutionStatus = "";
           String solutionVersionStatus = "";
           String solutionVersionArn = "";
   
           try {
               DescribeSolutionRequest describeSolutionRequest = DescribeSolutionRequest.builder()
                       .solutionArn(solutionArn)
                       .build();
   
               maxTime = Instant.now().getEpochSecond() + 3 * 60 * 60;
   
               // Wait until solution is active.
               while (Instant.now().getEpochSecond() < maxTime) {
   
                   solutionStatus = personalizeClient.describeSolution(describeSolutionRequest).solution().status();
                   System.out.println("Solution status: " + solutionStatus);
   
                   if (solutionStatus.equals("ACTIVE") || solutionStatus.equals("CREATE FAILED")) {
                       break;
                   }
                   try {
                       Thread.sleep(waitInMilliseconds);
                   } catch (InterruptedException e) {
                       System.out.println(e.getMessage());
                   }
               }
   
               if (solutionStatus.equals("ACTIVE")) {
   
                   CreateSolutionVersionRequest createSolutionVersionRequest = CreateSolutionVersionRequest.builder()
                           .solutionArn(solutionArn)
                           .build();
   
                   CreateSolutionVersionResponse createSolutionVersionResponse = personalizeClient
                           .createSolutionVersion(createSolutionVersionRequest);
                   solutionVersionArn = createSolutionVersionResponse.solutionVersionArn();
   
                   System.out.println("Solution version ARN: " + solutionVersionArn);
   
                   DescribeSolutionVersionRequest describeSolutionVersionRequest = DescribeSolutionVersionRequest.builder()
                           .solutionVersionArn(solutionVersionArn)
                           .build();
   
                   while (Instant.now().getEpochSecond() < maxTime) {
   
                       solutionVersionStatus = personalizeClient.describeSolutionVersion(describeSolutionVersionRequest)
                               .solutionVersion().status();
                       System.out.println("Solution version status: " + solutionVersionStatus);
   
                       if (solutionVersionStatus.equals("ACTIVE") || solutionVersionStatus.equals("CREATE FAILED")) {
                           break;
                       }
                       try {
                           Thread.sleep(waitInMilliseconds);
                       } catch (InterruptedException e) {
                           System.out.println(e.getMessage());
                       }
                   }
                   return solutionVersionArn;
               }
           } catch (PersonalizeException e) {
               System.err.println(e.awsErrorDetails().errorMessage());
               System.exit(1);
           }
           return "";
       }
   ```

For more information, see [Manually creating a solution version](creating-a-solution-version.md). When you create a solution version, you can evaluate its performance before proceeding. For more information, see [Evaluating an Amazon Personalize solution version with metrics](working-with-training-metrics.md).

#### Step 5: Create a campaign
<a name="getting-started-java-deploy-solution"></a>

After you train and evaluate your solution version, deploy it with an Amazon Personalize campaign. Use the following `createPersonalCampaign` method to deploy a solution version. Pass the following as parameters: an Amazon Personalize service client, the Amazon Resource Name (ARN) of the solution version you created in the previous step, and a name for the campaign. The method returns the ARN of your new campaign. Store it for later use.

```
public static String createPersonalCompaign(PersonalizeClient personalizeClient, String solutionVersionArn, String name) {

    try {
        CreateCampaignRequest createCampaignRequest = CreateCampaignRequest.builder()
            .minProvisionedTPS(1)
            .solutionVersionArn(solutionVersionArn)
            .name(name)
            .build();

        CreateCampaignResponse campaignResponse = personalizeClient.createCampaign(createCampaignRequest);
        System.out.println("The campaign ARN is "+campaignResponse.campaignArn());
        return campaignResponse.campaignArn();

    } catch (PersonalizeException e) {
        System.err.println(e.awsErrorDetails().errorMessage());
        System.exit(1);
    }
}
```

For more information about Amazon Personalize campaigns, see [Deploying an Amazon Personalize solution version with a campaignCreating a campaign](campaigns.md).

#### Step 6: Get recommendations
<a name="getting-started-java-get-recommendations"></a>

After you create a campaign, you use it to get recommendations. Use the following `getRecs` method to get recommendations for a user. Pass as parameters an Amazon Personalize runtime client, the Amazon Resource Name (ARN) of the campaign you created in the previous step, and a user ID (for example, `123`) from the historical data you imported. The method prints the list of recommended items to the screen.

```
    public static void getRecs(PersonalizeRuntimeClient personalizeRuntimeClient, String campaignArn, String userId) {

        try {
            GetRecommendationsRequest recommendationsRequest = GetRecommendationsRequest.builder()
                    .campaignArn(campaignArn)
                    .numResults(20)
                    .userId(userId)
                    .build();

            GetRecommendationsResponse recommendationsResponse = personalizeRuntimeClient
                    .getRecommendations(recommendationsRequest);
            List<PredictedItem> items = recommendationsResponse.itemList();
            for (PredictedItem item : items) {
                System.out.println("Item Id is : " + item.itemId());
                System.out.println("Item score is : " + item.score());
            }

        } catch (AwsServiceException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```

## Complete Amazon Personalize project
<a name="gs-java-example"></a>

For an all-in-one project that shows you how to complete the Amazon Personalize workflow with the SDK for Java 2.x, see the [Amazon-Personalize-Java-App](https://github.com/seashman/Amazon-Personalize-Java-App) on GitHub. This project includes training multiple solution versions with different recipes, and recording events with the PutEvents operation.

 For additional examples, see code the found in the [personalize](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javav2/example_code/personalize/src/main/java/com/example/personalize) folder of the Amazon SDK examples repository. 