

# Getting started with a Domain dataset group
<a name="getting-started-domain"></a>

 In this getting started tutorial you create a Domain dataset group for the VIDEO\$1ON\$1DEMAND domain, import interactions data from a CSV file, and create a recommender with the *Top picks for you* use case. Then you use the recommender to get personalized movie recommendations for a user. 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 depending on how you want to create Amazon Personalize resources, proceed to [Getting started with a Domain dataset group (console)](getting-started-console-domain.md), [Getting started with a Domain dataset group (SDK for Python (Boto3))](getting-started-domain-python.md), [Getting started with a Domain dataset group (SDK for Java 2.x)](domain-getting-started-java.md), or [Getting started with a Domain dataset group (SDK for JavaScript v3)](getting-started-domain-js.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 with a Domain dataset group (console)](getting-started-console-domain.md)
+ [Getting started with a Domain dataset group (SDK for Java 2.x)](domain-getting-started-java.md)
+ [Getting started with a Domain dataset group (SDK for Python (Boto3))](getting-started-domain-python.md)
+ [Getting started with a Domain dataset group (SDK for JavaScript v3)](getting-started-domain-js.md)

# Getting started with a Domain dataset group (console)
<a name="getting-started-console-domain"></a>

In this exercise, you use the Amazon Personalize console to create a Domain dataset group and a recommender 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 Domain dataset group
<a name="getting-started-console-import-dataset-domain"></a>

 In this procedure you create Domain dataset group for the VIDEO\$1ON\$1DEMAND domain, create an Item interactions dataset with the default schema for the VIDEO\$1ON\$1DEMAND domain, and import the item interactions data you created in [Creating the training data (Domain dataset group)](gs-prerequisites.md#gs-data-prep-domain). 

**To create a Domain dataset group**

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

1. In the navigation pane, choose **Create dataset group**.

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

1.  For **Domain**, choose **Video on demand**. The domain you choose determines the default schema you use when importing data. It also determines what use cases are available for recommenders. Your screen should look similar to the following.   
![\[Depicts Create dataset group page with Name and Domain fields.\]](http://docs.aws.amazon.com/personalize/latest/dg/images/gs-domain-1-create-dsg.png)

1. Choose **Create dataset group**. The Overview page appears. Proceed to [Step 2: Import data](#getting-started-import-data-domain).

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

 In this procedure you create an Item interactions dataset with the default VIDEO\$1ON\$1DEMAND domain schema. Then you import the item interactions data you created in [Creating the training data (Domain dataset group)](gs-prerequisites.md#gs-data-prep-domain). 

**To import data**

1. On the Overview page, 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 schema** page, for **Dataset name** provide a name for your Item interactions dataset. 

1. For **Dataset schema**, choose **Create a new domain schema by modifying the existing default schema for your domain** and enter a name for the schema. The **Schema definition** updates to display the default schema for the VIDEO\$1ON\$1DEMAND domain. Leave the schema unchanged. Your screen should look similar to the following.   
![\[Depicts the Configure item interactions schema page with dataset and schema fields.\]](http://docs.aws.amazon.com/personalize/latest/dg/images/gs-domain-2-create-dataset.png)

1. Choose **Next**. The **Configure item interactions dataset import job** page appears.

1. On the **Configure item interactions dataset import job** page, leave the **Data import source** unchanged as **Import data from S3**.

1. For **Dataset import job name**, give your import job a name.

1. In **Data import source**, specify where your data is stored in Amazon Simple Storage Service (S3). Use the following syntax:

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

1. In **IAM role**, for **IAM service role** choose **Enter a custom IAM role ARN** and enter the Amazon Resource Name (ARN) of the role you created in [Creating an IAM role for Amazon Personalize](set-up-required-permissions.md#set-up-create-role-with-permissions). Your screen should look similar to the following.  
![\[Depicts the Configure item interactions dataset import job page with import job fields.\]](http://docs.aws.amazon.com/personalize/latest/dg/images/gs-domain-3-import-job.png)

1. Choose **Start import** to import data. The **Overview** page for your Domain dataset group appears. Note the status of the import in the **Set up datasets** section. When the status is `Interaction data active` proceed to [Step 3: Create a recommender](#getting-started-console-create-recommenders).

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

In this procedure, you create a recommender for the *Top picks for you* use case for the VIDEO\$1ON\$1DEMAND domain.

**To create a recommender**

1.  On the **Overview** page for your Domain dataset group, in **Step 3** choose the **Use video on demand recommenders** tab and choose **Create recommenders**. 

1. On the **Choose use case** page, choose **Top picks for you** and provide a **Recommender name**. Your screen should appear similar to the following.  
![\[Depicts the Choose use case page with a list use case options to choose.\]](http://docs.aws.amazon.com/personalize/latest/dg/images/gs-domain-4-create-recommender.png)

1. Choose **Next**.

1. Leave the fields on the **Advanced configuration** page unchanged and choose **Next**.

1. Review the recommender details and choose **Create recommenders** to create your recommender.

   You can monitor the status of each recommender on the **Recommenders** page. When your recommender status is **Active**, you can use it to get recommendations in [Step 4: Get recommendations](#getting-started-console-get-recommendations-domain).

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

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

**To get recommendations**

1. On the Overview page for your Domain dataset group, in the navigation pane choose **Recommenders**.

1.  On the **Recommenders** page, choose your recommender. 

1.  At the top right, choose **Test**. 

1. In **Recommendation parameters**, enter a user ID. Leave the other fields unchanged.

1. Choose **Get recommendations**. A table containing the user’s top 25 recommended items appears. Your screen should look similar to the following.  
![\[Depicts the Test recommender page with fields for a recommendation request.\]](http://docs.aws.amazon.com/personalize/latest/dg/images/gs-domain-5-get-recc.png)

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

This tutorial shows you how to use the SDK for Java 2.x to create a Domain dataset group for the VIDEO\$1ON\$1DEMAND domain. In this tutorial, you create a recommender for the *Top picks for you* use case.

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). 

## Prerequisites
<a name="domain-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. If you also completed the [Getting started with a Domain dataset group (console)](getting-started-console-domain.md), you can reuse the same source data. 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 AWS credentials as specified in the [Setting up the AWS SDK for Java 2.x](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/setup.html) procedure in the *AWS SDK for Java 2.x Developer Guide*. 

## Tutorial
<a name="gs-java-domain-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 a recommender for the *Top picks for you* use case, and get recommendations.

### Step 1: Set up your project to use Amazon Personalize packages
<a name="domain-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;
   // recommender packages
   import software.amazon.awssdk.services.personalize.model.CreateRecommenderRequest;
   import software.amazon.awssdk.services.personalize.model.CreateRecommenderResponse;
   import software.amazon.awssdk.services.personalize.model.DescribeRecommenderRequest;
   // 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="domain-gs-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="domain-gs-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 that you created when you completed the [Creating the training data (Domain dataset group)](gs-prerequisites.md#gs-data-prep-domain). 

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

1. Use the following `createDomainSchema` method to create a domain schema in Amazon Personalize. Pass the following as parameters: an Amazon Personalize service client, the name for your schema, `VIDEO_ON_DEMAND` for the domain, and the file path for the schema JSON file that 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 createDomainSchema(PersonalizeClient personalizeClient, String schemaName, String domain,
               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)
                       .domain(domain)
                       .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 `createDomainDatasetGroup` method to create a domain dataset group. Pass the following as parameters: an Amazon Personalize service client, a name for the dataset group, and pass `VIDEO_ON_DEMAND` for the domain. The method returns the ARN of your new dataset group. Store it for later use.

   ```
       public static String createDomainDatasetGroup(PersonalizeClient personalizeClient,
               String datasetGroupName,
               String domain) {
   
           try {
               CreateDatasetGroupRequest createDatasetGroupRequest = CreateDatasetGroupRequest.builder()
                       .name(datasetGroupName)
                       .domain(domain)
                       .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, and your Interactions dataset's ARN. Pass 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 recommender
<a name="domain-gs-create-recommender"></a>

After your dataset import job completes, you are ready create a recommender. Use the following `createRecommender` method to create a recommender. Pass the following as parameters: an Amazon Personalize service client, a name for the recommender, your dataset group's Amazon Resource Name (ARN), and `arn:aws:personalize:::recipe/aws-vod-top-picks` for the recipe ARN. The method returns the ARN of your new recommender. Store it for later use.

```
    public static String createRecommender(PersonalizeClient personalizeClient,
            String name,
            String datasetGroupArn,
            String recipeArn) {

        long maxTime = 0;
        long waitInMilliseconds = 30 * 1000; // 30 seconds
        String recommenderStatus = "";

        try {
            CreateRecommenderRequest createRecommenderRequest = CreateRecommenderRequest.builder()
                    .datasetGroupArn(datasetGroupArn)
                    .name(name)
                    .recipeArn(recipeArn)
                    .build();

            CreateRecommenderResponse recommenderResponse = personalizeClient
                    .createRecommender(createRecommenderRequest);
            String recommenderArn = recommenderResponse.recommenderArn();
            System.out.println("The recommender ARN is " + recommenderArn);

            DescribeRecommenderRequest describeRecommenderRequest = DescribeRecommenderRequest.builder()
                    .recommenderArn(recommenderArn)
                    .build();

            maxTime = Instant.now().getEpochSecond() + 3 * 60 * 60;

            while (Instant.now().getEpochSecond() < maxTime) {

                recommenderStatus = personalizeClient.describeRecommender(describeRecommenderRequest).recommender()
                        .status();
                System.out.println("Recommender status: " + recommenderStatus);

                if (recommenderStatus.equals("ACTIVE") || recommenderStatus.equals("CREATE FAILED")) {
                    break;
                }
                try {
                    Thread.sleep(waitInMilliseconds);
                } catch (InterruptedException e) {
                    System.out.println(e.getMessage());
                }
            }
            return recommenderArn;

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

### Step 5: Get recommendations
<a name="domain-gs-java-get-recommendations"></a>

After you create a recommender, 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 recommender you created in the previous step, and a user ID (for example, `123`). The method prints the list of recommended items to the screen. 

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

        try {
            GetRecommendationsRequest recommendationsRequest = GetRecommendationsRequest.builder()
                    .recommenderArn(recommenderArn)
                    .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);
        }
    }
```

# Getting started with a Domain dataset group (SDK for Python (Boto3))
<a name="getting-started-domain-python"></a>

This tutorial shows you how to use the SDK for Python (Boto3) to create a Domain dataset group for the VIDEO\$1ON\$1DEMAND domain. In this tutorial, you create a recommender for the *Top picks for you* use case.

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-domain-prerequisites)
+ [Tutorial](#gs-python-tutorial)
+ [Getting started using Amazon Personalize APIs with Jupyter (iPython) notebooks](#gs-jupyter-domain-notebook)

## Prerequisites
<a name="gs-sdk-domain-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 in the prerequisites.
+ Set up your AWS SDK for Python (Boto3) environment as specified in [Setting up the AWS SDKs](aws-personalize-set-up-sdks.md).

## Tutorial
<a name="gs-python-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 a recommender for the *Top picks for you* use case, and get recommendations.

### Step 1: Verify your Python environment and create boto3 clients
<a name="gs-python-domain-verify-environment"></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 that 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-domain-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 `gs-domain-interactions-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": "EVENT_TYPE",
             "type": "string"
         },
         {
             "name": "TIMESTAMP",
             "type": "long"
         }
     ],
     "version": "1.0"
   }
   
   create_interactions_schema_response = personalize.create_schema(
       name='gs-domain-interactions-schema',
       schema=json.dumps(schema),
       domain='VIDEO_ON_DEMAND'
   )
   
   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',
     domain = 'VIDEO_ON_DEMAND'
   )
   dsg_arn = response['datasetGroupArn']
   
   description = personalize.describe_dataset_group(datasetGroupArn = dsg_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 = 'interactions-dataset-name',
       schemaArn = interactions_schema_arn,
       datasetGroupArn = dsg_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. For information on granting access, 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'
   )
   
   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 4: Create a recommender
<a name="domain-gs-py-create-recommender"></a>

After your dataset import job completes, you are ready create a recommender. Use the following code to create a recommender. Pass the following as parameters: a name for the recommender, your dataset group's Amazon Resource Name (ARN), and `arn:aws:personalize:::recipe/aws-vod-top-picks` for the recipe ARN. The code uses the describe\$1recommender method to track the status of the recommender.

```
import time
create_recommender_response = personalize.create_recommender(
  name = 'gs-python-top-picks',
  recipeArn = 'arn:aws:personalize:::recipe/aws-vod-top-picks',
  datasetGroupArn = dsg_arn     
)
recommender_arn = create_recommender_response['recommenderArn']

print('Recommender ARN:' + recommender_arn)
max_time = time.time() + 3*60*60 # 3 hours
while time.time() < max_time:

    version_response = personalize.describe_recommender(
        recommenderArn = recommender_arn
    )
    status = version_response["recommender"]["status"]

    if status == "ACTIVE":
        print("Creation succeeded for {}".format(recommender_arn))
        
    elif status == "CREATE FAILED":
        print("Creation failed for {}".format(recommender_arn))

    if status == "ACTIVE":
        break
    else:
        print("Recommender creation is still in progress")
        
    time.sleep(60)
```

### Step 5: Get recommendations
<a name="domain-gs-py-get-recommendations"></a>

After you create a recommender, you use it to get recommendations with the following code. Pass as parameters the Amazon Resource Name (ARN) of the recommender you created in the previous step, and a user ID (for example, `123`). The method prints the list of recommended items. 

```
response = personalizeRt.get_recommendations(
    recommenderArn = "arn:aws:personalize:us-west-2:014025156336:recommender/gs-python-top-picks-89",
    userId = '123'
)
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-domain-notebook"></a>

 To get started creating Domain dataset groups with Jupyter notebooks, clone or download a series of notebooks found in the [notebooks\$1managed\$1domains](https://github.com/aws-samples/amazon-personalize-samples/tree/master/getting_started/notebooks_managed_domains) 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 recommender, and getting recommendations with 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 with a Domain dataset group (SDK for JavaScript v3)
<a name="getting-started-domain-js"></a>

This tutorial shows you how to use the AWS SDK for JavaScript v3 to create a Domain dataset group for the VIDEO\$1ON\$1DEMAND domain. In this tutorial, you create a recommender for the *Top picks for you* use case.

 To view the code used in this tutorial on GitHub, see [Amazon Personalize code examples for SDK for JavaScript v3](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/personalize) in the* AWS SDK Code Examples* repository.

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-js-sdk-domain-prerequisites)
+ [Tutorial](#domain-gs-js-domain-tutorial)

## Prerequisites
<a name="gs-js-sdk-domain-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. If you also completed the [Getting started with a Domain dataset group (console)](getting-started-console-domain.md), you can reuse the same source data. If you are using your own source data, make sure that your data is formatted like in the prerequisites.
+ Set up the SDK for JavaScript and AWS credentials as specified in the [Setting up the SDK for JavaScript](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-up.html) procedure in the *AWS SDK for JavaScript Developer Guide*. 

## Tutorial
<a name="domain-gs-js-domain-tutorial"></a>

In the following steps, you install the required dependencies. Then you create a dataset group, import data, create a recommender for the *Top picks for you* use case, and get recommendations.

If you use Node.js, you can run each code sample by saving the sample as a JavaScript file and then running `node <fileName.js>`.

### Step 1: Install Amazon Personalize dependencies
<a name="domain-gs-js-install-dependencies"></a>

After you complete the prerequisites, install the following Amazon Personalize dependencies:
+ @aws-sdk/client-personalize
+ @aws-sdk/client-personalize-runtime
+ @aws-sdk/client-personalize-events (optional for this tutorial, but required if you want to [record events](recording-events.md) after you create your recommender)

The following is an example of a `package.json` file you can use. To install the dependencies with Node.js, navigate to where you saved the `package.json` file and run `npm install`.

```
{
  "name": "personalize-js-project",
  "version": "1.0.0",
  "description": "personalize operations",
  "type": "module",
  "author": "Author Name <email@address.com>",
  "license": "ISC",
  "dependencies": {
    "@aws-sdk/client-personalize": "^3.350.0",
    "@aws-sdk/client-personalize-events": "^3.350.0",
    "@aws-sdk/client-personalize-runtime": "^3.350.0",
    "fs": "^0.0.1-security"
  },
  "compilerOptions": {
    "resolveJsonModule": true,
    "esModuleInterop": true
  }
}
```

### Step 2: Create Amazon Personalize clients
<a name="domain-gs-js-clients"></a>

After you install the dependencies, create your Amazon Personalize clients. In this tutorial, the code samples assume you create the clients in a file named `personalizeClients.js` stored in a directory named `libs`. 

The following is an example of a `personalizeClient.js` file.

```
import { PersonalizeClient } from "@aws-sdk/client-personalize";
import { PersonalizeRuntimeClient } from "@aws-sdk/client-personalize-runtime";
import { PersonalizeEventsClient } from "@aws-sdk/client-personalize-events";
// Set your AWS region.
const REGION = "region"; //e.g. "us-east-1"

const personalizeClient = new PersonalizeClient({ region: REGION});
const personalizeEventsClient = new PersonalizeEventsClient({ region: REGION});
const personalizeRuntimeClient = new PersonalizeRuntimeClient({ region: REGION});

export { personalizeClient, personalizeEventsClient, personalizeRuntimeClient };
```

### Step 3: Import data
<a name="domain-gs-js-import-dataset"></a>

After you create 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 that you created when you completed the [Creating the training data (Domain dataset group)](gs-prerequisites.md#gs-data-prep-domain). 

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

1. Create a domain schema in Amazon Personalize with the following `createDomainSchema.js` code. Replace `SCHEMA_PATH` with the path to the schema.json file you just created. Update the `createSchemaParam` to specify a name for the schema, and for `domain` specify `VIDEO_ON_DEMAND`. 

   ```
   // Get service clients module and commands using ES6 syntax.
   import { CreateSchemaCommand } from "@aws-sdk/client-personalize";
   import { personalizeClient } from "./libs/personalizeClients.js";
   
   // Or, create the client here.
   // const personalizeClient = new PersonalizeClient({ region: "REGION"});
   
   import fs from "node:fs";
   
   const schemaFilePath = "SCHEMA_PATH";
   let mySchema = "";
   
   try {
     mySchema = fs.readFileSync(schemaFilePath).toString();
   } catch (err) {
     mySchema = "TEST"; // for unit tests.
   }
   
   // Set the domain schema parameters.
   export const createDomainSchemaParam = {
     name: "NAME" /* required */,
     schema: mySchema /* required */,
     domain:
       "DOMAIN" /* required for a domain dataset group, specify ECOMMERCE or VIDEO_ON_DEMAND */,
   };
   
   export const run = async () => {
     try {
       const response = await personalizeClient.send(
         new CreateSchemaCommand(createDomainSchemaParam),
       );
       console.log("Success", response);
       return response; // For unit tests.
     } catch (err) {
       console.log("Error", err);
     }
   };
   run();
   ```

1. Create a domain dataset group in Amazon Personalize with the following `createDomainDatasetGroup.js` code. Update the `domainDatasetGroupParams` to specify a name for the dataset group, and for `domain` specify `VIDEO_ON_DEMAND`.

   ```
   // Get service clients module and commands using ES6 syntax.
   import { CreateDatasetGroupCommand } from "@aws-sdk/client-personalize";
   import { personalizeClient } from "./libs/personalizeClients.js";
   
   // Or, create the client here.
   // const personalizeClient = new PersonalizeClient({ region: "REGION"});
   
   // Set the domain dataset group parameters.
   export const domainDatasetGroupParams = {
     name: "NAME" /* required */,
     domain:
       "DOMAIN" /* required for a domain dsg, specify ECOMMERCE or VIDEO_ON_DEMAND */,
   };
   
   export const run = async () => {
     try {
       const response = await personalizeClient.send(
         new CreateDatasetGroupCommand(domainDatasetGroupParams),
       );
       console.log("Success", response);
       return response; // For unit tests.
     } catch (err) {
       console.log("Error", err);
     }
   };
   run();
   ```

1. Create an Item interactions dataset in Amazon Personalize with the following `createDataset.js` code. Update the `createDatasetParam` to specify the Amazon Resource Name (ARN) of the dataset group and schema you just created, give the dataset a name, and for `datasetType`, specify `Interactions`.

   ```
   // Get service clients module and commands using ES6 syntax.
   import { CreateDatasetCommand } from "@aws-sdk/client-personalize";
   import { personalizeClient } from "./libs/personalizeClients.js";
   
   // Or, create the client here.
   // const personalizeClient = new PersonalizeClient({ region: "REGION"});
   
   // Set the dataset's parameters.
   export const createDatasetParam = {
     datasetGroupArn: "DATASET_GROUP_ARN" /* required */,
     datasetType: "DATASET_TYPE" /* required */,
     name: "NAME" /* required */,
     schemaArn: "SCHEMA_ARN" /* required */,
   };
   
   export const run = async () => {
     try {
       const response = await personalizeClient.send(
         new CreateDatasetCommand(createDatasetParam),
       );
       console.log("Success", response);
       return response; // For unit tests.
     } catch (err) {
       console.log("Error", err);
     }
   };
   run();
   ```

1. Import your data with the following `createDatasetImportJob.js` code. Update the `datasetImportJobParam` to specify the following: 
   + Specify a name for the job and specify your Interactions dataset's ARN.
   + For `dataLocation`, specify the Amazon S3 bucket path (`s3://https://amzn-s3-demo-bucket.s3.region-code.amazonaws.com/folder name/ratings.csv`) where you stored the training data.
   + For `roleArn` specify the Amazon Resource Name for your Amazon Personalize service role. You created this role as part of the [Getting started prerequisites](gs-prerequisites.md).

   ```
   // Get service clients module and commands using ES6 syntax.
   import { CreateDatasetImportJobCommand } from "@aws-sdk/client-personalize";
   import { personalizeClient } from "./libs/personalizeClients.js";
   
   // Or, create the client here.
   // const personalizeClient = new PersonalizeClient({ region: "REGION"});
   
   // Set the dataset import job parameters.
   export const datasetImportJobParam = {
     datasetArn: "DATASET_ARN" /* required */,
     dataSource: {
       /* required */
       dataLocation: "S3_PATH",
     },
     jobName: "NAME" /* required */,
     roleArn: "ROLE_ARN" /* required */,
   };
   
   export const run = async () => {
     try {
       const response = await personalizeClient.send(
         new CreateDatasetImportJobCommand(datasetImportJobParam),
       );
       console.log("Success", response);
       return response; // For unit tests.
     } catch (err) {
       console.log("Error", err);
     }
   };
   run();
   ```

### Step 4: Create a recommender
<a name="domain-gs-js-create-recommender"></a>

After your dataset import job completes, you are ready create a recommender. To create a recommender, use the following `createRecommender.js` code. Update the `createRecommenderParam` with the following: Specify a name for the recommender, specify your dataset group's ARN, and for `recipeArn` specify `arn:aws:personalize:::recipe/aws-vod-top-picks`.

```
// Get service clients module and commands using ES6 syntax.
import { CreateRecommenderCommand } from "@aws-sdk/client-personalize";
import { personalizeClient } from "./libs/personalizeClients.js";

// Or, create the client here.
// const personalizeClient = new PersonalizeClient({ region: "REGION"});

// Set the recommender's parameters.
export const createRecommenderParam = {
  name: "NAME" /* required */,
  recipeArn: "RECIPE_ARN" /* required */,
  datasetGroupArn: "DATASET_GROUP_ARN" /* required */,
};

export const run = async () => {
  try {
    const response = await personalizeClient.send(
      new CreateRecommenderCommand(createRecommenderParam),
    );
    console.log("Success", response);
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

### Step 5: Get recommendations
<a name="domain-gs-js-get-recommendations"></a>

After you create a recommender, you use it to get recommendations. Use the following `getRecommendations.js` code to get recommendations for a user. Update the `getRecommendationsParam` to specify the ARN of the recommender you created in the previous step, and specify a user ID (for example, `123`). 

```
// Get service clients module and commands using ES6 syntax.
import { GetRecommendationsCommand } from "@aws-sdk/client-personalize-runtime";
import { personalizeRuntimeClient } from "./libs/personalizeClients.js";
// Or, create the client here.
// const personalizeRuntimeClient = new PersonalizeRuntimeClient({ region: "REGION"});

// Set the recommendation request parameters.
export const getRecommendationsParam = {
  recommenderArn: "RECOMMENDER_ARN" /* required */,
  userId: "USER_ID" /* required */,
  numResults: 15 /* optional */,
};

export const run = async () => {
  try {
    const response = await personalizeRuntimeClient.send(
      new GetRecommendationsCommand(getRecommendationsParam),
    );
    console.log("Success!", response);
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```